blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3eb23e4458d6fd9e7e2ae05b7717752591dc970b | fb1b5cce9785d13a8925a46b69f73fca9e318fe5 | /kadanes-algorithm.cpp | e6d8472a1aede5d3efe30d943df76d13010a7545 | [] | no_license | ankurssharma96/Competitive-solutions | 72c0f280d0598ebe1733ac02a7056dd1bc4d2294 | 7abcad978c8eed05f6e431d59d519ac61da0c509 | refs/heads/master | 2021-05-08T13:43:30.658392 | 2018-08-18T18:15:11 | 2018-08-18T18:15:11 | 120,032,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int m_h=0,m_f=0;
for(int i=0;i<n;i++){
m_h+=a[i];
if(m_h<0){
m_h=0;
}
else if(m_h>m_f){
m_f=m_h;
}
}
sort(a,a+n);
if(m_f==0){
cout<<a[n-1]<<endl;
}
else{
cout<<m_f<<endl;
}
}
}
| [
"[email protected]"
] | |
5bca36f8996e4385c1e4d60ea9a4086eb88163a7 | 3d5a63c935fbc61f89f16a3d9d308ac0d652400d | /282A.cpp | ad50cc220dd407161f1cacfe4c2267bf7f27e795 | [] | no_license | shutterberg/CodeForces | 374f80b89591557b49fccce114b70f4c461660f1 | 6738c51016a6cffc503361741045ca283b3b27a3 | refs/heads/main | 2023-07-10T20:30:19.183488 | 2021-08-03T05:53:54 | 2021-08-03T05:53:54 | 379,151,763 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | #include<bits/stdc++.h>
#define init ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
using namespace std;
int main()
{
init;
int n=0,temp=0;
string s;
cin>>n;
while(n--){
cin>>s;
if(s[1]=='+')
++temp;
else
--temp;
}
cout<<temp;
return 0;
} | [
"[email protected]"
] | |
a038876612b730d3439d3cc4963a706af2ebec82 | d09a764c0409a65c736ae1aebbf20b7448e532e7 | /main.cpp | 70bbe01aaebc4360c2538d7ddfdae98508ceab83 | [
"Apache-2.0"
] | permissive | miachm/Snake | 131907a29643bcc0cf5b8546a587b3150168ae68 | 3d4c99cb1a56d885e0deb7eae9186c41bec164d8 | refs/heads/master | 2021-01-19T02:53:58.486127 | 2017-05-14T21:25:51 | 2017-05-14T21:25:51 | 61,800,421 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 841 | cpp | #include "Modelo.hpp"
#include "Menu.hpp"
#include <iostream>
#include <cstdlib>
#include <ctime>
/** Modelo de programación actual:
*
* - Objecto Modelo que gestiona los accesos a ventana, deja el decidir "qué" se dibuja a los Controladores.
* - Controladores: Ente que recibe los eventos/refrescos de fotograma y responde en consecuencia llamando
a la API que nos proporciona modelo (dibujar,cerrarventana,addcontroller...).
Problema con esto:
- Se pueden llamar dos veces seguidas a la API (cerrarventana, finishcontroller), con los perjuicios y errores extraños que
eso resulta.
*/
int main()
{
try
{
std::srand(std::time(0));
Modelo modelo(new Menu(&modelo));
}
catch(const char* c)
{
std::cout<<"Excepcion ocurrida: "<<c<<std::endl;
}
//std::cin.get();
return 0;
}
| [
"[email protected]"
] | |
27de59557bde4cc94f417925263e42ef95bd1b78 | 78d1f09868d34ba6d167b245419b0012885ffb3d | /BanDienThoai/invoice_detail.h | 83e68da723deaa21ce91189141aa33a49848dd59 | [] | no_license | ngovandong/SellSmartPhoneSystem | b356eb0b0c39870c13490583cc58540646714f75 | 3c1219ed62e4c89cf28acea00dcf25a136cfe350 | refs/heads/main | 2023-06-15T02:38:15.377040 | 2021-07-10T06:24:53 | 2021-07-10T06:24:53 | 314,524,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | h | #pragma once
#include <string>
#include <iostream>
#include "smartphone.h"
#include <vector>
using namespace std;
class invoice;
class invoice_detail
{
int invoice_id;
int smartphone_id;
int qty;
int unit_price;
smartphone* SM;
public:
invoice_detail(int = 0, int = 0, int = 0, int = 0);
~invoice_detail();
int getInvoiceID();
void setSmartphone(vector<smartphone>&);
friend ostream& operator<<(ostream&, const invoice&);
};
| [
"[email protected]"
] | |
6b13bc201fc7e13dd42333c3cd55befc108ce41d | 7b3d4dff3945584460dc474a8bb8fe8fd9bdb625 | /exercises/6/Seminar_04 & 05 - Car Dealership/ManufactureDetails.cpp | be21adb707c4ed1e9216aa736a6c41ef54dca48f | [
"MIT"
] | permissive | triffon/oop-2019-20 | 305535b006cb19e96c9c58d47737a28135fc666e | ec3e5488859d8140de5aa5090811cd0e1318d952 | refs/heads/master | 2022-05-13T07:04:22.306200 | 2022-03-19T09:49:17 | 2022-03-19T09:49:45 | 241,474,762 | 21 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 2,264 | cpp | #include "ManufactureDetails.h"
#include <string.h>
#include <iostream>
#define MAX_BUFF (1 << 10)
ManufactureDetails::ManufactureDetails()
{
std::cout << "Default Constuctor ManufactureDetails" << std::endl;
this->init( "", "", 0 );
}
ManufactureDetails::ManufactureDetails( const char* name, const char* model, unsigned int year) :
fName(new char[ strlen(name) + 1 ])
{
std::cout << "Constuctor with parameters ManufactureDetails" << std::endl;
this->init( name, model, year );
}
ManufactureDetails::ManufactureDetails( const ManufactureDetails& other)
{
std::cout << "Copy Constuctor ManufactureDetails" << std::endl;
if ( this != &other )
{
this->init( other.fName, other.fModel, other.fYear );
}
}
ManufactureDetails& ManufactureDetails::operator=( const ManufactureDetails& other )
{
std::cout << "operator= ManufactureDetails" << std::endl;
if ( this != &other )
{
this->clean();
this->init( other.fName, other.fModel, other.fYear );
}
return *this;
}
ManufactureDetails::~ManufactureDetails()
{
std::cout << "Destructor ManufactureDetails" << std::endl;
this->clean();
}
//=================================================================
void ManufactureDetails::print() const
{
std::cout << fName << std::endl;
std::cout << fModel << std::endl;
std::cout << fYear << std::endl;
}
void ManufactureDetails::readFromConsole()
{
std::cout << "Enter a name of manufacture: " << std::endl;
char name[ MAX_BUFF + 1 ];
std::cin.getline( name, MAX_BUFF );
std::cout << "Enter a name of model: " << std::endl;
char model[ MAX_BUFF + 1 ];
std::cin.getline( model, MAX_BUFF );
std::cout << "Еnter the year of production: " << std::endl;
unsigned int year;
std::cin >> year;
this->init( name, model, year );
}
void ManufactureDetails::init( const char* name, const char* model, unsigned int year)
{
if ( name )
{
fName = new char[ strlen(name) + 1 ];
strcpy( fName, name );
}
if ( model )
{
fModel = new char[ strlen(model) + 1 ];
strcpy( fModel, model );
}
if ( year < CAR_FIRST_YEAR )
{
fYear = CAR_FIRST_YEAR;
}
else if ( year > CURRENT_YEAR )
{
fYear = CURRENT_YEAR;
}
else
{
fYear = year;
}
}
void ManufactureDetails::clean()
{
delete[] fName;
delete[] fModel;
fYear = 0;
}
| [
"[email protected]"
] | |
e04979b7428569dd5f355da31374ced488c96c12 | 7e3c043ac83bbbc8fe7548423f3a33c02df992c3 | /src/map.cpp | f4cfe96d3dced17f234b1082e2f1dfe9e510d27d | [] | no_license | Naurislv/P11-Path-Planning-Project | f3707bc48f3dbd34a6a57ae0324af9c15f186211 | 7859a82d13f0d10a7d368239ef15219a1b6714ad | refs/heads/master | 2021-01-01T17:12:27.601239 | 2017-08-18T20:15:47 | 2017-08-18T20:15:47 | 98,023,107 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,593 | cpp | // Local include
#include "map.h"
using namespace std;
/**
* Initializes Map
*/
Map::Map() {}
Map::~Map() {}
void Map::load_data(string file_path) {
cout << "Loading map data from file.." << endl;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
// Waypoint map to read from
string map_file_ = file_path;
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
ifstream in_map_(map_file_.c_str(), ifstream::in);
string line;
while (getline(in_map_, line)) {
istringstream iss(line);
double x;
double y;
float s;
float d_x;
float d_y;
iss >> x;
iss >> y;
iss >> s;
iss >> d_x;
iss >> d_y;
map_x.push_back(x);
map_y.push_back(y);
map_s.push_back(s);
map_dx.push_back(d_x);
map_dy.push_back(d_y);
}
map_size = map_x.size();
cout << "Map size: " << map_size << endl;
}
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> Map::getXY(double s, double d)
{
int prev_wp = -1;
while(s > map_s[prev_wp+1] && (prev_wp < (int)(map_s.size()-1) ))
{
prev_wp++;
}
int wp2 = (prev_wp + 1) % map_x.size();
double heading = atan2((map_y[wp2]-map_y[prev_wp]),(map_x[wp2]-map_x[prev_wp]));
// the x,y,s along the segment
double seg_s = (s-map_s[prev_wp]);
double seg_x = map_x[prev_wp]+seg_s*cos(heading);
double seg_y = map_y[prev_wp]+seg_s*sin(heading);
double perp_heading = heading-M_PI/2;
double x = seg_x + d*cos(perp_heading);
double y = seg_y + d*sin(perp_heading);
return {x,y};
}
double Map::distance(double x1, double y1, double x2, double y2)
{
return sqrt((x2 - x1)*(x2 - x1) + (y2 - y1) * (y2 - y1));
}
int Map::ClosestWaypoint(double x, double y)
{
double closestLen = 100000; //large number
int closestWaypoint = 0;
for(int i = 0; i < map_x.size(); i++)
{
double maps_x = map_x[i];
double maps_y = map_y[i];
double dist = distance(x, y, maps_x, maps_y);
if(dist < closestLen)
{
closestLen = dist;
closestWaypoint = i;
}
}
return closestWaypoint;
}
int Map::NextWaypoint(double x, double y, double theta)
{
int closestWaypoint = ClosestWaypoint(x,y);
double maps_x = map_x[closestWaypoint];
double maps_y = map_y[closestWaypoint];
double heading = atan2( (maps_y-y),(maps_x-x) );
double angle = abs(theta-heading);
if(angle > M_PI/4)
{
closestWaypoint++;
}
return closestWaypoint;
}
// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> Map::getFrenet(double x, double y, double theta)
{
int next_wp = NextWaypoint(x,y, theta);
int prev_wp;
prev_wp = next_wp-1;
if(next_wp == 0)
{
prev_wp = map_x.size()-1;
}
double n_x = map_x[next_wp]-map_x[prev_wp];
double n_y = map_y[next_wp]-map_y[prev_wp];
double x_x = x - map_x[prev_wp];
double x_y = y - map_y[prev_wp];
// find the projection of x onto n
double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y);
double proj_x = proj_norm*n_x;
double proj_y = proj_norm*n_y;
double frenet_d = distance(x_x,x_y,proj_x,proj_y);
//see if d value is positive or negative by comparing it to a center point
double center_x = 1000-map_x[prev_wp];
double center_y = 2000-map_y[prev_wp];
double centerToPos = distance(center_x,center_y,x_x,x_y);
double centerToRef = distance(center_x,center_y,proj_x,proj_y);
if(centerToPos <= centerToRef)
{
frenet_d *= -1;
}
// calculate s value
double frenet_s = 0;
for(int i = 0; i < prev_wp; i++)
{
frenet_s += distance(map_x[i],map_y[i],map_x[i+1],map_y[i+1]);
}
frenet_s += distance(0,0,proj_x,proj_y);
return {frenet_s,frenet_d};
} | [
"[email protected]"
] | |
4a109a95424f0d04d5643a9b52ca2a290392c55b | 4c25432a6d82aaebd82fd48e927317b15a6bf6ab | /data/dataset_2017/dataset_2017_8_formatted/minaminao/3264486_5736519012712448_minaminao.cpp | cc5c0194d29d3ba2127254156a26d7a0367b91c2 | [] | no_license | wzj1988tv/code-imitator | dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933 | 07a461d43e5c440931b6519c8a3f62e771da2fc2 | refs/heads/master | 2020-12-09T05:33:21.473300 | 2020-01-09T15:29:24 | 2020-01-09T15:29:24 | 231,937,335 | 1 | 0 | null | 2020-01-05T15:28:38 | 2020-01-05T15:28:37 | null | UTF-8 | C++ | false | false | 1,441 | cpp | #include "bits/stdc++.h"
using namespace std;
#ifdef _DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif
//#define int long long
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define rrep(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define all(c) begin(c), end(c)
const int INF =
sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)(1e9) + 7;
template <class T> bool chmax(T &a, const T &b) {
if (a < b) {
a = b;
return true;
}
return false;
}
template <class T> bool chmin(T &a, const T &b) {
if (b < a) {
a = b;
return true;
}
return false;
}
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
freopen("A-small-attempt0.in", "r", stdin);
freopen("A-small-attempt0.txt", "w", stdout);
int T;
cin >> T;
for (int t = 0; t < T; t++) {
string S;
cin >> S;
int n = S.size();
vector<bool> v(n);
rep(i, 0, n) v[i] = S[i] == '+';
int K;
cin >> K;
int ans = 0;
rep(i, 0, n) {
if (i + K > n)
break;
if (v[i])
continue;
ans++;
rep(j, i, i + K) { v[j] = !v[j]; }
// dump(v);
}
bool flag = true;
rep(i, 0, n) if (!v[i]) flag = false;
cout << "Case #" << t + 1 << ": ";
if (flag) {
cout << ans << endl;
} else {
cout << "IMPOSSIBLE" << endl;
}
}
return 0;
} | [
"[email protected]"
] | |
86c918937324d3af2dd7742e0c27f394ea467a19 | 05099a30fcb1d738c7f34ec7c3dd3f3484e9c8e1 | /mav_control_interface/include/mav_control_interface/position_controller_interface.h | 86eae20f047f7d4e1cfbc845697b827a528ccc5a | [
"Apache-2.0"
] | permissive | caomuqing/mav_control_rw | a326c877b8987d82d9365b205c66b70b47133baf | 95beac589cb88b0040d5db1453ede9de952fb283 | refs/heads/master | 2023-01-21T23:08:13.576983 | 2023-01-07T05:11:06 | 2023-01-07T05:11:06 | 205,482,778 | 1 | 0 | Apache-2.0 | 2019-08-31T02:13:17 | 2019-08-31T02:13:17 | null | UTF-8 | C++ | false | false | 2,050 | h | /*
* Copyright (c) 2015, Markus Achtelik, ASL, ETH Zurich, Switzerland
* You can contact the author at <markus dot achtelik at mavt dot ethz dot ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef POSITION_CONTROLLER_INTERFACE_H_
#define POSITION_CONTROLLER_INTERFACE_H_
#include <mav_msgs/conversions.h>
#include <mav_msgs/eigen_mav_msgs.h>
#include <nav_msgs/Odometry.h>
namespace mav_control_interface {
class PositionControllerInterface {
public:
PositionControllerInterface();
virtual ~PositionControllerInterface();
virtual std::string getName() const = 0;
virtual bool getUseAttitudeQuaternionCommand() const = 0;
virtual double getMass() const = 0;
virtual bool setReference(const mav_msgs::EigenTrajectoryPoint& reference) = 0;
virtual bool setReferenceArray(const mav_msgs::EigenTrajectoryPointDeque& reference_array);
virtual bool setOdometry(const mav_msgs::EigenOdometry& odometry) = 0;
virtual bool getCurrentReference(mav_msgs::EigenTrajectoryPoint* reference) const = 0;
virtual bool getCurrentReference(mav_msgs::EigenTrajectoryPointDeque* reference) const = 0;
virtual bool getPredictedState(mav_msgs::EigenTrajectoryPointDeque* predicted_state) const = 0;
virtual bool calculateRollPitchYawrateThrustCommand(
mav_msgs::EigenRollPitchYawrateThrust* attitude_thrust_command);
virtual bool calculateAttitudeThrustCommand(mav_msgs::EigenAttitudeThrust* attitude_thrust_command);
};
} /* namespace mav_flight_manager */
#endif /* POSITION_CONTROLLER_INTERFACE_H_ */
| [
"[email protected]"
] | |
0354dc2481fe256c87591958d8e69a104cb38550 | 7066dcb660114afb0ef58ead07cfc80b49c3edf4 | /round_260/A.cpp | acaebafc36a7e2085bba60be0ec5884028e95776 | [] | no_license | Stomach-ache/Codeforces | 816d8360ae064a131831c1234fc88779e0c5bed3 | 051c5a83c8bd33b918b081c2b0903b9791221783 | refs/heads/master | 2021-01-15T18:46:15.707385 | 2015-03-11T07:40:24 | 2015-03-11T07:40:24 | 16,538,550 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 959 | cpp | /*************************************************************************
> File Name: A.cpp
> Author: Stomach_ache
> Mail: [email protected]
> Created Time: 2014年08月08日 星期五 23时32分05秒
> Propose:
************************************************************************/
#include <cmath>
#include <string>
#include <cstdio>
#include <fstream>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, int> pii;
const int maxn = 100002;
#define x first
#define y second
pii a[maxn];
int n;
bool vis[maxn];
int main(void) {
while (~scanf("%d", &n)) {
for (int i = 0; i < n; i++)
scanf("%d %d", &a[i].x, &a[i].y);
sort(a, a + n);
bool flag = false;
memset(vis, false, sizeof(vis));
for (int i = 1; i < n; i++) {
if (a[i].y < a[i-1].y) {
flag = true;
break;
}
}
if (flag) puts("Happy Alex");
else puts("Poor Alex");
}
return 0;
}
| [
"[email protected]"
] | |
d66c9bce3924b9d9535e52cff6de0497ea7c734e | 198031f9d9336b9daec1a46d238fdfa3436522e7 | /Dev/Cpp/Effekseer/Effekseer/Effekseer.EffectNodeRing.h | eab7a6a202489ec7da434f34f407fe0ebadf9237 | [
"MS-PL",
"MIT",
"IJG",
"GD"
] | permissive | dmitsuki/Effekseer | c242f4f311fe21191eed7298cfaa55a5161c2e81 | ca63e358bde2370d41a2831f7b9a259a6fb28653 | refs/heads/master | 2021-01-24T07:31:33.298415 | 2017-06-09T19:16:57 | 2017-06-09T19:16:57 | 93,346,975 | 0 | 0 | null | 2017-06-04T23:09:40 | 2017-06-04T23:09:40 | null | UTF-8 | C++ | false | false | 5,675 | h |
#ifndef __EFFEKSEER_ParameterNODE_RING_H__
#define __EFFEKSEER_ParameterNODE_RING_H__
//----------------------------------------------------------------------------------
// Include
//----------------------------------------------------------------------------------
#include "Effekseer.EffectNode.h"
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
namespace Effekseer
{
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
struct RingSingleParameter
{
enum
{
Fixed = 0,
Random = 1,
Easing = 2,
Parameter_DWORD = 0x7fffffff,
} type;
union
{
float fixed;
random_float random;
easing_float easing;
};
};
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
struct RingLocationParameter
{
enum
{
Fixed = 0,
PVA = 1,
Easing = 2,
Parameter_DWORD = 0x7fffffff,
} type;
union
{
struct
{
vector2d location;
} fixed;
struct
{
random_vector2d location;
random_vector2d velocity;
random_vector2d acceleration;
} pva;
easing_vector2d easing;
};
};
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
struct RingColorParameter
{
enum
{
Fixed = 0,
Random = 1,
Easing = 2,
Parameter_DWORD = 0x7fffffff,
} type;
union
{
color fixed;
random_color random;
easing_color easing;
};
};
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
struct RingSingleValues
{
float current;
union
{
struct
{
} fixed;
struct
{
} random;
struct
{
float start;
float end;
} easing;
};
};
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
struct RingLocationValues
{
vector2d current;
union
{
struct
{
} fixed;
struct
{
vector2d start;
vector2d velocity;
vector2d acceleration;
} pva;
struct
{
vector2d start;
vector2d end;
} easing;
};
};
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
struct RingColorValues
{
color current;
color original;
union
{
struct
{
} fixed;
struct
{
} random;
struct
{
color start;
color end;
} easing;
};
};
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
class EffectNodeRing
: public EffectNodeImplemented
{
friend class Manager;
friend class Effect;
friend class Instance;
public:
struct InstanceValues
{
RingSingleValues viewingAngle;
RingLocationValues outerLocation;
RingLocationValues innerLocation;
RingSingleValues centerRatio;
RingColorValues outerColor;
RingColorValues centerColor;
RingColorValues innerColor;
};
public:
AlphaBlendType AlphaBlend;
BillboardType Billboard;
int32_t VertexCount;
RingSingleParameter ViewingAngle;
RingLocationParameter OuterLocation;
RingLocationParameter InnerLocation;
RingSingleParameter CenterRatio;
RingColorParameter OuterColor;
RingColorParameter CenterColor;
RingColorParameter InnerColor;
int RingTexture;
EffectNodeRing( Effect* effect, unsigned char*& pos )
: EffectNodeImplemented(effect, pos)
{
}
~EffectNodeRing()
{
}
void LoadRendererParameter(unsigned char*& pos, Setting* setting);
void BeginRendering(int32_t count, Manager* manager);
void Rendering(const Instance& instance, Manager* manager);
void EndRendering(Manager* manager);
void InitializeRenderedInstance(Instance& instance, Manager* manager);
void UpdateRenderedInstance(Instance& instance, Manager* manager);
eEffectNodeType GetType() const { return EFFECT_NODE_TYPE_RING; }
private:
void LoadSingleParameter( unsigned char*& pos, RingSingleParameter& param );
void LoadLocationParameter( unsigned char*& pos, RingLocationParameter& param );
void LoadColorParameter( unsigned char*& pos, RingColorParameter& param );
void InitializeSingleValues(const RingSingleParameter& param, RingSingleValues& values, Manager* manager);
void InitializeLocationValues(const RingLocationParameter& param, RingLocationValues& values, Manager* manager);
void InitializeColorValues(const RingColorParameter& param, RingColorValues& values, Manager* manager);
void UpdateSingleValues( Instance& instance, const RingSingleParameter& param, RingSingleValues& values );
void UpdateLocationValues( Instance& instance, const RingLocationParameter& param, RingLocationValues& values );
void UpdateColorValues( Instance& instance, const RingColorParameter& param, RingColorValues& values );
};
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#endif // __EFFEKSEER_ParameterNODE_RING_H__
| [
"[email protected]"
] | |
521de6c32f46cac877500c7617d8e483d57ff19f | 72bb98dd565173b718d71e8a6e027699c8f188db | /include/PHYSICAL_CONST.hh | 125dda231563d9f0d0c9d5ee00fa7f6eb52dfd1a | [] | no_license | GengisGreg/physics | a43c5d04accfe326ff1704bb0f83931c1daea042 | 2dcf35bce8d461bd899e600d915681809f354a00 | refs/heads/master | 2021-01-10T22:52:05.188814 | 2016-10-08T16:40:51 | 2016-10-08T16:40:51 | 70,344,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 526 | hh | #ifndef PHYSICAL_CONST
#define PHYSICAL_CONST
class Physics
{
public:
static const double htc = 197.327053; // Mev*fm
static const double m_e = 0.510999; // MeV
static const double m_p = 938.272; // MeV
static const double m_n = 939.56563; // MeV
static const double e2 = 1.43996518; // MeV*fm
static const double m_nuc = 938.918815; // MeV
static const double htc2om = 20.73553391; // MeV*fm^2
};
#endif
| [
"[email protected]"
] | |
63e97296518af367cb476e35af10e9cf3a9fdfda | a3990ba7173e92c54c09897439406dcbf319d7cf | /NewCode/QuickTurns/QuickTurns.ino | 0b84dbf1f5e4acb4ae8660c29cfa1a0f99715129 | [] | no_license | armadillojoe/UWHPS2017 | 15dba9dff468d71fb4830c24b8e52d214773c314 | ad476333ba49c5ed249fc38aee1496b518d7922e | refs/heads/master | 2021-01-11T05:42:35.674504 | 2017-05-09T00:16:31 | 2017-05-09T00:16:31 | 71,520,385 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 571 | ino | /*
* Jack Gentsch
* UWHPS Electronics Core Code '16-'17
* 2/11/17
* This Arduino sketch acts as the master of the Sub controls network
* Sets PWM timers for 4 rear control fins, requests data from slave joystick via I2C
*/
#include <Servo.h>
Servo x_servo;
Servo y_servo;
int val;
void setup() {
// put your setup code here, to run once:
x_servo.attach(9); //analog pin 1
y_servo.attach(10);
val = 0;
}
void loop() {
// put your main code here, to run repeatedly:
val = (val + 1) % 180;
x_servo.write(val);
y_servo.write(val);
delay(100);
}
| [
"[email protected]"
] | |
5e381d1924d2bcea4f04d3ad25f09c650012a973 | a299a931e99368093f589a45f658f6eba64609d2 | /buildsystem/fastbuild/v0.86/Code/Tools/FBuild/FBuildCore/BFF/Functions/FunctionVCXProject.cpp | e9facb497a0584a7892744a9e598e4a797698a14 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | kasicass/kasicass | 4d4236942a3936b518c53ac59bdb3be3cff9ea44 | b688c670f04bdf2990fc87998e3fd18ddb3b7e35 | refs/heads/master | 2022-12-06T20:43:24.635730 | 2020-04-09T11:44:16 | 2020-04-09T11:44:16 | 883,202 | 13 | 11 | null | 2022-11-22T00:20:44 | 2010-09-02T12:30:02 | C++ | UTF-8 | C++ | false | false | 12,864 | cpp | // FunctionVCXProject
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "Tools/FBuild/FBuildCore/PrecompiledHeader.h"
// FBuild
#include "FunctionVCXProject.h"
#include "Tools/FBuild/FBuildCore/FBuild.h"
#include "Tools/FBuild/FBuildCore/BFF/BFFStackFrame.h"
#include "Tools/FBuild/FBuildCore/BFF/BFFVariable.h"
#include "Tools/FBuild/FBuildCore/Graph/NodeGraph.h"
#include "Tools/FBuild/FBuildCore/Graph/DirectoryListNode.h"
#include "Tools/FBuild/FBuildCore/Graph/VCXProjectNode.h"
// Core
#include "Core/Strings/AStackString.h"
// CONSTRUCTOR
//------------------------------------------------------------------------------
FunctionVCXProject::FunctionVCXProject()
: Function( "VCXProject" )
{
}
// AcceptsHeader
//------------------------------------------------------------------------------
/*virtual*/ bool FunctionVCXProject::AcceptsHeader() const
{
return true;
}
// Commit
//------------------------------------------------------------------------------
/*virtual*/ bool FunctionVCXProject::Commit( const BFFIterator & funcStartIter ) const
{
// required
AStackString<> projectOutput;
AStackString<> rootNamespace;
AStackString<> projectGuid;
AStackString<> defaultLanguage;
AStackString<> applicationEnvironment;
if ( !GetString( funcStartIter, projectOutput, ".ProjectOutput", true ) ||
!GetString( funcStartIter, rootNamespace, ".RootNamespace", false ) ||
!GetString( funcStartIter, projectGuid, ".ProjectGuid", false ) ||
!GetString( funcStartIter, defaultLanguage, ".DefaultLanguage", false ) ||
!GetString( funcStartIter, applicationEnvironment, ".ApplicationEnvironment", false ) )
{
return false;
}
// optional inputs
Array< AString > inputPaths;
Array< AString > inputPathsExclude;
if ( !GetStrings( funcStartIter, inputPaths, ".ProjectInputPaths", false ) ||
!GetStrings( funcStartIter, inputPathsExclude, ".ProjectInputPathsExclude", false ) )
{
return false;
}
// project base
Array< AString > basePaths;
if ( !GetStrings( funcStartIter, basePaths, ".ProjectBasePath", false ) )
{
return false;
}
CleanFolderPaths( basePaths );
// references
Array< AString > references;
Array< AString > projectReferences;
if ( !GetStrings( funcStartIter, references, ".ProjectReferences", false ) ||
!GetStrings( funcStartIter, projectReferences, ".ProjectProjectReferences", false ) )
{
return false;
}
// permitted file extensions
Array< AString > allowedFileExtensions( 8, true );
if ( !GetStrings( funcStartIter, allowedFileExtensions, ".ProjectAllowedFileExtensions", false ) )
{
return true;
}
if ( allowedFileExtensions.IsEmpty() )
{
const char * extensions[] = { ".cpp", ".hpp", ".cxx",".hxx",".c",".h",".cc",".hh",
".cp",".hp",".cs",".inl",".bff",".rc",".resx",".m",".mm",
".cu",
nullptr };
AStackString<> tmp;
const char ** item = extensions;
while ( *item )
{
tmp.Assign( *item );
allowedFileExtensions.Append( tmp );
++item;
}
}
// files and filesToExclude
Array< AString > files( 8, true );
Array< AString > filesToExclude( 8, true );
if ( !GetStrings( funcStartIter, files, ".ProjectFiles", false ) ||
!GetStrings( funcStartIter, filesToExclude, ".ProjectFilesToExclude", false ) )
{
return false;
}
// filetypes
Array< VSProjectFileType > fileTypes;
const BFFVariable * projectFileTypes = BFFStackFrame::GetVar( ".ProjectFileTypes" );
if ( projectFileTypes )
{
if ( projectFileTypes->IsArrayOfStructs() == false )
{
Error::Error_1050_PropertyMustBeOfType( funcStartIter, this, ".ProjectFileTypes", projectFileTypes->GetType(), BFFVariable::VAR_ARRAY_OF_STRUCTS );
return false;
}
const Array< const BFFVariable * > & structs = projectFileTypes->GetArrayOfStructs();
const BFFVariable * const * end = structs.End();
for ( const BFFVariable ** it = structs.Begin(); it != end; ++it )
{
const BFFVariable * s = *it;
VSProjectFileType ft;
// .FileType must be provided
if ( !GetStringFromStruct( s, ".FileType", ft.m_FileType ) )
{
// TODO:B custom error
Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".FileType" ) );
return false;
}
// .Pattern must be provided
if ( !GetStringFromStruct( s, ".Pattern", ft.m_Pattern ) )
{
// TODO:B custom error
Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Pattern" ) );
return false;
}
fileTypes.Append( ft );
}
}
// path cleaning
CleanFolderPaths( inputPaths ); // input paths
CleanFolderPaths( inputPathsExclude ); // exclude paths
CleanFilePaths( files ); // explicit files
// per-config options
VSProjectConfig baseConfig;
// various options
if ( !GetString( funcStartIter, baseConfig.m_BuildCommand, ".ProjectBuildCommand", false ) ||
!GetString( funcStartIter, baseConfig.m_RebuildCommand,".ProjectRebuildCommand", false ) ||
!GetString( funcStartIter, baseConfig.m_CleanCommand, ".ProjectCleanCommand", false ) ||
!GetString( funcStartIter, baseConfig.m_Output, ".Output", false ) ||
!GetString( funcStartIter, baseConfig.m_PreprocessorDefinitions, ".PreprocessorDefinitions", false ) ||
!GetString( funcStartIter, baseConfig.m_IncludeSearchPath, ".IncludeSearchPath", false ) ||
!GetString( funcStartIter, baseConfig.m_ForcedIncludes, ".ForcedIncludes", false ) ||
!GetString( funcStartIter, baseConfig.m_AssemblySearchPath, ".AssemblySearchPath", false ) ||
!GetString( funcStartIter, baseConfig.m_ForcedUsingAssemblies, ".ForcedUsingAssemblies", false ) ||
!GetString( funcStartIter, baseConfig.m_AdditionalOptions, ".AdditionalOptions", false ) ||
!GetString( funcStartIter, baseConfig.m_OutputDirectory, ".OutputDirectory", false ) ||
!GetString( funcStartIter, baseConfig.m_IntermediateDirectory, ".IntermediateDirectory", false ) ||
!GetString( funcStartIter, baseConfig.m_Xbox360DebuggerCommand,".Xbox360DebuggerCommand", false ) ||
!GetString( funcStartIter, baseConfig.m_LayoutDir, ".LayoutDir", false ) ||
!GetString( funcStartIter, baseConfig.m_LayoutExtensionFilter, ".LayoutExtensionFilter", false ) ||
!GetString( funcStartIter, baseConfig.m_DebuggerFlavor, ".DebuggerFlavor", false ) ||
!GetString( funcStartIter, baseConfig.m_AumidOverride, ".AumidOverride", false ) ||
!GetString( funcStartIter, baseConfig.m_PlatformToolset, ".PlatformToolset", false ) ||
!GetString( funcStartIter, baseConfig.m_DeploymentType, ".DeploymentType", false ) ||
!GetString( funcStartIter, baseConfig.m_DeploymentFiles, ".DeploymentFiles", false ) ||
!GetString( funcStartIter, baseConfig.m_LocalDebuggerCommandArguments, ".LocalDebuggerCommandArguments", false ) ||
!GetString( funcStartIter, baseConfig.m_LocalDebuggerWorkingDirectory, ".LocalDebuggerWorkingDirectory", false ) ||
!GetString( funcStartIter, baseConfig.m_LocalDebuggerCommand, ".LocalDebuggerCommand", false ) ||
!GetString( funcStartIter, baseConfig.m_LocalDebuggerEnvironment, ".LocalDebuggerEnvironment", false ) )
{
return false;
}
// create configs
Array< VSProjectConfig > configs( 16, true );
const BFFVariable * projectConfigs = BFFStackFrame::GetVar( ".ProjectConfigs" );
if ( projectConfigs )
{
if ( projectConfigs->IsArrayOfStructs() == false )
{
Error::Error_1050_PropertyMustBeOfType( funcStartIter, this, ".ProjectConfigs", projectConfigs->GetType(), BFFVariable::VAR_ARRAY_OF_STRUCTS );
return false;
}
const Array< const BFFVariable * > & structs = projectConfigs->GetArrayOfStructs();
const BFFVariable * const * end = structs.End();
for ( const BFFVariable ** it = structs.Begin(); it != end; ++it )
{
const BFFVariable * s = *it;
// start with the base configuration
VSProjectConfig newConfig( baseConfig );
// .Platform must be provided
if ( !GetStringFromStruct( s, ".Platform", newConfig.m_Platform ) )
{
// TODO:B custom error
Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Platform" ) );
return false;
}
// .Config must be provided
if ( !GetStringFromStruct( s, ".Config", newConfig.m_Config ) )
{
// TODO:B custom error
Error::Error_1101_MissingProperty( funcStartIter, this, AStackString<>( ".Config" ) );
return false;
}
GetStringFromStruct( s, ".ProjectBuildCommand", newConfig.m_BuildCommand );
GetStringFromStruct( s, ".ProjectRebuildCommand", newConfig.m_RebuildCommand );
GetStringFromStruct( s, ".ProjectCleanCommand", newConfig.m_CleanCommand );
GetStringFromStruct( s, ".Output", newConfig.m_Output );
GetStringFromStruct( s, ".PreprocessorDefinitions", newConfig.m_PreprocessorDefinitions );
GetStringFromStruct( s, ".IncludeSearchPath", newConfig.m_IncludeSearchPath );
GetStringFromStruct( s, ".ForcedIncludes", newConfig.m_ForcedIncludes );
GetStringFromStruct( s, ".AssemblySearchPath", newConfig.m_AssemblySearchPath );
GetStringFromStruct( s, ".ForcedUsingAssemblies", newConfig.m_ForcedUsingAssemblies );
GetStringFromStruct( s, ".AdditionalOptions", newConfig.m_AdditionalOptions );
GetStringFromStruct( s, ".OutputDirectory", newConfig.m_OutputDirectory );
GetStringFromStruct( s, ".IntermediateDirectory", newConfig.m_IntermediateDirectory );
GetStringFromStruct( s, ".LayoutDir", newConfig.m_LayoutDir );
GetStringFromStruct( s, ".LayoutExtensionFilter", newConfig.m_LayoutExtensionFilter );
GetStringFromStruct( s, ".Xbox360DebuggerCommand", newConfig.m_Xbox360DebuggerCommand );
GetStringFromStruct( s, ".DebuggerFlavor", newConfig.m_DebuggerFlavor );
GetStringFromStruct( s, ".AumidOverride", newConfig.m_AumidOverride );
GetStringFromStruct( s, ".PlatformToolset", newConfig.m_PlatformToolset );
GetStringFromStruct( s, ".DeploymentType", newConfig.m_DeploymentType );
GetStringFromStruct( s, ".DeploymentFiles", newConfig.m_DeploymentFiles );
GetStringFromStruct( s, ".LocalDebuggerCommandArguments", newConfig.m_LocalDebuggerCommandArguments );
GetStringFromStruct( s, ".LocalDebuggerWorkingDirectory", newConfig.m_LocalDebuggerWorkingDirectory );
GetStringFromStruct( s, ".LocalDebuggerCommand", newConfig.m_LocalDebuggerCommand );
GetStringFromStruct( s, ".LocalDebuggerEnvironment", newConfig.m_LocalDebuggerEnvironment );
configs.Append( newConfig );
}
}
else
{
// no user specified configs, make some defaults
// start from the default
VSProjectConfig config( baseConfig );
// make the configs
config.m_Platform = "Win32";
config.m_Config = "Debug";
configs.Append( config );
config.m_Config = "Release";
configs.Append( config );
config.m_Platform = "x64";
configs.Append( config );
config.m_Config = "Debug";
configs.Append( config );
}
NodeGraph & ng = FBuild::Get().GetDependencyGraph();
// create all of the DirectoryListNodes we need
AStackString<> inputPattern( "*" );
Dependencies dirNodes( inputPaths.GetSize() );
if ( !GetDirectoryListNodeList( funcStartIter, inputPaths, Array< AString >(), Array< AString >(), true, inputPattern, "ProjectInputPaths", dirNodes ) )
{
return false; // GetDirectoryListNodeList will have emitted an error
}
// Check for existing node
if ( ng.FindNode( projectOutput ) )
{
Error::Error_1100_AlreadyDefined( funcStartIter, this, projectOutput );
return false;
}
VCXProjectNode * pn = ng.CreateVCXProjectNode( projectOutput,
basePaths,
dirNodes,
inputPathsExclude, // TODO:B Remove this (handled by DirectoryListNode now)
allowedFileExtensions,
files,
filesToExclude,
rootNamespace,
projectGuid,
defaultLanguage,
applicationEnvironment,
configs,
fileTypes,
references,
projectReferences );
ASSERT( pn );
return ProcessAlias( funcStartIter, pn );
}
// GetStringFromStruct
//------------------------------------------------------------------------------
bool FunctionVCXProject::GetStringFromStruct( const BFFVariable * s, const char * name, AString & result ) const
{
const Array< const BFFVariable * > & members = s->GetStructMembers();
const BFFVariable * const * end = members.End();
for ( const BFFVariable ** it = members.Begin(); it != end; ++it )
{
const BFFVariable * v = *it;
if ( v->IsString() == false )
{
continue; // ignore non-strings
}
if ( v->GetName() == name )
{
result = v->GetString();
return true; // found
}
}
return false; // not found - caller decides if this is an error
}
//------------------------------------------------------------------------------
| [
"[email protected]"
] | |
848228f241792125316d71a25122806521fa31a5 | 7e791eccdc4d41ba225a90b3918ba48e356fdd78 | /chromium/src/chrome/browser/extensions/api/extension_action/extension_action_prefs_unittest.cc | d307196511cb3b0d689ca8fbb452c99be829aa5d | [
"BSD-3-Clause"
] | permissive | WiViClass/cef-3.2623 | 4e22b763a75e90d10ebf9aa3ea9a48a3d9ccd885 | 17fe881e9e481ef368d9f26e903e00a6b7bdc018 | refs/heads/master | 2021-01-25T04:38:14.941623 | 2017-06-09T07:37:43 | 2017-06-09T07:37:43 | 93,824,379 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,360 | cc | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/logging.h"
#include "base/macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
#include "chrome/browser/extensions/extension_prefs_unittest.h"
#include "chrome/test/base/testing_profile.h"
#include "extensions/common/extension.h"
namespace extensions {
// Tests force hiding browser actions.
class ExtensionPrefsHidingBrowserActions : public ExtensionPrefsTest {
public:
ExtensionPrefsHidingBrowserActions() {}
~ExtensionPrefsHidingBrowserActions() override {}
void Initialize() override {
profile_.reset(new TestingProfile());
// Install 5 extensions.
for (int i = 0; i < 5; i++) {
std::string name = "test" + base::IntToString(i);
extensions_.push_back(prefs_.AddExtension(name));
}
ExtensionActionAPI* action_api = ExtensionActionAPI::Get(profile_.get());
action_api->set_prefs_for_testing(prefs());
for (const scoped_refptr<const Extension>& extension : extensions_)
EXPECT_TRUE(action_api->GetBrowserActionVisibility(extension->id()));
action_api->SetBrowserActionVisibility(extensions_[0]->id(), false);
action_api->SetBrowserActionVisibility(extensions_[1]->id(), true);
}
void Verify() override {
ExtensionActionAPI* action_api = ExtensionActionAPI::Get(profile_.get());
action_api->set_prefs_for_testing(prefs());
// Make sure the one we hid is hidden.
EXPECT_FALSE(action_api->GetBrowserActionVisibility(extensions_[0]->id()));
// Make sure the other id's are not hidden.
ExtensionList::const_iterator iter = extensions_.begin() + 1;
for (; iter != extensions_.end(); ++iter) {
SCOPED_TRACE(base::StringPrintf("Loop %d ",
static_cast<int>(iter - extensions_.begin())));
EXPECT_TRUE(action_api->GetBrowserActionVisibility((*iter)->id()));
}
}
private:
scoped_ptr<TestingProfile> profile_;
ExtensionList extensions_;
DISALLOW_COPY_AND_ASSIGN(ExtensionPrefsHidingBrowserActions);
};
TEST_F(ExtensionPrefsHidingBrowserActions, ForceHide) {}
} // namespace extensions
| [
"[email protected]"
] | |
8edcb5c6ce70538c23a34672009f3644c1e3187d | 254c25b6cc21ff9f245e8c600adf7cde16c210ef | /ConsoleLibrary/MVCController.cpp | d8d25a450df397bbaa06b346c6e7cc26a66d080e | [] | no_license | 492443886/Gomoku | f91b02f39a0c23be83e7e7e9e8d40b6a36048002 | 36775e1a5588506fe2f5c24414fe67ecfd0c0ae6 | refs/heads/main | 2023-02-16T02:28:58.402898 | 2021-01-14T18:54:52 | 2021-01-14T18:54:52 | 329,706,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 506 | cpp | #include "MVControllerApp.hpp"
using namespace std;
void MVControllerApp::EventPump() {
while (!done) {
vector<Event> events = console->getEvents();
for (auto e : events) {
if (e.EventName == "")
continue;
for (size_t i = 0; i < Views.size(); i++)
{
if (Views[i]->isHit(e)) {
std::shared_ptr<Command> command = Views[i]->EventPush(e);
if (command != nullptr)
model->process(command);
}
}
if (e.EventName == "cPressed") {
done = true;
}
}
}
} | [
"[email protected]"
] | |
8b72468d5955c12bde2e9c479c3f1a63028144c3 | 3cd7d2497c20d59b32229bbcd86a669fabc450ba | /hphp/runtime/ext/soap/ext_soap.h | 05ac5993aed878cca2238fe474333caccd2ad29b | [
"PHP-3.01",
"Zend-2.0",
"BSD-3-Clause"
] | permissive | ropik/hhvm | 4b27272a3ffd5a859e1fbb14acf6fd89375dff15 | b1ff97cad475562a8c6da7b8085624d786eed3db | refs/heads/master | 2021-01-18T02:35:56.801050 | 2015-03-19T00:44:45 | 2015-03-19T01:00:30 | 32,500,815 | 2 | 0 | null | 2015-03-19T04:29:25 | 2015-03-19T04:29:22 | null | UTF-8 | C++ | false | false | 6,179 | h | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_EXT_SOAP_H_
#define incl_HPHP_EXT_SOAP_H_
#include "hphp/runtime/ext/extension.h"
#include "hphp/runtime/ext/soap/soap.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
bool HHVM_FUNCTION(use_soap_error_handler,
bool handler = true);
bool HHVM_FUNCTION(is_soap_fault,
const Variant& fault);
int64_t HHVM_FUNCTION(_soap_active_version);
///////////////////////////////////////////////////////////////////////////////
class SoapServer {
public:
SoapServer();
int m_type;
soapFunctions m_soap_functions;
soapClass m_soap_class;
Object m_soap_object;
String m_actor;
String m_uri;
int m_version;
sdl *m_sdl;
xmlCharEncodingHandlerPtr m_encoding;
Array m_classmap;
encodeMap *m_typemap;
int m_features;
Array m_soap_headers;
int m_send_errors;
static const StaticString s_className;
};
///////////////////////////////////////////////////////////////////////////////
class SoapClient {
public:
SoapClient();
int m_soap_version;
sdl *m_sdl;
xmlCharEncodingHandlerPtr m_encoding;
encodeMap *m_typemap;
Array m_classmap;
int m_features;
String m_uri;
String m_location;
int m_style;
int m_use;
String m_login;
String m_password;
int m_authentication;
bool m_digest;
String m_proxy_host;
int m_proxy_port;
String m_proxy_login;
String m_proxy_password;
int m_connection_timeout;
int m_max_redirect;
bool m_use11;
String m_user_agent;
bool m_compression;
Variant m_default_headers;
Array m_cookies;
bool m_exceptions;
Variant m_soap_fault;
bool m_trace;
Variant m_last_request;
Variant m_last_response;
Variant m_last_request_headers;
Variant m_last_response_headers;
Array m_stream_context_options;
static const StaticString s_className;
};
///////////////////////////////////////////////////////////////////////////////
extern const StaticString
s_enc_type, s_enc_value, s_enc_stype,
s_enc_ns, s_enc_name, s_enc_namens;
class SoapVar {
public:
static Class* getClass();
static int64_t getEncType(ObjectData* obj) {
auto enc_type = obj->o_get(s_enc_type, false);
if (!enc_type.isInitialized()) {
raise_error("Encoding: SoapVar has no 'enc_type' property");
not_reached();
assert(false);
}
return enc_type.toInt64();
}
static void setEncType(ObjectData* obj, int64_t t) {
obj->o_set(s_enc_type, t);
}
static Variant getEncValue(ObjectData* obj) {
return obj->o_get(s_enc_value, false);
}
static void setEncValue(ObjectData* obj, const Variant& val) {
obj->o_set(s_enc_value, val);
}
#define X(Name, str_name) \
static void setEnc##Name(ObjectData* obj, const String& str) { \
obj->o_set(s_enc_##str_name, str); \
} \
static String getEnc##Name(ObjectData* obj) { \
return getStrValue(obj, s_enc_##str_name); \
}
X(SType, stype)
X(NS, ns)
X(Name, name)
X(NameNS, namens)
#undef X
private:
static String getStrValue(ObjectData* obj, const String& prop) {
auto str = obj->o_get(prop, false);
if (str.isString()) {
return str.toString();
} else {
return String();
}
}
static Class* s_class;
static const StaticString s_className;
};
///////////////////////////////////////////////////////////////////////////////
class SoapParam {
public:
static Class* getClass();
String m_name;
String m_data;
static Class* s_class;
static const StaticString s_className;
};
///////////////////////////////////////////////////////////////////////////////
class SoapHeader {
public:
static Class* getClass();
String m_namespace;
String m_name;
Variant m_data;
bool m_mustUnderstand;
Variant m_actor;
static Class* s_class;
static const StaticString s_className;
};
///////////////////////////////////////////////////////////////////////////////
}
#endif // incl_HPHP_EXT_SOAP_H_
| [
"[email protected]"
] | |
fa8963e5745cf80e18f873994fb7bde4ed2d51ca | d90bb820a517727f4d3f1972f235d7bbbec2a187 | /cpp/third_party/kmeans/kmeans.cpp | d8c7adfc03697318e25221736d08b0cf333c2dd8 | [] | no_license | umariqb/Multi-Person-Pose-Estimation-using-LJPA-ECCVW-2016 | bf83edce518d0d59ac54ee57d4014062655c9d68 | 9fde830e974b5c5453b77c3a07bbc8a8df3ae9d7 | refs/heads/master | 2021-09-23T09:49:01.864657 | 2018-09-21T08:52:15 | 2018-09-21T08:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 144,683 | cpp | # include <cstdlib>
# include <iostream>
# include <fstream>
# include <iomanip>
# include <cmath>
# include <ctime>
# include <cstring>
using namespace std;
# include "kmeans.hpp"
//****************************************************************************80
char ch_cap ( char ch )
//****************************************************************************80
//
// Purpose:
//
// CH_CAP capitalizes a single character.
//
// Discussion:
//
// This routine should be equivalent to the library "toupper" function.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 July 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, char CH, the character to capitalize.
//
// Output, char CH_CAP, the capitalized character.
//
{
if ( 97 <= ch && ch <= 122 )
{
ch = ch - 32;
}
return ch;
}
//****************************************************************************80
bool ch_eqi ( char ch1, char ch2 )
//****************************************************************************80
//
// Purpose:
//
// CH_EQI is true if two characters are equal, disregarding case.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 June 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, char CH1, CH2, the characters to compare.
//
// Output, bool CH_EQI, is true if the two characters are equal,
// disregarding case.
//
{
if ( 97 <= ch1 && ch1 <= 122 )
{
ch1 = ch1 - 32;
}
if ( 97 <= ch2 && ch2 <= 122 )
{
ch2 = ch2 - 32;
}
return ( ch1 == ch2 );
}
//****************************************************************************80
int ch_to_digit ( char ch )
//****************************************************************************80
//
// Purpose:
//
// CH_TO_DIGIT returns the integer value of a base 10 digit.
//
// Example:
//
// CH DIGIT
// --- -----
// '0' 0
// '1' 1
// ... ...
// '9' 9
// ' ' 0
// 'X' -1
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 June 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, char CH, the decimal digit, '0' through '9' or blank are legal.
//
// Output, int CH_TO_DIGIT, the corresponding integer value. If the
// character was 'illegal', then DIGIT is -1.
//
{
int digit;
if ( '0' <= ch && ch <= '9' )
{
digit = ch - '0';
}
else if ( ch == ' ' )
{
digit = 0;
}
else
{
digit = -1;
}
return digit;
}
//****************************************************************************80
double *cluster_energy_compute ( int dim_num, int point_num, int cluster_num,
double point[], int cluster[], double cluster_center[] )
//****************************************************************************80
//
// Purpose:
//
// CLUSTER_ENERGY_COMPUTE computes the energy of the clusters.
//
// Discussion:
//
// The cluster energy is defined as the sum of the distance
// squared from each point to its cluster center. It is the goal
// of the H-means and K-means algorithms to find, for a fixed number
// of clusters, a clustering that minimizes this energy
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 07 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of data points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the data points.
//
// Input, int CLUSTER[POINT_NUM], the cluster to which each
// data point belongs. These values are 0-based.
//
// Input, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM], the
// centers associated with the minimal energy clustering.
//
// Output, double CLUSTER_ENERGY_COMPUTE[CLUSTER_NUM], the energy
// associated with each cluster.
//
{
double *cluster_energy;
int i;
int j;
int k;
double point_energy;
cluster_energy = r8vec_zero_new ( cluster_num );
for ( j = 0; j < point_num; j++ )
{
k = cluster[i];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy
+ pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + point_energy;
}
return cluster_energy;
}
//****************************************************************************80
double *cluster_initialize_1 ( int dim_num, int point_num, int cluster_num,
double point[] )
//****************************************************************************80
//
// Purpose:
//
// CLUSTER_INITIALIZE_1 initializes the clusters to data points.
//
// Discussion:
//
// The cluster centers are simply chosen to be the first data points.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates
// of the points.
//
// Output, double CLUSTER_INITIALIZE_1[DIM_NUM*CLUSTER_NUM],
// the coordinates of the cluster centers.
//
{
double *cluster_center;
int i;
int j;
cluster_center = new double[dim_num*cluster_num];
for ( j = 0; j < cluster_num; j++ )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+j*dim_num] = point[i+j*dim_num];
}
}
return cluster_center;
}
//****************************************************************************80
double *cluster_initialize_2 ( int dim_num, int point_num, int cluster_num,
double point[], int *seed )
//****************************************************************************80
//
// Purpose:
//
// CLUSTER_INITIALIZE_2 initializes the cluster centers to random values.
//
// Discussion:
//
// In this case, the hyperbox containing the data is computed.
//
// Then the cluster centers are chosen uniformly at random within
// this hyperbox.
//
// Of course, if the data is not smoothly distributed throughout
// the box, many cluster centers will be isolated.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates
// of the points.
//
// Input/output, int *SEED, a seed for the random
// number generator.
//
// Output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM],
// the coordinates of the cluster centers.
//
{
double *cluster_center;
int i;
int j;
double *r;
double *r_max;
double *r_min;
cluster_center = new double[dim_num*cluster_num];
r = new double[dim_num];
r_min = new double[dim_num];
r_max = new double[dim_num];
j = 0;
for ( i = 0; i < dim_num; i++ )
{
r_max[i] = point[i+j*dim_num];
r_min[i] = point[i+j*dim_num];
}
for ( j = 1; j < point_num; j++ )
{
for ( i = 0; i < dim_num; i++ )
{
r_max[i] = r8_max ( r_max[i], point[i+j*dim_num] );
r_min[i] = r8_min ( r_min[i], point[i+j*dim_num] );
}
}
for ( j = 0; j < cluster_num; j++ )
{
r8vec_uniform_01 ( dim_num, seed, r );
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+j*dim_num] = ( 1.0 - r[i] ) * r_min[i] + r[i] * r_max[i];
}
}
delete [] r;
delete [] r_max;
delete [] r_min;
return cluster_center;
}
//****************************************************************************80
double *cluster_initialize_3 ( int dim_num, int point_num, int cluster_num,
double point[], int *seed )
//****************************************************************************80
//
// Purpose:
//
// CLUSTER_INITIALIZE_3 initializes the cluster centers to random values.
//
// Discussion:
//
// In this case, each point is randomly assigned to a cluster, and
// the cluster centers are then computed as the centroids of the points
// in the cluster.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates
// of the points.
//
// Input/output, int SEED, a seed for the random
// number generator.
//
// Output, double CLUSTER_INITIALIZE_3[DIM_NUM*CLUSTER_NUM],
// the coordinates of the cluster centers.
//
{
double *cluster_center;
int *cluster_population;
int i;
int j;
int k;
//
// Assign one point to each cluster center.
//
cluster_center = new double[dim_num*cluster_num];
for ( k = 0; k < cluster_num; k++ )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = point[i+k*dim_num];
}
}
cluster_population = new int[cluster_num];
for ( k = 0; k < cluster_num; k++ )
{
cluster_population[k] = 1;
}
//
// The rest of the points get assigned randomly.
//
for ( j = cluster_num; j < point_num; j++ )
{
k = i4_uniform ( 1, cluster_num, seed );
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ point[i+j*dim_num];
}
cluster_population[k] = cluster_population[k] + 1;
}
//
// Now average the points to get the centroid.
//
for ( k = 0; k < cluster_num; k++ )
{
if ( cluster_population[k] != 0 )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num] /
( double ) ( cluster_population[k] );
}
}
}
delete [] cluster_population;
return cluster_center;
}
//****************************************************************************80
double *cluster_initialize_4 ( int dim_num, int point_num, int cluster_num,
double point[], int *seed )
//****************************************************************************80
//
// Purpose:
//
// CLUSTER_INITIALIZE_4 initializes the cluster centers to random values.
//
// Discussion:
//
// In this case, each data point is divided randomly among the
// the cluster centers.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates
// of the points.
//
// Input/output, int SEED, a seed for the random
// number generator.
//
// Output, double CLUSTER_INITIALIZE_4[DIM_NUM*CLUSTER_NUM],
// the coordinates of the cluster centers.
//
{
double *cluster_center;
double *cluster_factor;
double *cluster_weight;
double divisor;
int i;
int j;
int k;
cluster_center = r8vec_zero_new ( dim_num * cluster_num );
cluster_factor = new double[cluster_num];
cluster_weight = r8vec_zero_new ( cluster_num );
for ( j = 0; j < point_num; j++ )
{
r8vec_uniform_01 ( cluster_num, seed, cluster_factor );
divisor = r8vec_sum ( cluster_num, cluster_factor );
for ( k = 0; k < cluster_num; k++ )
{
cluster_factor[k] = cluster_factor[k] / divisor;
}
for ( k = 0; k < cluster_num; k++ )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ cluster_factor[k] * point[i+j*dim_num];
}
}
for ( k = 0; k < cluster_num; k++ )
{
cluster_weight[k] = cluster_weight[k] + cluster_factor[k];
}
}
//
// Now normalize, so that each cluster center is now a convex
// combination of the points.
//
for ( k = 0; k < cluster_num; k++ )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
/ cluster_weight[k];
}
}
delete [] cluster_factor;
delete [] cluster_weight;
return cluster_center;
}
//****************************************************************************80
double *cluster_initialize_5 ( int dim_num, int point_num, int cluster_num,
double point[], int *seed )
//****************************************************************************80
//
// Purpose:
//
// CLUSTER_INITIALIZE_5 initializes the cluster centers to random values.
//
// Discussion:
//
// In this case, each cluster center is a random convex combination
// of the data points.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates
// of the points.
//
// Input/output, int *SEED, a seed for the random
// number generator.
//
// Output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM],
// the coordinates of the cluster centers.
//
{
double *cluster_center;
double column_sum;
double *factor;
int j;
int k;
//
// Get a PxC block of random factors.
//
factor = r8mat_uniform_01_new ( point_num, cluster_num, seed );
//
// Make each column of factors have unit sum.
//
for ( k = 0; k < cluster_num; k++ )
{
column_sum = 0.0;
for ( j = 0; j < point_num; j++ )
{
column_sum = column_sum + factor[j+k*point_num];
}
for ( j = 0; j < point_num; j++ )
{
factor[j+k*point_num] = factor[j+k*point_num] / column_sum;
}
}
//
// Set centers = points * factors.
//
cluster_center = r8mat_mm_new ( dim_num, point_num, cluster_num, point,
factor );
delete [] factor;
return cluster_center;
}
//****************************************************************************80
void cluster_print_summary ( int point_num, int cluster_num,
int cluster_population[], double cluster_energy[], double cluster_variance[] )
//****************************************************************************80
//
// Purpose:
//
// CLUSTER_PRINT_SUMMARY prints a summary of data about a clustering.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int CLUSTER_POPULATION[CLUSTER_NUM], the number of
// points assigned to each cluster.
//
// Input, double CLUSTER_ENERGY[CLUSTER_NUM], the energy of
// the clusters.
//
// Input, double CLUSTER_VARIANCE[CLUSTER_NUM], the variance of
// the clusters.
//
{
double ce;
int cep;
double ce_total;
int cp;
int cpp;
double cv;
int k;
ce_total = r8vec_sum ( cluster_num, cluster_energy );
cout << "\n";
cout << " Clustering statistics:\n";
cout << "\n";
cout << " Number of clusters is " << cluster_num << "\n";
cout << " Number of points is " << point_num << "\n";
cout << " Total energy is " << ce_total << "\n";
cout << "\n";
cout << " Cluster Population Energy Variance\n";
cout << " ------- ----------- ----------------- --------------\n";
cout << " # % value %\n";
cout << "\n";
for ( k = 0; k < cluster_num; k++ )
{
cp = cluster_population[k];
cpp = ( int ) ( ( double ) ( 100 * cp ) / ( double ) ( point_num ) );
ce = cluster_energy[k];
cep = ( int ) ( ( ce * 100.0 ) / ce_total );
cv = cluster_variance[k];
cout << " " << setw(7) << k
<< " " << setw(8) << cp
<< " " << setw(3) << cpp
<< " " << setw(12) << ce
<< " " << setw(3) << cep
<< " " << setw(12) << cv << "\n";
}
cp = i4vec_sum ( cluster_num, cluster_population );
cpp = 100;
ce = r8vec_sum ( cluster_num, cluster_energy );
cep = 100;
cv = r8vec_i4vec_dot_product ( cluster_num, cluster_variance,
cluster_population ) / cp;
cout << "\n";
cout << " " << " Total"
<< " " << setw(8) << cp
<< " " << setw(3) << cpp
<< " " << setw(12) << ce
<< " " << setw(3) << cep
<< " " << setw(12) << cv << "\n";
return;
}
//****************************************************************************80
double *cluster_variance_compute ( int dim_num, int point_num, int cluster_num,
double point[], int cluster[], double cluster_center[] )
//****************************************************************************80
//
// Purpose:
//
// CLUSTER_VARIANCE_COMPUTE computes the variance of the clusters.
//
// Discussion:
//
// The cluster variance (from the cluster center) is the average of the
// sum of the squares of the distances of each point in the cluster to the
// cluster center.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 October 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of data points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the data points.
//
// Input, int CLUSTER[POINT_NUM], the cluster to which each
// data point belongs.
//
// Input, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM], the
// centers associated with the minimal energy clustering.
//
// Output, double CLUSTER_VARIANCE_COMPUTE[CLUSTER_NUM], the variance
// associated with each cluster.
//
{
int *cluster_population;
double *cluster_variance;
int i;
int j;
int k;
double point_variance;
cluster_population = i4vec_zero_new ( cluster_num );
cluster_variance = r8vec_zero_new ( cluster_num );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_variance = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_variance = point_variance +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_variance[k] = cluster_variance[k] + point_variance;
cluster_population[k] = cluster_population[k] + 1;
}
for ( k = 0; k < cluster_num; k++ )
{
if ( 0 < cluster_population[k] )
{
cluster_variance[k] = cluster_variance[k] / cluster_population[k];
}
}
delete [] cluster_population;
return cluster_variance;
}
//****************************************************************************80
int file_column_count ( string filename )
//****************************************************************************80
//
// Purpose:
//
// FILE_COLUMN_COUNT counts the columns in the first line of a file.
//
// Discussion:
//
// The file is assumed to be a simple text file.
//
// Most lines of the file are presumed to consist of COLUMN_NUM words,
// separated by spaces. There may also be some blank lines, and some
// comment lines, which have a "#" in column 1.
//
// The routine tries to find the first non-comment non-blank line and
// counts the number of words in that line.
//
// If all lines are blanks or comments, it goes back and tries to analyze
// a comment line.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string FILENAME, the name of the file.
//
// Output, int FILE_COLUMN_COUNT, the number of columns assumed
// to be in the file.
//
{
int column_num;
ifstream input;
bool got_one;
string text;
//
// Open the file.
//
input.open ( filename.c_str ( ) );
if ( !input )
{
column_num = -1;
cerr << "\n";
cerr << "FILE_COLUMN_COUNT - Fatal error!\n";
cerr << " Could not open the file:\n";
cerr << " \"" << filename << "\"\n";
exit ( 1 );
}
//
// Read one line, but skip blank lines and comment lines.
//
got_one = false;
for ( ; ; )
{
getline ( input, text );
if ( input.eof ( ) )
{
break;
}
if ( s_len_trim ( text ) <= 0 )
{
continue;
}
if ( text[0] == '#' )
{
continue;
}
got_one = true;
break;
}
if ( !got_one )
{
input.close ( );
input.open ( filename.c_str ( ) );
for ( ; ; )
{
input >> text;
if ( input.eof ( ) )
{
break;
}
if ( s_len_trim ( text ) == 0 )
{
continue;
}
got_one = true;
break;
}
}
input.close ( );
if ( !got_one )
{
cerr << "\n";
cerr << "FILE_COLUMN_COUNT - Warning!\n";
cerr << " The file does not seem to contain any data.\n";
return -1;
}
column_num = s_word_count ( text );
return column_num;
}
//****************************************************************************80
int file_row_count ( string input_filename )
//****************************************************************************80
//
// Purpose:
//
// FILE_ROW_COUNT counts the number of row records in a file.
//
// Discussion:
//
// It does not count lines that are blank, or that begin with a
// comment symbol '#'.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Output, int FILE_ROW_COUNT, the number of rows found.
//
{
int bad_num;
int comment_num;
ifstream input;
int i;
string line;
int record_num;
int row_num;
row_num = 0;
comment_num = 0;
record_num = 0;
bad_num = 0;
input.open ( input_filename.c_str ( ) );
if ( !input )
{
cerr << "\n";
cerr << "FILE_ROW_COUNT - Fatal error!\n";
cerr << " Could not open the input file: \"" << input_filename << "\"\n";
exit ( 1 );
}
for ( ; ; )
{
getline ( input, line );
if ( input.eof ( ) )
{
break;
}
record_num = record_num + 1;
if ( line[0] == '#' )
{
comment_num = comment_num + 1;
continue;
}
if ( s_len_trim ( line ) == 0 )
{
comment_num = comment_num + 1;
continue;
}
row_num = row_num + 1;
}
input.close ( );
return row_num;
}
//****************************************************************************80
void hmeans_01 ( int dim_num, int point_num, int cluster_num, int it_max,
int &it_num, double point[], int cluster[], double cluster_center[],
int cluster_population[], double cluster_energy[] )
//****************************************************************************80
//
// Purpose:
//
// HMEANS_01 applies the H-Means algorithm.
//
// Discussion:
//
// The data for the H-Means problem is a set of N points X in
// M-dimensions, and a desired number of clusters K.
//
// The goal is to determine K points Z, called cluster centers, so that
// if we associate each point X with its nearest Z value, we minimize
// the standard deviation or cluster energy. Writing CLUSTER(I) to
// indicate the index of the nearest cluster center to point X(I), the
// energy can be written as:
//
// Energy = Sum ( 1 <= I <= N ) || X(I) - Z(CLUSTER(I)) ||^2
//
// where
//
// || X - Z ||^2 = Sum ( 1 <= J <= M ) ( X(J) - Z(J) )^2
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Wendy Martinez, Angel Martinez,
// Computational Statistics Handbook with MATLAB,
// pages 373-376,
// Chapman and Hall / CRC, 2002.
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of data points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int IT_MAX, the maximum number of iterations.
//
// Output, int &IT_NUM, the number of iterations taken.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the data points.
//
// Input/output, int CLUSTER[POINT_NUM]. On input, the user
// may specify an initial cluster for each point, or leave all entrie of
// CLUSTER set to 0. On output, CLUSTER contains the index of the
// cluster to which each data point belongs.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM], the
// centers associated with the minimal energy clustering.
//
// Output, int CLUSTER_POPULATION[CLUSTER_NUM],
// the populuation of each cluster.
//
// Output, double CLUSTER_ENERGY[CLUSTER_NUM], the energy
// associated with each cluster.
//
{
int c;
double *centroid;
bool debug = true;
int i;
int j;
int k;
int k2;
int missed;
double point_energy;
double point_energy_min;
int swap;
//
// Data checks.
//
if ( cluster_num < 1 )
{
cout << "\n";
cout << "HMEANS_01 - Fatal error!\n";
cout << " CLUSTER_NUM < 1.\n";
exit ( 1 );
}
if ( dim_num < 1 )
{
cout << "\n";
cout << "HMEANS_01 - Fatal error!\n";
cout << " DIM_NUM < 1.\n";
exit ( 1 );
}
if ( point_num < 1 )
{
cout << "\n";
cout << "HMEANS_01 - Fatal error!\n";
cout << " POINT_NUM < 1.\n";
exit ( 1 );
}
if ( it_max < 0 )
{
cout << "\n";
cout << "HMEANS_01 - Fatal error!\n";
cout << " IT_MAX < 0.\n";
exit ( 1 );
}
//
// On input, legal entries in CLUSTER are preserved, but
// otherwise, each point is assigned to its nearest cluster.
//
for ( j = 0; j < point_num; j++ )
{
if ( cluster[j] < 0 || cluster_num <= cluster[j] )
{
point_energy_min = r8_huge ( );
for ( k = 0; k < cluster_num; k++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k;
}
}
}
}
it_num = 0;
while ( it_num < it_max )
{
it_num = it_num + 1;
//
// #1:
// Assign each point to the cluster of its nearest center.
//
swap = 0;
for ( j = 0; j < point_num; j++ )
{
point_energy_min = r8_huge ( );
k = cluster[j];
for ( k2 = 0; k2 < cluster_num; k2++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k2*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k2;
}
}
if ( k != cluster[j] )
{
swap = swap + 1;
}
}
//
// Terminate if no points were swapped.
//
if ( 1 < it_num )
{
if ( swap == 0 )
{
break;
}
}
//
// #2:
// Determine the total energy of the new clustering with current centroids.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + point_energy;
}
//
// #3:
// Determine the centroids of the clusters.
//
centroid = r8vec_zero_new ( dim_num * cluster_num );
i4vec_zero ( cluster_num, cluster_population );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
cluster_population[k] = cluster_population[k] + 1;
for ( i = 0; i < dim_num; i++ )
{
centroid[i+k*dim_num] = centroid[i+k*dim_num] + point[i+j*dim_num];
}
}
//
// Now divide by the population to get the centroid.
// But if a center has no population, pick a point at random.
//
missed = 0;
for ( k = 0; k < cluster_num; k++ )
{
if ( cluster_population[k] != 0 )
{
for ( i = 0; i < dim_num; i++ )
{
centroid[i+k*dim_num] = centroid[i+k*dim_num]
/ ( double ) ( cluster_population[k] );
}
}
else
{
for ( i = 0; i < dim_num; i++ )
{
centroid[i+k*dim_num] = point[i+missed*dim_num];
}
missed = missed + 1;
}
}
for ( k = 0; k < cluster_num; k++ )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = centroid[i+k*dim_num];
}
}
delete [] centroid;
//
// #4:
// Determine the total energy of the current clustering with new centroids.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + point_energy;
}
}
return;
}
//****************************************************************************80
void hmeans_02 ( int dim_num, int point_num, int cluster_num, int it_max,
int &it_num, double point[], int cluster[], double cluster_center[],
int cluster_population[], double cluster_energy[], int *seed )
//****************************************************************************80
//
// Purpose:
//
// HMEANS_02 applies the H-Means algorithm.
//
// Discussion:
//
// This is a simple routine to group a set of points into K clusters,
// each with a center point, in such a way that the total cluster
// energy is minimized. The total cluster energy is the sum of the
// squares of the distances of each point to the center of its cluster.
//
// The algorithm begins with an initial estimate for the cluster centers:
//
// 1. The points are assigned to the nearest cluster centers.
//
// 2. The iteration exit ( 1 );s if the total energy has not changed
// significantly, or we have reached the maximum number of iterations.
//
// 3. Each cluster center is replaced by the centroid of the points
// in the cluster.
//
// 4. Return to step 1.
//
// The algorithm may fail to find the best solution.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int IT_MAX, the maximum number of iterations.
//
// Output, int IT_NUM, the number of iterations taken.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates
// of the points.
//
// Input/output, int CLUSTER[POINT_NUM]. On input, the user
// may specify an initial cluster for each point, or leave all entrie of
// CLUSTER set to 0. On output, CLUSTER contains the index of the
// cluster to which each data point belongs.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM],
// the coordinates of the cluster centers.
//
// Output, int CLUSTER_POPULATION[CLUSTER_NUM], the number of
// points assigned to each cluster.
//
// Output, double CLUSTER_ENERGY[CLUSTER_NUM], the energy of
// the clusters.
//
// Input/output, int *SEED, a seed for the random
// number generator.
//
{
int c;
bool debug = false;
int i;
int j;
int k;
int k2;
double point_energy;
double point_energy_min;
int swap;
//
// Data checks.
//
if ( cluster_num < 1 )
{
cout << "\n";
cout << "HMEANS_02 - Fatal error!\n";
cout << " CLUSTER_NUM < 1.\n";
exit ( 1 );
}
if ( dim_num < 1 )
{
cout << "\n";
cout << "HMEANS_02 - Fatal error!\n";
cout << " DIM_NUM < 1.\n";
exit ( 1 );
}
if ( point_num < 1 )
{
cout << "\n";
cout << "HMEANS_02 - Fatal error!\n";
cout << " POINT_NUM < 1.\n";
exit ( 1 );
}
if ( it_max < 0 )
{
cout << "\n";
cout << "HMEANS_02 - Fatal error!\n";
cout << " IT_MAX < 0.\n";
exit ( 1 );
}
//
// On input, legal entries in CLUSTER are preserved, but
// otherwise, each point is assigned to its nearest cluster.
//
for ( j = 0; j < point_num; j++ )
{
if ( cluster[j] < 0 || cluster_num <= cluster[j] )
{
point_energy_min = r8_huge ( );
for ( k = 0; k < cluster_num; k++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k;
}
}
}
}
it_num = 0;
for ( ; ; )
{
//
// Given centers, assign points to nearest center.
//
i4vec_zero ( cluster_num, cluster_population );
r8vec_zero ( cluster_num, cluster_energy );
swap = 0;
for ( j = 0; j < point_num; j++ )
{
point_energy_min = r8_huge ( );
k = cluster[j];
for ( k2 = 0; k2 < cluster_num; k2++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k2*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k2;
}
}
if ( k != cluster[j] )
{
swap = swap + 1;
}
k = cluster[j];
cluster_energy[k] = cluster_energy[k] + point_energy_min;
cluster_population[k] = cluster_population[k] + 1;
}
if ( debug )
{
cout << " " << setw(3) << it_num
<< " " << setw(14) << r8vec_sum ( cluster_num, cluster_energy ) << "\n";
}
if ( 0 < it_num )
{
if ( swap == 0 )
{
break;
}
}
if ( it_max <= it_num )
{
break;
}
it_num = it_num + 1;
//
// Given points in cluster, replace center by centroid.
//
r8vec_zero ( dim_num * cluster_num, cluster_center );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ point[i+j*dim_num];
}
}
for ( k = 0; k < cluster_num; k++ )
{
if ( cluster_population[k] != 0 )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num] /
( double ) ( cluster_population[k] );
}
}
else
{
j = i4_uniform ( 0, point_num - 1, seed );
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = point[i+j*dim_num];
}
}
}
}
//
// Compute the energy based on the final value of the cluster centers.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + point_energy;
}
return;
}
//****************************************************************************80
void hmeans_w_01 ( int dim_num, int point_num, int cluster_num, int it_max,
int &it_num, double point[], double weight[], int cluster[],
double cluster_center[], int cluster_population[], double cluster_energy[] )
//****************************************************************************80
//
// Purpose:
//
// HMEANS_W_01 applies the weighted H-Means algorithm.
//
// Discussion:
//
// The input data for the weight H-Means problem includes:
// * a set of N data points X in M dimensions,
// * a set of N nonnegative weights W,
// * a desired number of clusters K.
// * an initial set of cluster centers Z,
// * an (optional) initial set of cluster assignments.
//
// The goal is to determine K points Z, called cluster centers, and
// to assign each point X(I) to some cluster Z(J), so that we minimize
// the weighted standard deviation of the distance of each data point
// to the center of its cluster. Writing J = CLUSTER(I) to
// indicate the index of the nearest cluster center Z(J) to the
// point X(I), the quantity we are trying to minimize is the sum
// of the weighted cluster energies E(J), where:
//
// E(J) = Sum ( 1 <= I <= N ) W(I) * || X(I) - Z(J) ||^2
//
// Here, we assume that we are using the Euclidean norm, so that
//
// || X(I) - Z(J) ||^2 = Sum ( 1 <= K <= M )
// ( X(I)(K) - Z(J)(K) )^2
//
// In this notation, X(I)(K) is the K-th spatial component of the
// I-th data point.
//
// Note that this routine should give the same results as HMEANS_01
// in any case in which all the entries of the WEIGHT vector are equal.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Wendy Martinez, Angel Martinez,
// Computational Statistics Handbook with MATLAB,
// pages 373-376,
// Chapman and Hall / CRC, 2002.
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of data points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int IT_MAX, the maximum number of iterations.
//
// Output, int &IT_NUM, the number of iterations taken.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the data points.
//
// Input, double WEIGHT[POINT_NUM], the weights
// assigned to the data points. These must be nonnegative, and
// at least one must be strictly positive.
//
// Input/output, int CLUSTER[POINT_NUM]. On input, the user
// may specify an initial cluster for each point, or leave all entrie of
// CLUSTER set to 0. On output, CLUSTER contains the index of the
// cluster to which each data point belongs.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM], the
// centers associated with the minimal energy clustering.
//
// Output, double CLUSTER_ENERGY[CLUSTER_NUM], the energy
// associated with each cluster.
//
{
int c;
double *centroid;
double *cluster_weight;
bool debug = true;
double energy;
int i;
int j;
int k;
int k2;
int missed;
double point_energy;
double point_energy_min;
int swap;
//
// Data checks.
//
if ( cluster_num < 1 )
{
cout << "\n";
cout << "HMEANS_W_01 - Fatal error!\n";
cout << " CLUSTER_NUM < 1.\n";
exit ( 1 );
}
if ( dim_num < 1 )
{
cout << "\n";
cout << "HMEANS_W_01 - Fatal error!\n";
cout << " DIM_NUM < 1.\n";
exit ( 1 );
}
if ( point_num < 1 )
{
cout << "\n";
cout << "HMEANS_W_01 - Fatal error!\n";
cout << " POINT_NUM < 1.\n";
exit ( 1 );
}
if ( it_max < 0 )
{
cout << "\n";
cout << "HMEANS_W_01 - Fatal error!\n";
cout << " IT_MAX < 0.\n";
exit ( 1 );
}
if ( r8vec_any_negative ( point_num, weight ) )
{
cout << "\n";
cout << "HMEANS_W_01 - Fatal error!\n";
cout << " Some weight entry is negative.\n";
exit ( 1 );
}
if ( r8vec_all_nonpositive ( point_num, weight ) )
{
cout << "\n";
cout << "HMEANS_W_01 - Fatal error!\n";
cout << " No weight entry is positive.\n";
exit ( 1 );
}
//
// On input, legal entries in CLUSTER are preserved, but
// otherwise, each point is assigned to its nearest cluster.
//
for ( j = 0; j < point_num; j++ )
{
if ( cluster[j] < 0 || cluster_num <= cluster[j] )
{
point_energy_min = r8_huge ( );
for ( k = 0; k < cluster_num; k++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k;
}
}
}
}
it_num = 0;
while ( it_num < it_max )
{
it_num = it_num + 1;
//
// #1:
// Reassign points to clusters:
// Assign each point to the cluster whose center is nearest;
// Count the number of points whose cluster assignment is changed.
//
swap = 0;
for ( j = 0; j < point_num; j++ )
{
point_energy_min = r8_huge ( );
k = cluster[j];
for ( k2 = 0; k2 < cluster_num; k2++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k2*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k2;
}
}
if ( k != cluster[j] )
{
swap = swap + 1;
}
}
//
// If no point changed its cluster assignment, the algorithm can make no
// more improvements, so terminate.
//
if ( 1 < it_num )
{
if ( swap == 0 )
{
break;
}
}
//
// Determine the current energy.
//
energy = 0.0;
for ( j = 0; j < point_num; j++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k2*dim_num], 2 );
}
energy = energy + weight[j] * point_energy;
}
cout << " " << setw(4) << it_num
<< " " << setw(14) << energy << "\n";
//
// #2:
// Determine the centroids of the clusters, and set the
// cluster center to the cluster centroid.
//
centroid = r8vec_zero_new ( dim_num * cluster_num );
cluster_weight = r8vec_zero_new ( cluster_num );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
cluster_population[k] = cluster_population[k] + 1;
cluster_weight[k] = cluster_weight[k] + weight[j];
for ( i = 0; i < dim_num; i++ )
{
centroid[i+k*dim_num] = centroid[i+k*dim_num]
+ weight[j] * point[i+j*dim_num];
}
}
missed = 0;
for ( k = 0; k < cluster_num; k++ )
{
if ( cluster_weight[k] != 0.0 )
{
for ( i = 0; i < dim_num; i++ )
{
centroid[i+k*dim_num] = centroid[i+k*dim_num] / cluster_weight[k];
}
}
else
{
for ( i = 0; i < dim_num; i++ )
{
centroid[i+k*dim_num] = point[i+missed*dim_num];
}
missed = missed + 1;
}
}
for ( k = 0; k < cluster_num; k++ )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = centroid[i+k*dim_num];
}
}
delete [] centroid;
delete [] cluster_weight;
}
//
// Compute the energy based on the final value of the cluster centers.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + weight[j] * point_energy;
}
return;
}
//****************************************************************************80
void hmeans_w_02 ( int dim_num, int point_num, int cluster_num, int it_max,
int &it_num, double point[], double weight[], int cluster[],
double cluster_center[], int cluster_population[], double cluster_energy[],
int *seed )
//****************************************************************************80
//
// Purpose:
//
// HMEANS_W_02 applies the weighted H-Means algorithm.
//
// Discussion:
//
// The input data for the weight H-Means problem includes:
// * a set of N data points X in M dimensions,
// * a set of N nonnegative weights W,
// * a desired number of clusters K.
// * an initial set of cluster centers Z,
// * an (optional) initial set of cluster assignments.
//
// The goal is to determine K points Z, called cluster centers, and
// to assign each point X(I) to some cluster Z(J), so that we minimize
// the weighted standard deviation of the distance of each data point
// to the center of its cluster. Writing J = CLUSTER(I) to
// indicate the index of the nearest cluster center Z(J) to the
// point X(I), the quantity we are trying to minimize is the sum
// of the weighted cluster energies E(J), where:
//
// E(J) = Sum ( 1 <= I <= N ) W(I) * || X(I) - Z(J) ||^2
//
// Here, we assume that we are using the Euclidean norm, so that
//
// || X(I) - Z(J) ||^2 = Sum ( 1 <= K <= M )
// ( X(I)(K) - Z(J)(K) )^2
//
// In this notation, X(I)(K) is the K-th spatial component of the
// I-th data point.
//
// Note that this routine should give the same results as HMEANS_02
// in any case in which all the entries of the WEIGHT vector are equal.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int IT_MAX, the maximum number of iterations.
//
// Output, int &IT_NUM, the number of iterations taken.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates
// of the points.
//
// Input, double WEIGHT[POINT_NUM], the weights
// assigned to the data points. These must be nonnegative, and
// at least one must be strictly positive.
//
// Input/output, int CLUSTER[POINT_NUM]. On input, the user
// may specify an initial cluster for each point, or leave all entrie of
// CLUSTER set to 0. On output, CLUSTER contains the index of the
// cluster to which each data point belongs.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM],
// the coordinates of the cluster centers.
//
// Output, int CLUSTER_POPULATION[CLUSTER_NUM], the number of
// points assigned to each cluster.
//
// Output, double CLUSTER_ENERGY[CLUSTER_NUM], the energy of
// the clusters.
//
// Input/output, int *SEED, a seed for the random
// number generator.
//
{
double *cluster_weight;
int i;
int j;
int k;
int k2;
double point_energy;
double point_energy_min;
int swap;
//
// Data checks.
//
if ( cluster_num < 1 )
{
cout << "\n";
cout << "HMEANS_W_02 - Fatal error!\n";
cout << " CLUSTER_NUM < 1.\n";
exit ( 1 );
}
if ( dim_num < 1 )
{
cout << "\n";
cout << "HMEANS_W_02 - Fatal error!\n";
cout << " DIM_NUM < 1.\n";
exit ( 1 );
}
if ( point_num < 1 )
{
cout << "\n";
cout << "HMEANS_W_02 - Fatal error!\n";
cout << " POINT_NUM < 1.\n";
exit ( 1 );
}
if ( it_max < 0 )
{
cout << "\n";
cout << "HMEANS_W_02 - Fatal error!\n";
cout << " IT_MAX < 0.\n";
exit ( 1 );
}
if ( r8vec_any_negative ( point_num, weight ) )
{
cout << "\n";
cout << "HMEANS_W_02 - Fatal error!\n";
cout << " Some weight entry is negative.\n";
exit ( 1 );
}
if ( r8vec_all_nonpositive ( point_num, weight ) )
{
cout << "\n";
cout << "HMEANS_W_02 - Fatal error!\n";
cout << " No weight entry is positive.\n";
exit ( 1 );
}
//
// On input, legal entries in CLUSTER are preserved, but
// otherwise, each point is assigned to its nearest cluster.
//
for ( j = 0; j < point_num; j++ )
{
if ( cluster[j] < 0 || cluster_num <= cluster[j] )
{
point_energy_min = r8_huge ( );
for ( k = 0; k < cluster_num; k++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k;
}
}
}
}
it_num = 0;
for ( ; ; )
{
//
// Given centers, assign points to nearest center.
//
i4vec_zero ( cluster_num, cluster_population );
r8vec_zero ( cluster_num, cluster_energy );
cluster_weight = r8vec_zero_new ( cluster_num );
swap = 0;
for ( j = 0; j < point_num; j++ )
{
point_energy_min = r8_huge ( );
k = cluster[j];
for ( k2 = 0; k2 < cluster_num; k2++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k2*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k2;
}
}
if ( k != cluster[j] )
{
swap = swap + 1;
}
k = cluster[j];
cluster_energy[k] = cluster_energy[k] + weight[j] * point_energy_min;
cluster_population[k] = cluster_population[k] + 1;
cluster_weight[k] = cluster_weight[k] + weight[j];
}
if ( 0 < it_num )
{
if ( swap == 0 )
{
break;
}
}
if ( it_max <= it_num )
{
break;
}
it_num = it_num + 1;
//
// Given points in cluster, replace center by weighted centroid.
//
r8vec_zero ( dim_num * cluster_num, cluster_center );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ weight[j] * point[i+j*dim_num];
}
}
for ( k = 0; k < cluster_num; k++ )
{
if ( cluster_weight[k] != 0.0 )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num] /
cluster_weight[k];
}
}
else
{
j = i4_uniform ( 0, point_num - 1, seed );
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = point[i+j*dim_num];
}
}
}
delete [] cluster_weight;
}
//
// Compute the energy based on the final value of the cluster centers.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + weight[j] * point_energy;
}
return;
}
//****************************************************************************80
int i4_max ( int i1, int i2 )
//****************************************************************************80
//
// Purpose:
//
// I4_MAX returns the maximum of two I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I1, I2, are two integers to be compared.
//
// Output, int I4_MAX, the larger of I1 and I2.
//
{
int value;
if ( i2 < i1 )
{
value = i1;
}
else
{
value = i2;
}
return value;
}
//****************************************************************************80
int i4_min ( int i1, int i2 )
//****************************************************************************80
//
// Purpose:
//
// I4_MIN returns the minimum of two I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 1998
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int I1, I2, two integers to be compared.
//
// Output, int I4_MIN, the smaller of I1 and I2.
//
{
int value;
if ( i1 < i2 )
{
value = i1;
}
else
{
value = i2;
}
return value;
}
//****************************************************************************80
int i4_uniform ( int a, int b, int *seed )
//****************************************************************************80
//
// Purpose:
//
// I4_UNIFORM returns a scaled pseudorandom I4.
//
// Discussion:
//
// The pseudorandom number should be uniformly distributed
// between A and B.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 November 2006
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Springer Verlag, pages 201-202, 1983.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley Interscience, page 95, 1998.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, pages 362-376, 1986.
//
// Peter Lewis, Allen Goodman, James Miller
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, pages 136-143, 1969.
//
// Parameters:
//
// Input, int A, B, the limits of the interval.
//
// Input/output, int *SEED, the "seed" value, which should NOT be 0.
// On output, SEED has been updated.
//
// Output, int I4_UNIFORM, a number between A and B.
//
{
int k;
float r;
int value;
if ( *seed == 0 )
{
cerr << "\n";
cerr << "I4_UNIFORM - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 )
{
*seed = *seed + 2147483647;
}
r = ( float ) ( *seed ) * 4.656612875E-10;
//
// Scale R to lie between A-0.5 and B+0.5.
//
r = ( 1.0 - r ) * ( ( float ) ( i4_min ( a, b ) ) - 0.5 )
+ r * ( ( float ) ( i4_max ( a, b ) ) + 0.5 );
//
// Use rounding to convert R to an integer between A and B.
//
value = r4_nint ( r );
value = i4_max ( value, i4_min ( a, b ) );
value = i4_min ( value, i4_max ( a, b ) );
return value;
}
//****************************************************************************80
void i4mat_write ( string output_filename, int m, int n, int table[] )
//****************************************************************************80
//
// Purpose:
//
// I4MAT_WRITE writes an I4MAT file with no header.
//
// Discussion:
//
// An I4MAT is an array of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 June 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string OUTPUT_FILENAME, the output filename.
//
// Input, int M, the spatial dimension.
//
// Input, int N, the number of points.
//
// Input, int TABLE[M*N], the data.
//
{
int i;
int j;
ofstream output;
//
// Open the file.
//
output.open ( output_filename.c_str ( ) );
if ( !output )
{
cerr << "\n";
cerr << "I4MAT_WRITE - Fatal error!\n";
cerr << " Could not open the output file.\n";
exit ( 1 );
}
//
// Write the data.
//
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
output << " " << setw(10) << table[i+j*m];
}
output << "\n";
}
//
// Close the file.
//
output.close ( );
return;
}
//****************************************************************************80
void i4vec_negone ( int n, int a[] )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_NEGONE sets an I4VEC to -1.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, int A[N], a vector of -1's.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = -1;
}
return;
}
//****************************************************************************80
int *i4vec_negone_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_NEGONE_NEW creates an I4VEC and sets it to -1.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 12 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, int I4VEC_NEGONE_NEW[N], a vector of -1's.
//
{
int *a;
int i;
a = new int[n];
for ( i = 0; i < n; i++ )
{
a[i] = -1;
}
return a;
}
//****************************************************************************80
int i4vec_sum ( int n, int a[] )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_SUM sums the entries of an I4VEC.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Example:
//
// Input:
//
// A = ( 1, 2, 3, 4 )
//
// Output:
//
// I4VEC_SUM = 10
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 26 May 1999
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, int A[N], the vector to be summed.
//
// Output, int I4VEC_SUM, the sum of the entries of A.
//
{
int i;
int sum;
sum = 0;
for ( i = 0; i < n; i++ )
{
sum = sum + a[i];
}
return sum;
}
//****************************************************************************80
void i4vec_zero ( int n, int a[] )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_ZERO zeroes an I4VEC.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 01 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, int A[N], a vector of zeroes.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = 0;
}
return;
}
//****************************************************************************80
int *i4vec_zero_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// I4VEC_ZERO_NEW creates and zeroes an I4VEC.
//
// Discussion:
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 July 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, int I4VEC_ZERO_NEW[N], a vector of zeroes.
//
{
int *a;
int i;
a = new int[n];
for ( i = 0; i < n; i++ )
{
a[i] = 0;
}
return a;
}
//****************************************************************************80
void kmeans_01 ( int dim_num, int point_num, int cluster_num, int it_max,
int &it_num, double point[], int cluster[], double cluster_center[],
int cluster_population[], double cluster_energy[] )
//****************************************************************************80
//
// Purpose:
//
// KMEANS_01 applies the K-Means algorithm.
//
// Discussion:
//
// Given a matrix of POINT_NUM observations on DIM_NUM variables, the
// observations are to be allocated to CLUSTER_NUM clusters in such
// a way that the within-cluster sum of squares is minimized.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 October 2011
//
// Author:
//
// Original FORTRAN77 version by David Sparks.
// C++ version by John Burkardt.
//
// Reference:
//
// David Sparks,
// Algorithm AS 58:
// Euclidean Cluster Analysis,
// Applied Statistics,
// Volume 22, Number 1, 1973, pages 126-130.
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int IT_MAX, the maximum number of iterations.
//
// Output, int IT_NUM, the number of iterations taken.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the points.
//
// Output, int CLUSTER[POINT_NUM], indicates which cluster
// each point belongs to.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM],
// the cluster centers.
//
// Output, int CLUSTER_POPULATION[CLUSTER_NUM], the number
// of points in each cluster.
//
// Output, double CLUSTER_ENERGY[CLUSTER_NUM], the
// cluster energies.
//
{
double dc;
double de;
double *f;
int i;
int il;
int ir;
int j;
int j2;
int k;
double point_energy;
double point_energy_min;
int swap;
it_num = 0;
//
// Idiot checks.
//
if ( cluster_num < 1 )
{
cout << "\n";
cout << "KMEANS_01 - Fatal error!\n";
cout << " CLUSTER_NUM < 1.\n";
exit ( 1 );
}
if ( dim_num < 1 )
{
cout << "\n";
cout << "KMEANS_01 - Fatal error!\n";
cout << " DIM_NUM < 1.\n";
exit ( 1 );
}
if ( point_num < 1 )
{
cout << "\n";
cout << "KMEANS_01 - Fatal error!\n";
cout << " POINT_NUM < 1.\n";
exit ( 1 );
}
//
// For each observation, calculate the distance from each cluster
// center, and assign to the nearest.
//
for ( j = 0; j < point_num; j++ )
{
point_energy_min = r8_huge ( );
cluster[j] = -1;
for ( k = 0; k < cluster_num; k++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k;
}
}
}
//
// Determine the cluster population counts.
//
i4vec_zero ( cluster_num, cluster_population );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
cluster_population[k] = cluster_population[k] + 1;
}
//
// Calculate the mean and sum of squares for each cluster.
//
r8vec_zero ( dim_num * cluster_num, cluster_center );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ point[i+j*dim_num];
}
}
for ( k = 0; k < cluster_num; k++ )
{
if ( 0 < cluster_population[k] )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num] /
( double ) cluster_population[k];
}
}
}
//
// Set the point energies.
//
f = r8vec_zero_new ( point_num );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
for ( i = 0; i < dim_num; i++ )
{
f[j] = f[j] + pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
}
//
// Set the cluster energies.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
cluster_energy[k] = cluster_energy[k] + f[j];
}
//
// Adjust the point energies by a weight factor.
//
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
if ( 1 < cluster_population[k] )
{
f[j] = f[j] * ( double ) ( cluster_population[k] )
/ ( double ) ( cluster_population[k] - 1 );
}
}
//
// Examine each observation in turn to see if it should be
// reassigned to a different cluster.
//
it_num = 0;
while ( it_num < it_max )
{
it_num = it_num + 1;
swap = 0;
for ( j = 0; j < point_num; j++ )
{
il = cluster[j];
ir = il;
if ( cluster_population[il] <= 1 )
{
continue;
}
dc = f[j];
for ( k = 0; k < cluster_num; k++ )
{
if ( k != il )
{
de = 0.0;
for ( i = 0; i < dim_num; i++ )
{
de = de + pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
de = de * ( double ) cluster_population[k]
/ ( double ) ( cluster_population[k] + 1 );
if ( de < dc )
{
dc = de;
ir = k;
}
}
}
//
// If the lowest value was obtained by staying in the current cluster,
// then cycle.
//
if ( ir == il )
{
continue;
}
//
// Reassign the point from cluster IL to cluster IR.
//
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+il*dim_num] = ( cluster_center[i+il*dim_num]
* ( double ) ( cluster_population[il] ) - point[i+j*dim_num] )
/ ( double ) ( cluster_population[il] - 1 );
cluster_center[i+ir*dim_num] = ( cluster_center[i+ir*dim_num]
* ( double ) ( cluster_population[ir] ) + point[i+j*dim_num] )
/ ( double ) ( cluster_population[ir] + 1 );
}
cluster_energy[il] = cluster_energy[il] - f[j];
cluster_energy[ir] = cluster_energy[ir] + dc;
cluster_population[ir] = cluster_population[ir] + 1;
cluster_population[il] = cluster_population[il] - 1;
cluster[j] = ir;
//
// Adjust the value of F for points in clusters IL and IR.
//
for ( j2 = 0; j2 < point_num; j2++ )
{
k = cluster[j2];
if ( k == il || k == ir )
{
f[j2] = 0.0;
for ( i = 0; i < dim_num; i++ )
{
f[j2] = f[j2] + pow ( point[i+j2*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( 1 < cluster_population[k] )
{
f[j2] = f[j2] * ( double ) ( cluster_population[k] )
/ ( ( double ) ( cluster_population[k] - 1 ) );
}
}
}
swap = swap + 1;
}
//
// Exit if no reassignments were made during this iteration.
//
if ( swap == 0 )
{
break;
}
}
//
// Compute the cluster energies.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + point_energy;
}
delete [] f;
return;
}
//****************************************************************************80
void kmeans_02 ( int dim_num, int point_num, int cluster_num, int it_max,
int &it_num, double point[], int cluster[], double cluster_center[],
int cluster_population[], double cluster_energy[] )
//****************************************************************************80
//
// Purpose:
//
// KMEANS_02 applies the K-Means algorithm.
//
// Discussion:
//
// The routine attempts to divide POINT_NUM points in
// DIM_NUM-dimensional space into CLUSTER_NUM clusters so that the within
// cluster sum of squares is minimized.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 2011
//
// Author:
//
// Original FORTRAN77 by John Hartigan, Manchek Wong.
// C++ version by John Burkardt.
//
// Reference:
//
// John Hartigan, Manchek Wong,
// Algorithm AS 136:
// A K-Means Clustering Algorithm,
// Applied Statistics,
// Volume 28, Number 1, 1979, pages 100-108.
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int IT_MAX, the maximum number of iterations.
//
// Output, int &IT_NUM, the number of iterations taken.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates
// of the points.
//
// Output, int CLUSTER[POINT_NUM], the cluster each
// point belongs to.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM],
// the cluster centers.
//
// Output, int CLUSTER_POPULATION[CLUSTER_NUM], the number
// of points in each cluster.
//
// Output, double CLUSTER_ENERGY[CLUSTER_NUM], the
// within-cluster sum of squares.
//
{
double *an1;
double *an2;
int *cluster2;
double *d;
double db;
double dt[2];
int i;
int ifault;
int il;
int indx;
int *itran;
int j;
int k;
int l;
int *live;
int *ncp;
double point_energy;
double temp;
it_num = 0;
if ( cluster_num < 1 )
{
cout << "\n";
cout << "KMEANS_02 - Fatal error!\n";
cout << " CLUSTER_NUM < 1.\n";
exit ( 1 );
}
if ( point_num <= cluster_num )
{
cout << "\n";
cout << "KMEANS_02 - Fatal error!\n";
cout << " POINT_NUM <= CLUSTER_NUM.\n";
exit ( 1 );
}
if ( dim_num < 1 )
{
cout << "\n";
cout << "KMEANS_02 - Fatal error!\n";
cout << " DIM_NUM < 1.\n";
exit ( 1 );
}
if ( point_num < 1 )
{
cout << "\n";
cout << "KMEANS_02 - Fatal error!\n";
cout << " POINT_NUM < 1.\n";
exit ( 1 );
}
//
// For each point I, find its two closest centers, CLUSTER(I) and CLUSTER2(I).
// Assign it to CLUSTER(I).
//
cluster2 = new int[point_num];
for ( j = 0; j < point_num; j++ )
{
cluster[j] = 0;
cluster2[j] = 1;
for ( il = 0; il < 2; il++ )
{
dt[il] = 0.0;
for ( i = 0; i < dim_num; i++ )
{
dt[il] = dt[il] + pow ( point[i+j*dim_num] - cluster_center[i+il*dim_num], 2 );
}
}
if ( dt[1] < dt[0] )
{
cluster[j] = 1;
cluster2[j] = 0;
temp = dt[0];
dt[0] = dt[1];
dt[1] = temp;
}
for ( k = 2; k < cluster_num; k++ )
{
db = 0.0;
for ( i = 0; i < dim_num; i++ )
{
db = db + pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( db < dt[0] )
{
dt[1] = dt[0];
cluster2[j] = cluster[j];
dt[0] = db;
cluster[j] = k;
}
else if ( db < dt[1] )
{
dt[1] = db;
cluster2[j] = k;
}
}
}
//
// Update cluster centers to be the average of points contained
// within them.
//
i4vec_zero ( cluster_num, cluster_population );
r8vec_zero ( dim_num * cluster_num, cluster_center );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
cluster_population[k] = cluster_population[k] + 1;
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ point[i+j*dim_num];
}
}
//
// Check to see if there is any empty cluster.
//
an1 = new double[cluster_num];
an2 = new double[cluster_num];
itran = new int[cluster_num];
ncp = new int[cluster_num];
for ( k = 0; k < cluster_num; k++ )
{
if ( cluster_population[k] == 0 )
{
cout << "\n";
cout << "KMEANS_02 - Fatal error!\n";
cout << " Cluster " << k << " has zero population.\n";
exit ( 1 );
}
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
/ ( double ) ( cluster_population[k] );
}
//
// Initialize AN1, AN2, ITRAN and NCP
// AN1(K) = CLUSTER_POPULATION(K) / (CLUSTER_POPULATION(K) - 1)
// AN2(K) = CLUSTER_POPULATION(K) / (CLUSTER_POPULATION(K) + 1)
// ITRAN(K) = 1 if cluster K is updated in the quick-transfer stage,
// = 0 otherwise
// In the optimal-transfer stage, NCP(K) stores the step at which
// cluster K is last updated.
// In the quick-transfer stage, NCP(K) stores the step at which
// cluster K is last updated plus POINT_NUM.
//
an2[k] = ( double ) ( cluster_population[k] )
/ ( double ) ( cluster_population[k] + 1 );
if ( 1 < cluster_population[k] )
{
an1[k] = ( double ) ( cluster_population[k] )
/ ( double ) ( cluster_population[k] - 1 );
}
else
{
an1[k] = r8_huge ( );
}
itran[k] = 1;
ncp[k] = -1;
}
indx = 0;
ifault = 2;
it_num = 0;
d = new double[point_num];
live = new int[cluster_num];
while ( it_num < it_max )
{
it_num = it_num + 1;
//
// In this stage, there is only one pass through the data. Each
// point is re-allocated, if necessary, to the cluster that will
// induce the maximum reduction in within-cluster sum of squares.
//
kmeans_02_optra ( dim_num, point_num, cluster_num, point,
cluster_center, cluster, cluster2, cluster_population, an1, an2,
ncp, d, itran, live, indx );
//
// Stop if no transfer took place in the last POINT_NUM optimal transfer steps.
//
if ( indx == point_num )
{
ifault = 0;
break;
}
//
// Each point is tested in turn to see if it should be re-allocated
// to the cluster to which it is most likely to be transferred,
// CLUSTER2(I), from its present cluster, CLUSTER(I). Loop through the
// data until no further change is to take place.
//
kmeans_02_qtran ( dim_num, point_num, cluster_num, point,
cluster_center, cluster, cluster2, cluster_population, an1, an2,
ncp, d, itran, indx );
//
// If there are only two clusters, there is no need to re-enter the
// optimal transfer stage.
//
if ( cluster_num == 2 )
{
ifault = 0;
break;
}
//
// NCP has to be set to 0 before entering OPTRA.
//
i4vec_zero ( cluster_num, ncp );
}
if ( ifault == 2 )
{
cout << "\n";
cout << "KMEANS_02 - Warning!\n";
cout << " Maximum number of iterations reached\n";
cout << " without convergence.\n";
}
//
// Compute the within-cluster sum of squares for each cluster.
//
r8vec_zero ( dim_num * cluster_num, cluster_center );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ point[i+j*dim_num];
}
}
for ( k = 0; k < cluster_num; k++ )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
/ ( double ) cluster_population[k];
}
}
//
// Compute the cluster energies.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + point_energy;
}
delete [] an1;
delete [] an2;
delete [] cluster2;
delete [] d;
delete [] itran;
delete [] live;
delete [] ncp;
return;
}
//****************************************************************************80
void kmeans_02_optra ( int dim_num, int point_num, int cluster_num,
double point[], double cluster_center[], int cluster[], int cluster2[],
int cluster_population[], double an1[], double an2[], int ncp[],
double d[], int itran[], int live[], int &indx )
//****************************************************************************80
//
// Purpose:
//
// KMEANS_02_OPTRA carries out the optimal transfer stage.
//
// Discussion:
//
// Each point is re-allocated, if necessary, to the cluster that
// will induce a maximum reduction in the within-cluster sum of
// squares.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 October 2011
//
// Author:
//
// Original FORTRAN77 by John Hartigan, Manchek Wong.
// C++ version by John Burkardt.
//
// Reference:
//
// John Hartigan, Manchek Wong,
// Algorithm AS 136:
// A K-Means Clustering Algorithm,
// Applied Statistics,
// Volume 28, Number 1, 1979, pages 100-108.
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates of
// the points.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM],
// the cluster centers.
//
// Input/output, int CLUSTER[POINT_NUM], the cluster
// each point belongs to.
//
// Input/output, int CLUSTER2[POINT_NUM], the cluster
// to which each point is most likely to be transferred to.
//
// Input/output, int CLUSTER_POPULATION[CLUSTER_NUM],
// the number of points in each cluster.
//
// Input/output, double AN1[CLUSTER_NUM],
// CLUSTER_POPULATION(L) / (CLUSTER_POPULATION(L) - 1)
//
// Input/output, double AN2[CLUSTER_NUM],
// CLUSTER_POPULATION(L) / (CLUSTER_POPULATION(L) + 1)
//
// Input/output, int NCP[CLUSTER_NUM], ?
//
// Input/output, double D[POINT_NUM], ?
//
// Input/output, int ITRAN[CLUSTER_NUM],
// 1 if cluster L is updated in the quick-transfer stage,
// 0 otherwise. Reset to zero on output.
//
// Input/output, int LIVE[CLUSTER_NUM], ?
//
// Input/output, int INDX, ?
//
{
double al1;
double al2;
double alt;
double alw;
double dc;
int i;
int j;
int k;
int l;
int l1;
int l2;
int ll;
double r2;
double rr;
//
// If cluster L is updated in the last quick-transfer stage, it
// belongs to the live set throughout this stage. Otherwise, at
// each step, it is not in the live set if it has not been updated
// in the last POINT_NUM optimal transfer steps.
//
for ( k = 0; k < cluster_num; k++ )
{
if ( itran[k] == 1 )
{
live[k] = point_num + 1;
}
}
for ( j = 0; j < point_num; j++ )
{
indx = indx + 1;
l1 = cluster[j];
l2 = cluster2[j];
ll = l2;
//
// If point J is the only member of cluster L1, no transfer.
//
if ( 1 < cluster_population[l1] )
{
//
// If L1 has been updated in this stage, re-compute D(I).
//
if ( ncp[l1] != 0 )
{
d[j] = 0.0;
for ( i = 0; i < dim_num; i++ )
{
d[j] = d[j] + pow ( point[i+j*dim_num] - cluster_center[i+l1*dim_num], 2 );
}
d[j] = an1[l1] * d[j];
}
//
// Find the cluster with minimum R2.
//
r2 = 0.0;
for ( i = 0; i < dim_num; i++ )
{
r2 = r2 + pow ( point[i+j*dim_num] - cluster_center[i+l2*dim_num], 2 );
}
r2 = an2[l2] * r2;
for ( l = 0; l < cluster_num; l++ )
{
//
// If LIVE(L1) <= J, then L1 is not in the live set. If this is
// true, we only need to consider clusters that are in the live set
// for possible transfer of point J.
//
// Otherwise, we need to consider all possible clusters.
//
if ( ( j < live[l1] || j < live[l] ) && l != l1 && l != ll )
{
rr = r2 / an2[l];
dc = 0.0;
for ( i = 0; i < dim_num; i++ )
{
dc = dc + pow ( point[i+j*dim_num] - cluster_center[i+l*dim_num], 2 );
}
if ( dc < rr )
{
r2 = dc * an2[l];
l2 = l;
}
}
}
//
// If no transfer is necessary, L2 is the new CLUSTER2(J).
//
if ( d[j] <= r2 )
{
cluster2[j] = l2;
}
//
// Update cluster centers, LIVE, NCP, AN1 and AN2 for clusters L1 and
// L2, and update CLUSTER(J) and CLUSTER2(J).
//
else
{
indx = 0;
live[l1] = point_num + j;
live[l2] = point_num + j;
ncp[l1] = j;
ncp[l2] = j;
al1 = cluster_population[l1];
alw = al1 - 1.0;
al2 = cluster_population[l2];
alt = al2 + 1.0;
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+l1*dim_num] = ( cluster_center[i+l1*dim_num] * al1
- point[i+j*dim_num] ) / alw;
cluster_center[i+l2*dim_num] = ( cluster_center[i+l2*dim_num] * al2
+ point[i+j*dim_num] ) / alt;
}
cluster_population[l1] = cluster_population[l1] - 1;
cluster_population[l2] = cluster_population[l2] + 1;
an2[l1] = alw / al1;
if ( 1.0 < alw )
{
an1[l1] = alw / ( alw - 1.0 );
}
else
{
an1[l1] = r8_huge ( );
}
an1[l2] = alt / al2;
an2[l2] = alt / ( alt + 1.0 );
cluster[j] = l2;
cluster2[j] = l1;
}
}
if ( indx == point_num )
{
return;
}
}
//
// ITRAN(L) = 0 before entering QTRAN.
//
i4vec_zero ( cluster_num, itran );
//
// LIVE(L) has to be decreased by POINT_NUM before re-entering OPTRA.
//
for ( k = 0; k < cluster_num; k++ )
{
live[k] = live[k] - point_num;
}
return;
}
//****************************************************************************80
void kmeans_02_qtran ( int dim_num, int point_num, int cluster_num,
double point[], double cluster_center[], int cluster[], int cluster2[],
int cluster_population[], double an1[], double an2[], int ncp[], double d[],
int itran[], int &indx )
//****************************************************************************80
//
// Purpose:
//
// KMEANS_02_QTRAN carries out the quick transfer stage.
//
// Discussion:
//
// For each point I, CLUSTER(I) and CLUSTER2(I) are switched, if necessary,
// to reduce within-cluster sum of squares. The cluster centers are
// updated after each step.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 13 October 2011
//
// Author:
//
// Original FORTRAN77 by John Hartigan, Manchek Wong.
// C++ version by John Burkardt.
//
// Reference:
//
// John Hartigan, Manchek Wong,
// Algorithm AS 136:
// A K-Means Clustering Algorithm,
// Applied Statistics,
// Volume 28, Number 1, 1979, pages 100-108.
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the coordinates
// of the points.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM],
// the cluster centers.
//
// Input/output, int CLUSTER[POINT_NUM], the cluster
// each point belongs to.
//
// Input/output, int CLUSTER2[POINT_NUM], the cluster to
// which each point is most likely to be transferred to.
//
// Input/output, int CLUSTER_POPULATION[CLUSTER_NUM],
// the number of points in each cluster.
//
// Input/output, double AN1[CLUSTER_NUM],
// CLUSTER_POPULATION(L) / (CLUSTER_POPULATION(L) - 1).
//
// Input/output, double AN2[CLUSTER_NUM],
// CLUSTER_POPULATION(L) / (CLUSTER_POPULATION(L) + 1).
//
// Input/output, int NCP[CLUSTER_NUM], ?
//
// Input/output, double D[POINT_NUM], ?
//
// Input/output, int ITRAN[CLUSTER_NUM],
// 1 if cluster L is updated in the quick-transfer stage,
// 0 otherwise.
//
// Input/output, int INDX, is set to 0 if any
// updating occurs.
//
{
double al1;
double al2;
double alt;
double alw;
int count;
double dd;
int i;
int j;
int l1;
int l2;
double r2;
int step;
//
// In the optimal transfer stage, NCP(L) indicates the step at which
// cluster L is last updated. In the quick transfer stage, NCP(L)
// is equal to the step at which cluster L is last updated plus POINT_NUM.
//
count = 0;
step = 0;
for ( ; ; )
{
for ( j = 0; j < point_num; j++ )
{
count = count + 1;
step = step + 1;
l1 = cluster[j];
l2 = cluster2[j];
//
// If point I is the only member of cluster L1, no transfer.
//
if ( 1 < cluster_population[l1] )
{
//
// If NCP(L1) < STEP, no need to re-compute distance from point I to
// cluster L1. Note that if cluster L1 is last updated exactly POINT_NUM
// steps ago, we still need to compute the distance from point I to
// cluster L1.
//
if ( step <= ncp[l1] )
{
d[j] = 0.0;
for ( i = 0; i < dim_num; i++ )
{
d[j] = d[j] + pow ( point[i+j*dim_num] - cluster_center[i+l1*dim_num], 2 );
}
d[j] = an1[l1] * d[j];
}
//
// If STEP >= both NCP(L1) and NCP(L2) there will be no transfer of
// point I at this step.
//
if ( step < ncp[l1] || step < ncp[l2] )
{
r2 = d[j] / an2[l2];
dd = 0.0;
for ( i = 0; i < dim_num; i++ )
{
dd = dd + pow ( point[i+j*dim_num] - cluster_center[i+l2*dim_num], 2 );
}
//
// Update cluster centers, NCP, CLUSTER_POPULATION, ITRAN, AN1 and AN2
// for clusters L1 and L2. Also update CLUSTER(J) and CLUSTER2(J).
//
// Note that if any updating occurs in this stage, INDX is set back to 0.
//
if ( dd < r2 )
{
count = 0;
indx = 0;
itran[l1] = 1;
itran[l2] = 1;
ncp[l1] = step + point_num;
ncp[l2] = step + point_num;
al1 = cluster_population[l1];
alw = al1 - 1.0;
al2 = cluster_population[l2];
alt = al2 + 1.0;
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+l1*dim_num] = ( cluster_center[i+l1*dim_num] * al1
- point[i+j*dim_num] ) / alw;
cluster_center[i+l2*dim_num] = ( cluster_center[i+l2*dim_num] * al2
+ point[i+j*dim_num] ) / alt;
}
cluster_population[l1] = cluster_population[l1] - 1;
cluster_population[l2] = cluster_population[l2] + 1;
an2[l1] = alw / al1;
if ( 1.0 < alw )
{
an1[l1] = alw / ( alw - 1.0 );
}
else
{
an1[l1] = r8_huge ( );
}
an1[l2] = alt / al2;
an2[l2] = alt / ( alt + 1.0 );
cluster[j] = l2;
cluster2[j] = l1;
}
}
}
//
// If no re-allocation took place in the last POINT_NUM steps, return.
//
if ( count == point_num )
{
return;
}
}
}
return;
}
//****************************************************************************80
void kmeans_03 ( int dim_num, int point_num, int cluster_num, int it_max,
int &it_num, double point[], int cluster[], double cluster_center[],
int cluster_population[], double cluster_energy[] )
//****************************************************************************80
//
// Purpose:
//
// KMEANS_03 applies the K-Means algorithm.
//
// Discussion:
//
// It is possible for a straightforward K-Means algorithm to
// halt at a non-optimal partition of the points. This routine
// tries to improve the input partition if possible.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 October 2011
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Wendy Martinez, Angel Martinez,
// Computational Statistics Handbook with MATLAB,
// pages 373-376,
// Chapman and Hall / CRC, 2002.
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of data points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int IT_MAX, the maximum number of iterations.
//
// Output, int IT_NUM, the number of iterations taken.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the data points.
//
// Output, int CLUSTER[POINT_NUM], the cluster to which
// each point belongs.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM], the
// centers associated with the clustering. On output, these may
// have been altered.
//
// Output, int CLUSTER_POPULATION[CLUSTER_NUM], the number
// of points in each cluster.
//
// Output, double CLUSTER_ENERGY[CLUSTER_NUM], the energy of
// the clusters.
//
{
int ci;
int cj;
bool debug = true;
double *distsq;
int i;
int j;
int k;
double point_energy;
double point_energy_min;
int swap;
//
// Check the input.
//
if ( cluster_num < 1 )
{
cout << "\n";
cout << "KMEANS_03 - Fatal error!\n";
cout << " CLUSTER_NUM < 1.\n";
exit ( 1 );
}
if ( dim_num < 1 )
{
cout << "\n";
cout << "KMEANS_03 - Fatal error!\n";
cout << " DIM_NUM < 1.\n";
exit ( 1 );
}
if ( point_num < 1 )
{
cout << "\n";
cout << "KMEANS_03 - Fatal error!\n";
cout << " POINT_NUM < 1.\n";
exit ( 1 );
}
if ( it_max < 0 )
{
cout << "\n";
cout << "KMEANS_03 - Fatal error!\n";
cout << " IT_MAX < 0.\n";
exit ( 1 );
}
//
// Assign each point to the nearest cluster center.
//
for ( j = 0; j < point_num; j++ )
{
point_energy_min = r8_huge ( );
cluster[j] = -1;
for ( k = 0; k < cluster_num; k++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k;
}
}
}
//
// Determine the cluster populations.
//
i4vec_zero ( cluster_num, cluster_population );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
cluster_population[k] = cluster_population[k] + 1;
}
//
// Average the points in each cluster to get a new cluster center.
//
r8vec_zero ( dim_num * cluster_num, cluster_center );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ point[i+j*dim_num];
}
}
for ( k = 0; k < cluster_num; k++ )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
/ ( double ) ( cluster_population[k] );
}
}
//
// Carry out the iteration.
//
it_num = 0;
distsq = new double[cluster_num];
while ( it_num < it_max )
{
it_num = it_num + 1;
swap = 0;
for ( j = 0; j < point_num; j++ )
{
ci = cluster[j];
if ( cluster_population[ci] <= 1 )
{
continue;
}
for ( cj = 0; cj < cluster_num; cj++ )
{
if ( cj == ci )
{
distsq[cj] = 0.0;
for ( i = 0; i < dim_num; i++ )
{
distsq[cj] = distsq[cj]
+ pow ( point[i+j*dim_num] - cluster_center[i+cj*dim_num], 2 );
}
distsq[cj] = distsq[cj] * ( double ) ( cluster_population[cj] )
/ ( double ) ( cluster_population[cj] - 1 );
}
else if ( cluster_population[cj] == 0 )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+cj*dim_num] = point[i+j*dim_num];
}
distsq[cj] = 0.0;
}
else
{
distsq[cj] = 0.0;
for ( i = 0; i < dim_num; i++ )
{
distsq[cj] = distsq[cj]
+ pow ( point[i+j*dim_num] - cluster_center[i+cj*dim_num], 2 );
}
distsq[cj] = distsq[cj] * ( double ) ( cluster_population[cj] )
/ ( double ) ( cluster_population[cj] + 1 );
}
}
//
// Find the index of the minimum value of DISTSQ.
//
k = r8vec_min_index ( cluster_num, distsq );
//
// If that is not the cluster to which point I now belongs, move it there.
//
if ( k == ci )
{
continue;
}
cj = k;
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+ci*dim_num] = ( ( double ) ( cluster_population[ci] )
* cluster_center[i+ci*dim_num] - point[i+j*dim_num] )
/ ( double ) ( cluster_population[ci] - 1 );
cluster_center[i+cj*dim_num] = ( ( double ) ( cluster_population[cj] )
* cluster_center[i+cj*dim_num] + point[i+j*dim_num] )
/ ( double ) ( cluster_population[cj] + 1 );
}
cluster_population[ci] = cluster_population[ci] - 1;
cluster_population[cj] = cluster_population[cj] + 1;
cluster[j] = cj;
swap = swap + 1;
}
//
// Exit if no reassignments were made during this iteration.
//
if ( swap == 0 )
{
break;
}
}
//
// Compute the cluster energies.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + point_energy;
}
delete [] distsq;
return;
}
//****************************************************************************80
void kmeans_w_01 ( int dim_num, int point_num, int cluster_num, int it_max,
int &it_num, double point[], double weight[], int cluster[],
double cluster_center[], int cluster_population[], double cluster_energy[] )
//****************************************************************************80
//
// Purpose:
//
// KMEANS_W_01 applies the weighted K-Means algorithm.
//
// Discussion:
//
// The input data for the weight K-Means problem includes:
// * a set of N data points X in M dimensions,
// * a set of N nonnegative weights W,
// * a desired number of clusters K.
// * an initial set of cluster centers Z,
// * an (optional) initial set of cluster assignments.
//
// The goal is to determine K points Z, called cluster centers, and
// to assign each point X(I) to some cluster Z(J), so that we minimize
// the weighted standard deviation of the distance of each data point
// to the center of its cluster. Writing J = CLUSTER(I) to
// indicate the index of the nearest cluster center Z(J) to the
// point X(I), the quantity we are trying to minimize is the sum
// of the weighted cluster energies E(J), where:
//
// E(J) = Sum ( 1 <= I <= N ) W(I) * || X(I) - Z(J) ||^2
//
// Here, we assume that we are using the Euclidean norm, so that
//
// || X(I) - Z(J) ||^2 = Sum ( 1 <= K <= M )
// ( X(I)(K) - Z(J)(K) )^2
//
// In this notation, X(I)(K) is the K-th spatial component of the
// I-th data point.
//
// Note that this routine should give the same results as KMEANS_01
// in any case in which all the entries of the WEIGHT vector are equal.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 October 2011
//
// Author:
//
// John Burkardt
//
// Reference:
//
// David Sparks,
// Algorithm AS 58: Euclidean Cluster Analysis,
// Applied Statistics,
// Volume 22, Number 1, 1973, pages 126-130.
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int IT_MAX, the maximum number of iterations.
//
// Output, int &IT_NUM, the number of iterations taken.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the points.
//
// Input, double WEIGHT[POINT_NUM], the weights.
//
// Output, int CLUSTER[POINT_NUM], indicates which cluster
// each point belongs to.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM],
// the cluster centers.
//
// Output, int CLUSTER_POPULATION[CLUSTER_NUM], the number
// of points in each cluster.
//
// Output, double CLUSTER_ENERGY[CLUSTER_NUM], the
// cluster energies.
//
{
int c;
double *cluster_weight;
double dc;
double de;
double *f;
int i;
int il;
int ir;
int j;
int k;
double point_energy;
double point_energy_min;
int swap;
it_num = 0;
//
// Idiot checks.
//
if ( cluster_num < 1 )
{
cout << "\n";
cout << "KMEANS_W_01 - Fatal error!\n";
cout << " CLUSTER_NUM < 1.\n";
exit ( 1 );
}
if ( dim_num < 1 )
{
cout << "\n";
cout << "KMEANS_W_01 - Fatal error!\n";
cout << " DIM_NUM < 1.\n";
exit ( 1 );
}
if ( point_num < 1 )
{
cout << "\n";
cout << "KMEANS_W_01 - Fatal error!\n";
cout << " POINT_NUM < 1.\n";
exit ( 1 );
}
if ( it_max < 0 )
{
cout << "\n";
cout << "KMEANS_W_01 - Fatal error!\n";
cout << " IT_MAX < 0.\n";
exit ( 1 );
}
if ( r8vec_any_negative ( point_num, weight ) )
{
cout << "\n";
cout << "KMEANS_W_01 - Fatal error!\n";
cout << " Some weight entry is negative.\n";
exit ( 1 );
}
if ( r8vec_all_nonpositive ( point_num, weight ) )
{
cout << "\n";
cout << "KMEANS_W_01 - Fatal error!\n";
cout << " No weight entry is positive.\n";
exit ( 1 );
}
//
// Assign each point to the nearest cluster.
//
for ( j = 0; j < point_num; j++ )
{
point_energy_min = r8_huge ( );
cluster[j] = -1;
for ( k = 0; k < cluster_num; k++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k;
}
}
}
//
// Determine the cluster populations and weights.
//
i4vec_zero ( cluster_num, cluster_population );
cluster_weight = r8vec_zero_new ( cluster_num );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
cluster_population[k] = cluster_population[k] + 1;
cluster_weight[k] = cluster_weight[k] + weight[j];
}
//
// Calculate the mean and sum of squares for each cluster.
//
r8vec_zero ( dim_num * cluster_num, cluster_center );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ weight[j] * point[i+j*dim_num];
}
}
for ( k = 0; k < cluster_num; k++ )
{
if ( 0.0 < cluster_weight[k] )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
/ cluster_weight[k];
}
}
}
//
// Set the point energies.
//
f = r8vec_zero_new ( point_num );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
for ( i = 0; i < dim_num; i++ )
{
f[j] = f[j] + pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
}
//
// Set the cluster energies.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
cluster_energy[k] = cluster_energy[k] + weight[j] * f[j];
}
//
// Adjust the point energies by a weight factor.
//
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
if ( weight[j] < cluster_weight[k] )
{
f[j] = f[j] * cluster_weight[k] / ( cluster_weight[k] - weight[j] );
}
}
//
// Examine each observation in turn to see if it should be
// reassigned to a different cluster.
//
it_num = 0;
while ( it_num < it_max )
{
it_num = it_num + 1;
swap = 0;
for ( j = 0; j < point_num; j++ )
{
il = cluster[j];
ir = il;
if ( cluster_population[il] <= 1 )
{
continue;
}
dc = f[j];
for ( k = 0; k < cluster_num; k++ )
{
if ( k != il )
{
de = 0.0;
for ( i = 0; i < dim_num; i++ )
{
de = de + pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 )
* cluster_weight[k] / ( cluster_weight[k] + weight[j] );
}
if ( de < dc )
{
dc = de;
ir = k;
}
}
}
//
// If the lowest value was obtained by staying in the current cluster,
// then cycle.
//
if ( ir == il )
{
continue;
}
//
// Reassign the point from cluster IL to cluster IR.
//
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+il*dim_num] =
( cluster_weight[il] * cluster_center[i+il*dim_num]
- weight[j] * point[i+j*dim_num] )
/ ( cluster_weight[il] - weight[j] );
cluster_center[i+ir*dim_num] =
( cluster_weight[ir] * cluster_center[i+ir*dim_num]
+ weight[j] * point[i+j*dim_num] )
/ ( cluster_weight[ir] + weight[j] );
}
cluster_weight[il] = cluster_weight[il] - weight[j];
cluster_weight[ir] = cluster_weight[ir] + weight[j];
cluster_energy[il] = cluster_energy[il] - f[j];
cluster_energy[ir] = cluster_energy[ir] + dc;
cluster_population[ir] = cluster_population[ir] + 1;
cluster_population[il] = cluster_population[il] - 1;
cluster[j] = ir;
//
// Adjust the value of F for all points in clusters IL and IR.
//
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
if ( k == il || k == ir )
{
f[j] = 0.0;
for ( i = 0; i < dim_num; i++ )
{
f[j] = f[j] + pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( weight[j] < cluster_weight[k] )
{
f[j] = f[j] * cluster_weight[k] / ( cluster_weight[k] - weight[j] );
}
}
}
swap = swap + 1;
}
//
// Exit if no reassignments were made during this iteration.
//
if ( swap == 0 )
{
break;
}
}
//
// Compute the energy based on the final value of the cluster centers.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + weight[j] * point_energy;
}
delete [] cluster_weight;
delete [] f;
return;
}
//****************************************************************************80
void kmeans_w_03 ( int dim_num, int point_num, int cluster_num, int it_max,
int &it_num, double point[], double weight[], int cluster[],
double cluster_center[], int cluster_population[], double cluster_energy[] )
//****************************************************************************80
//
// Purpose:
//
// KMEANS_W_03 applies the weighted K-Means algorithm.
//
// Discussion:
//
// The input data for the weight K-Means problem includes:
// * a set of N data points X in M dimensions,
// * a set of N nonnegative weights W,
// * a desired number of clusters K.
// * an initial set of cluster centers Z,
// * an (optional) initial set of cluster assignments.
//
// The goal is to determine K points Z, called cluster centers, and
// to assign each point X(I) to some cluster Z(J), so that we minimize
// the weighted standard deviation of the distance of each data point
// to the center of its cluster. Writing J = CLUSTER(I) to
// indicate the index of the nearest cluster center Z(J) to the
// point X(I), the quantity we are trying to minimize is the sum
// of the weighted cluster energies E(J), where:
//
// E(J) = Sum ( 1 <= I <= N ) W(I) * || X(I) - Z(J) ||^2
//
// Here, we assume that we are using the Euclidean norm, so that
//
// || X(I) - Z(J) ||^2 = Sum ( 1 <= K <= M )
// ( X(I)(K) - Z(J)(K) )^2
//
// In this notation, X(I)(K) is the K-th spatial component of the
// I-th data point.
//
// Note that this routine should give the same results as KMEANS_01
// in any case in which all the entries of the WEIGHT vector are equal.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 October 2011
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Wendy Martinez, Angel Martinez,
// Computational Statistics Handbook with MATLAB,
// pages 373-376,
// Chapman and Hall / CRC, 2002.
//
// Parameters:
//
// Input, int DIM_NUM, the number of spatial dimensions.
//
// Input, int POINT_NUM, the number of data points.
//
// Input, int CLUSTER_NUM, the number of clusters.
//
// Input, int IT_MAX, the maximum number of iterations.
//
// Output, int IT_NUM, the number of iterations taken.
//
// Input, double POINT[DIM_NUM*POINT_NUM], the data points.
//
// Input, double WEIGHT[POINT_NUM], the weights.
//
// Input/output, int CLUSTER[POINT_NUM], the cluster
// to which each point belongs. On output, these may have been altered.
//
// Input/output, double CLUSTER_CENTER[DIM_NUM*CLUSTER_NUM], the
// centers associated with the clustering. On output, these may
// have been altered.
//
// Output, int CLUSTER_POPULATION[CLUSTER_NUM], the number
// of points in each cluster.
//
// Output, double CLUSTER_ENERGY[CLUSTER_NUM], the energy of
// the clusters.
//
{
int ci;
int cj;
double *cluster_weight;
bool debug = true;
double *distsq;
int i;
int j;
int k;
double point_energy;
double point_energy_min;
int swap;
//
// Check the input.
//
if ( cluster_num < 1 )
{
cout << "\n";
cout << "KMEANS_W_03 - Fatal error!\n";
cout << " CLUSTER_NUM < 1.\n";
exit ( 1 );
}
if ( dim_num < 1 )
{
cout << "\n";
cout << "KMEANS_W_03 - Fatal error!\n";
cout << " DIM_NUM < 1.\n";
exit ( 1 );
}
if ( point_num < 1 )
{
cout << "\n";
cout << "KMEANS_W_03 - Fatal error!\n";
cout << " POINT_NUM < 1.\n";
exit ( 1 );
}
if ( it_max < 0 )
{
cout << "\n";
cout << "KMEANS_W_03 - Fatal error!\n";
cout << " IT_MAX < 0.\n";
exit ( 1 );
}
if ( r8vec_any_negative ( point_num, weight ) )
{
cout << "\n";
cout << "KMEANS_W_03 - Fatal error!\n";
cout << " Some weight entry is negative.\n";
exit ( 1 );
}
if ( r8vec_all_nonpositive ( point_num, weight ) )
{
cout << "\n";
cout << "KMEANS_W_03 - Fatal error!\n";
cout << " No weight entry is positive.\n";
exit ( 1 );
}
//
// Assign each observation to the nearest cluster center.
//
for ( j = 0; j < point_num; j++ )
{
point_energy_min = r8_huge ( );
cluster[j] = -1;
for ( k = 0; k < cluster_num; k++ )
{
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
if ( point_energy < point_energy_min )
{
point_energy_min = point_energy;
cluster[j] = k;
}
}
}
//
// Determine the cluster populations and weights.
//
i4vec_zero ( cluster_num, cluster_population );
cluster_weight = r8vec_zero_new ( cluster_num );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
cluster_population[k] = cluster_population[k] + 1;
cluster_weight[k] = cluster_weight[k] + weight[j];
}
//
// Average the points in each cluster to get a new cluster center.
//
r8vec_zero ( dim_num * cluster_num, cluster_center );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num]
+ weight[j] * point[i+j*dim_num];
}
}
for ( k = 0; k < cluster_num; k++ )
{
if ( cluster_weight[k] != 0.0 )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+k*dim_num] = cluster_center[i+k*dim_num] /
cluster_weight[k];
}
}
}
//
// Carry out the iteration.
//
it_num = 0;
distsq = new double[cluster_num];
while ( it_num < it_max )
{
it_num = it_num + 1;
swap = 0;
for ( j = 0; j < point_num; j++ )
{
ci = cluster[j];
if ( cluster_population[ci] <= 1 )
{
continue;
}
for ( cj = 0; cj < cluster_num; cj++ )
{
if ( cj == ci )
{
distsq[cj] = 0.0;
for ( i = 0; i < dim_num; i++ )
{
distsq[cj] = distsq[cj]
+ pow ( point[i+j*dim_num] - cluster_center[i+cj*dim_num], 2 );
}
distsq[cj] = distsq[cj] * cluster_weight[cj]
/ ( cluster_weight[cj] - weight[j] );
}
else if ( cluster_population[cj] == 0 )
{
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+cj*dim_num] = point[i+j*dim_num];
}
distsq[cj] = 0.0;
}
else
{
distsq[cj] = 0.0;
for ( i = 0; i < dim_num; i++ )
{
distsq[cj] = distsq[cj]
+ pow ( point[i+j*dim_num] - cluster_center[i+cj*dim_num], 2 );
}
distsq[cj] = distsq[cj] * cluster_weight[cj]
/ ( cluster_weight[cj] + weight[j] );
}
}
//
// Find the index of the minimum value of DISTSQ.
//
k = r8vec_min_index ( cluster_num, distsq );
//
// If that is not the cluster to which point I now belongs, move it there.
//
if ( k == ci )
{
continue;
}
cj = k;
for ( i = 0; i < dim_num; i++ )
{
cluster_center[i+ci*dim_num] =
( cluster_weight[ci] * cluster_center[i+ci*dim_num]
- weight[j] * point[i+j*dim_num] )
/ ( cluster_weight[ci] - weight[j] );
cluster_center[i+cj*dim_num] =
( cluster_weight[cj] * cluster_center[i+cj*dim_num]
+ weight[j] * point[i+j*dim_num] )
/ ( cluster_weight[cj] + weight[j] );
}
cluster_population[ci] = cluster_population[ci] - 1;
cluster_population[cj] = cluster_population[cj] + 1;
cluster_weight[ci] = cluster_weight[ci] - weight[j];
cluster_weight[cj] = cluster_weight[cj] + weight[j];
cluster[j] = cj;
swap = swap + 1;
}
//
// Exit if no reassignments were made during this iteration.
//
if ( swap == 0 )
{
break;
}
}
//
// Compute the energy based on the final value of the cluster centers.
//
r8vec_zero ( cluster_num, cluster_energy );
for ( j = 0; j < point_num; j++ )
{
k = cluster[j];
point_energy = 0.0;
for ( i = 0; i < dim_num; i++ )
{
point_energy = point_energy +
pow ( point[i+j*dim_num] - cluster_center[i+k*dim_num], 2 );
}
cluster_energy[k] = cluster_energy[k] + weight[j] * point_energy;
}
delete [] cluster_weight;
delete [] distsq;
return;
}
//****************************************************************************80
int r4_nint ( float x )
//****************************************************************************80
//
// Purpose:
//
// R4_NINT returns the nearest integer to an R4.
//
// Example:
//
// X R4_NINT
//
// 1.3 1
// 1.4 1
// 1.5 1 or 2
// 1.6 2
// 0.0 0
// -0.7 -1
// -1.1 -1
// -1.6 -2
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 14 November 2006
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, float X, the value.
//
// Output, int R4_NINT, the nearest integer to X.
//
{
int value;
if ( x < 0.0 )
{
value = - ( int ) ( - x + 0.5 );
}
else
{
value = ( int ) ( x + 0.5 );
}
return value;
}
//****************************************************************************80
double r8_huge ( )
//****************************************************************************80
//
// Purpose:
//
// R8_HUGE returns a "huge" R8.
//
// Discussion:
//
// The value returned by this function is NOT required to be the
// maximum representable R8. This value varies from machine to machine,
// from compiler to compiler, and may cause problems when being printed.
// We simply want a "very large" but non-infinite number.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 06 October 2007
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Output, double R8_HUGE, a "huge" R8 value.
//
{
double value;
value = 1.0E+30;
return value;
}
//****************************************************************************80
double r8_max ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_MAX returns the maximum of two R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 August 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, the quantities to compare.
//
// Output, double R8_MAX, the maximum of X and Y.
//
{
double value;
if ( y < x )
{
value = x;
}
else
{
value = y;
}
return value;
}
//****************************************************************************80
double r8_min ( double x, double y )
//****************************************************************************80
//
// Purpose:
//
// R8_MIN returns the minimum of two R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 31 August 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, double X, Y, the quantities to compare.
//
// Output, double R8_MIN, the minimum of X and Y.
//
{
double value;
if ( y < x )
{
value = y;
}
else
{
value = x;
}
return value;
}
//****************************************************************************80
double r8_uniform_01 ( int *seed )
//****************************************************************************80
//
// Purpose:
//
// R8_UNIFORM_01 returns a unit pseudorandom R8.
//
// Discussion:
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// If the initial seed is 12345, then the first three computations are
//
// Input Output R8_UNIFORM_01
// SEED SEED
//
// 12345 207482415 0.096616
// 207482415 1790989824 0.833995
// 1790989824 2035175616 0.947702
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 11 August 2004
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input/output, int *SEED, the "seed" value. Normally, this
// value should not be 0. On output, SEED has been updated.
//
// Output, double R8_UNIFORM_01, a new pseudorandom variate,
// strictly between 0 and 1.
//
{
int i4_huge = 2147483647;
int k;
double r;
if ( *seed == 0 )
{
cerr << "\n";
cerr << "R8_UNIFORM_01 - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 )
{
*seed = *seed + i4_huge;
}
r = ( double ) ( *seed ) * 4.656612875E-10;
return r;
}
//****************************************************************************80
double *r8mat_data_read ( string input_filename, int m, int n )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_DATA_READ reads the data from an R8MAT file.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// The file is assumed to contain one record per line.
//
// Records beginning with '#' are comments, and are ignored.
// Blank lines are also ignored.
//
// Each line that is not ignored is assumed to contain exactly (or at least)
// M real numbers, representing the coordinates of a point.
//
// There are assumed to be exactly (or at least) N such records.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Input, int M, the number of spatial dimensions.
//
// Input, int N, the number of points. The program
// will stop reading data once N values have been read.
//
// Output, double R8MAT_DATA_READ[M*N], the data.
//
{
bool error;
ifstream input;
int i;
int j;
string line;
double *table;
double *x;
input.open ( input_filename.c_str ( ) );
if ( !input )
{
cerr << "\n";
cerr << "R8MAT_DATA_READ - Fatal error!\n";
cerr << " Could not open the input file: \"" << input_filename << "\"\n";
exit ( 1 );
}
table = new double[m*n];
x = new double[m];
j = 0;
while ( j < n )
{
getline ( input, line );
if ( input.eof ( ) )
{
break;
}
if ( line[0] == '#' || s_len_trim ( line ) == 0 )
{
continue;
}
error = s_to_r8vec ( line, m, x );
if ( error )
{
continue;
}
for ( i = 0; i < m; i++ )
{
table[i+j*m] = x[i];
}
j = j + 1;
}
input.close ( );
delete [] x;
return table;
}
//****************************************************************************80
void r8mat_header_read ( string input_filename, int *m, int *n )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_HEADER_READ reads the header from an R8MAT file.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 February 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string INPUT_FILENAME, the name of the input file.
//
// Output, int *M, the number of spatial dimensions.
//
// Output, int *N, the number of points.
//
{
*m = file_column_count ( input_filename );
if ( *m <= 0 )
{
cerr << "\n";
cerr << "R8MAT_HEADER_READ - Fatal error!\n";
cerr << " FILE_COLUMN_COUNT failed.\n";
exit ( 1 );
}
*n = file_row_count ( input_filename );
if ( *n <= 0 )
{
cerr << "\n";
cerr << "R8MAT_HEADER_READ - Fatal error!\n";
cerr << " FILE_ROW_COUNT failed.\n";
exit ( 1 );
}
return;
}
//****************************************************************************80
double *r8mat_mm_new ( int n1, int n2, int n3, double a[], double b[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_MM_NEW multiplies two matrices.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8 values, stored as a vector
// in column-major order.
//
// For this routine, the result is returned as the function value.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 18 October 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N1, N2, N3, the order of the matrices.
//
// Input, double A[N1*N2], double B[N2*N3], the matrices to multiply.
//
// Output, double R8MAT_MM[N1*N3], the product matrix C = A * B.
//
{
double *c;
int i;
int j;
int k;
c = new double[n1*n3];
for ( i = 0; i < n1; i++ )
{
for ( j = 0; j < n3; j++ )
{
c[i+j*n1] = 0.0;
for ( k = 0; k < n2; k++ )
{
c[i+j*n1] = c[i+j*n1] + a[i+k*n1] * b[k+j*n2];
}
}
}
return c;
}
//****************************************************************************80
void r8mat_uniform_01 ( int m, int n, int *seed, double r[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UNIFORM_01 returns a unit pseudorandom R8MAT.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 October 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input/output, int *SEED, the "seed" value. Normally, this
// value should not be 0. On output, SEED has
// been updated.
//
// Output, double R[M*N], a matrix of pseudorandom values.
//
{
int i;
int i4_huge = 2147483647;
int j;
int k;
if ( *seed == 0 )
{
cerr << "\n";
cerr << "R8MAT_UNIFORM_01 - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 )
{
*seed = *seed + i4_huge;
}
r[i+j*m] = ( double ) ( *seed ) * 4.656612875E-10;
}
}
return;
}
//****************************************************************************80
double *r8mat_uniform_01_new ( int m, int n, int *seed )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_UNIFORM_01_NEW returns a unit pseudorandom R8MAT.
//
// Discussion:
//
// An R8MAT is a doubly dimensioned array of R8's, stored as a vector
// in column-major order.
//
// This routine implements the recursion
//
// seed = 16807 * seed mod ( 2^31 - 1 )
// unif = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 October 2005
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Springer Verlag, pages 201-202, 1983.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, pages 362-376, 1986.
//
// Philip Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, pages 136-143, 1969.
//
// Parameters:
//
// Input, int M, N, the number of rows and columns.
//
// Input/output, int *SEED, the "seed" value. Normally, this
// value should not be 0, otherwise the output value of SEED
// will still be 0, and R8_UNIFORM will be 0. On output, SEED has
// been updated.
//
// Output, double R8MAT_UNIFORM_01_NEW[M*N], a matrix of pseudorandom values.
//
{
int i;
int j;
int k;
double *r;
r = new double[m*n];
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 )
{
*seed = *seed + 2147483647;
}
r[i+j*m] = ( double ) ( *seed ) * 4.656612875E-10;
}
}
return r;
}
//****************************************************************************80
void r8mat_write ( string output_filename, int m, int n, double table[] )
//****************************************************************************80
//
// Purpose:
//
// R8MAT_WRITE writes an R8MAT file.
//
// Discussion:
//
// An R8MAT is an array of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 29 June 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string OUTPUT_FILENAME, the output filename.
//
// Input, int M, the spatial dimension.
//
// Input, int N, the number of points.
//
// Input, double TABLE[M*N], the data.
//
{
int i;
int j;
ofstream output;
//
// Open the file.
//
output.open ( output_filename.c_str ( ) );
if ( !output )
{
cerr << "\n";
cerr << "R8MAT_WRITE - Fatal error!\n";
cerr << " Could not open the output file.\n";
exit ( 1 );
}
//
// Write the data.
//
for ( j = 0; j < n; j++ )
{
for ( i = 0; i < m; i++ )
{
output << " " << setw(24) << setprecision(16) << table[i+j*m];
}
output << "\n";
}
//
// Close the file.
//
output.close ( );
return;
}
//****************************************************************************80
bool r8vec_all_nonpositive ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ALL_NONPOSITIVE: ( all ( A <= 0 ) ) for R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, double A[N], the vector to check.
//
// Output, bool R8VEC_ALL_NONPOSITIVE is TRUE if all entries
// of A are less than or equal to zero.
//
{
int i;
bool value;
for ( i = 0; i < n; i++ )
{
if ( 0.0 < a[i] )
{
value = false;
return value;
}
}
value = true;
return value;
}
//****************************************************************************80
bool r8vec_any_negative ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ANY_NEGATIVE: ( any ( A < 0 ) ) for R8VEC's.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 09 October 2011
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries.
//
// Input, double A[N], the vector to check.
//
// Output, bool R8VEC_ANY_NEGATIVE is TRUE if any entry
// of A is less than zero.
//
{
int i;
bool value;
for ( i = 0; i < n; i++ )
{
if ( a[i] < 0.0 )
{
value = true;
return value;
}
}
value = false;
return value;
}
//****************************************************************************80
double r8vec_i4vec_dot_product ( int n, double r8vec[], int i4vec[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_I4VEC_DOT_PRODUCT computes the dot product of an R8VEC and an I4VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// An I4VEC is a vector of I4's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vectors.
//
// Input, double R8VEC[N], the first vector.
//
// Input, int I4VEC[N], the second vector.
//
// Output, double R8VEC_I4VEC_DOT_PRODUCT, the dot product of the vectors.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + r8vec[i] * ( double ) ( i4vec[i] );
}
return value;
}
//****************************************************************************80
int r8vec_min_index ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_MIN_INDEX returns the index of the minimum value in an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 August 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the array.
//
// Input, double A[N], the array.
//
// Output, int R8VEC_MIN_INDEX, the index of the smallest entry.
//
{
int i;
int min_index;
if ( n <= 0 )
{
min_index = -1;
}
else
{
min_index = 0;
for ( i = 1; i < n; i++ )
{
if ( a[i] < a[min_index] )
{
min_index = i;
}
}
}
return min_index;
}
//****************************************************************************80
double r8vec_sum ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_SUM returns the sum of an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 15 October 2004
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input, double A[N], the vector.
//
// Output, double R8VEC_SUM, the sum of the vector.
//
{
int i;
double value;
value = 0.0;
for ( i = 0; i < n; i++ )
{
value = value + a[i];
}
return value;
}
//****************************************************************************80
void r8vec_uniform_01 ( int n, int *seed, double r[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_UNIFORM_01 returns a unit pseudorandom R8VEC.
//
// Discussion:
//
// This routine implements the recursion
//
// seed = ( 16807 * seed ) mod ( 2^31 - 1 )
// u = seed / ( 2^31 - 1 )
//
// The integer arithmetic never requires more than 32 bits,
// including a sign bit.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 19 August 2004
//
// Author:
//
// John Burkardt
//
// Reference:
//
// Paul Bratley, Bennett Fox, Linus Schrage,
// A Guide to Simulation,
// Second Edition,
// Springer, 1987,
// ISBN: 0387964673,
// LC: QA76.9.C65.B73.
//
// Bennett Fox,
// Algorithm 647:
// Implementation and Relative Efficiency of Quasirandom
// Sequence Generators,
// ACM Transactions on Mathematical Software,
// Volume 12, Number 4, December 1986, pages 362-376.
//
// Pierre L'Ecuyer,
// Random Number Generation,
// in Handbook of Simulation,
// edited by Jerry Banks,
// Wiley, 1998,
// ISBN: 0471134031,
// LC: T57.62.H37.
//
// Peter Lewis, Allen Goodman, James Miller,
// A Pseudo-Random Number Generator for the System/360,
// IBM Systems Journal,
// Volume 8, Number 2, 1969, pages 136-143.
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Input/output, int *SEED, a seed for the random number generator.
//
// Output, double R[N], the vector of pseudorandom values.
//
{
int i;
int i4_huge = 2147483647;
int k;
if ( *seed == 0 )
{
cerr << "\n";
cerr << "R8VEC_UNIFORM_01 - Fatal error!\n";
cerr << " Input value of SEED = 0.\n";
exit ( 1 );
}
for ( i = 0; i < n; i++ )
{
k = *seed / 127773;
*seed = 16807 * ( *seed - k * 127773 ) - k * 2836;
if ( *seed < 0 )
{
*seed = *seed + i4_huge;
}
r[i] = ( double ) ( *seed ) * 4.656612875E-10;
}
return;
}
//****************************************************************************80
void r8vec_zero ( int n, double a[] )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ZERO zeroes an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 July 2005
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, double A[N], a vector of zeroes.
//
{
int i;
for ( i = 0; i < n; i++ )
{
a[i] = 0.0;
}
return;
}
//****************************************************************************80
double *r8vec_zero_new ( int n )
//****************************************************************************80
//
// Purpose:
//
// R8VEC_ZERO_NEW creates and zeroes an R8VEC.
//
// Discussion:
//
// An R8VEC is a vector of R8's.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 10 July 2008
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int N, the number of entries in the vector.
//
// Output, double R8VEC_ZERO_NEW[N], a vector of zeroes.
//
{
double *a;
int i;
a = new double[n];
for ( i = 0; i < n; i++ )
{
a[i] = 0.0;
}
return a;
}
//****************************************************************************80
int s_len_trim ( string s )
//****************************************************************************80
//
// Purpose:
//
// S_LEN_TRIM returns the length of a string to the last nonblank.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, a string.
//
// Output, int S_LEN_TRIM, the length of the string to the last nonblank.
// If S_LEN_TRIM is 0, then the string is entirely blank.
//
{
int n;
n = s.length ( );
while ( 0 < n )
{
if ( s[n-1] != ' ' )
{
return n;
}
n = n - 1;
}
return n;
}
//****************************************************************************80
double s_to_r8 ( string s, int *lchar, bool *error )
//****************************************************************************80
//
// Purpose:
//
// S_TO_R8 reads an R8 from a string.
//
// Discussion:
//
// This routine will read as many characters as possible until it reaches
// the end of the string, or encounters a character which cannot be
// part of the real number.
//
// Legal input is:
//
// 1 blanks,
// 2 '+' or '-' sign,
// 2.5 spaces
// 3 integer part,
// 4 decimal point,
// 5 fraction part,
// 6 'E' or 'e' or 'D' or 'd', exponent marker,
// 7 exponent sign,
// 8 exponent integer part,
// 9 exponent decimal point,
// 10 exponent fraction part,
// 11 blanks,
// 12 final comma or semicolon.
//
// with most quantities optional.
//
// Example:
//
// S R
//
// '1' 1.0
// ' 1 ' 1.0
// '1A' 1.0
// '12,34,56' 12.0
// ' 34 7' 34.0
// '-1E2ABCD' -100.0
// '-1X2ABCD' -1.0
// ' 2E-1' 0.2
// '23.45' 23.45
// '-4.2E+2' -420.0
// '17d2' 1700.0
// '-14e-2' -0.14
// 'e2' 100.0
// '-12.73e-9.23' -12.73 * 10.0**(-9.23)
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, the string containing the
// data to be read. Reading will begin at position 1 and
// terminate at the end of the string, or when no more
// characters can be read to form a legal real. Blanks,
// commas, or other nonnumeric data will, in particular,
// cause the conversion to halt.
//
// Output, int *LCHAR, the number of characters read from
// the string to form the number, including any terminating
// characters such as a trailing comma or blanks.
//
// Output, bool *ERROR, is true if an error occurred.
//
// Output, double S_TO_R8, the real value that was read from the string.
//
{
char c;
int ihave;
int isgn;
int iterm;
int jbot;
int jsgn;
int jtop;
int nchar;
int ndig;
double r;
double rbot;
double rexp;
double rtop;
char TAB = 9;
nchar = s_len_trim ( s );
*error = false;
r = 0.0;
*lchar = -1;
isgn = 1;
rtop = 0.0;
rbot = 1.0;
jsgn = 1;
jtop = 0;
jbot = 1;
ihave = 1;
iterm = 0;
for ( ; ; )
{
c = s[*lchar+1];
*lchar = *lchar + 1;
//
// Blank or TAB character.
//
if ( c == ' ' || c == TAB )
{
if ( ihave == 2 )
{
}
else if ( ihave == 6 || ihave == 7 )
{
iterm = 1;
}
else if ( 1 < ihave )
{
ihave = 11;
}
}
//
// Comma.
//
else if ( c == ',' || c == ';' )
{
if ( ihave != 1 )
{
iterm = 1;
ihave = 12;
*lchar = *lchar + 1;
}
}
//
// Minus sign.
//
else if ( c == '-' )
{
if ( ihave == 1 )
{
ihave = 2;
isgn = -1;
}
else if ( ihave == 6 )
{
ihave = 7;
jsgn = -1;
}
else
{
iterm = 1;
}
}
//
// Plus sign.
//
else if ( c == '+' )
{
if ( ihave == 1 )
{
ihave = 2;
}
else if ( ihave == 6 )
{
ihave = 7;
}
else
{
iterm = 1;
}
}
//
// Decimal point.
//
else if ( c == '.' )
{
if ( ihave < 4 )
{
ihave = 4;
}
else if ( 6 <= ihave && ihave <= 8 )
{
ihave = 9;
}
else
{
iterm = 1;
}
}
//
// Exponent marker.
//
else if ( ch_eqi ( c, 'E' ) || ch_eqi ( c, 'D' ) )
{
if ( ihave < 6 )
{
ihave = 6;
}
else
{
iterm = 1;
}
}
//
// Digit.
//
else if ( ihave < 11 && '0' <= c && c <= '9' )
{
if ( ihave <= 2 )
{
ihave = 3;
}
else if ( ihave == 4 )
{
ihave = 5;
}
else if ( ihave == 6 || ihave == 7 )
{
ihave = 8;
}
else if ( ihave == 9 )
{
ihave = 10;
}
ndig = ch_to_digit ( c );
if ( ihave == 3 )
{
rtop = 10.0 * rtop + ( double ) ndig;
}
else if ( ihave == 5 )
{
rtop = 10.0 * rtop + ( double ) ndig;
rbot = 10.0 * rbot;
}
else if ( ihave == 8 )
{
jtop = 10 * jtop + ndig;
}
else if ( ihave == 10 )
{
jtop = 10 * jtop + ndig;
jbot = 10 * jbot;
}
}
//
// Anything else is regarded as a terminator.
//
else
{
iterm = 1;
}
//
// If we haven't seen a terminator, and we haven't examined the
// entire string, go get the next character.
//
if ( iterm == 1 || nchar <= *lchar + 1 )
{
break;
}
}
//
// If we haven't seen a terminator, and we have examined the
// entire string, then we're done, and LCHAR is equal to NCHAR.
//
if ( iterm != 1 && (*lchar) + 1 == nchar )
{
*lchar = nchar;
}
//
// Number seems to have terminated. Have we got a legal number?
// Not if we terminated in states 1, 2, 6 or 7!
//
if ( ihave == 1 || ihave == 2 || ihave == 6 || ihave == 7 )
{
*error = true;
return r;
}
//
// Number seems OK. Form it.
//
if ( jtop == 0 )
{
rexp = 1.0;
}
else
{
if ( jbot == 1 )
{
rexp = pow ( 10.0, jsgn * jtop );
}
else
{
rexp = jsgn * jtop;
rexp = rexp / jbot;
rexp = pow ( 10.0, rexp );
}
}
r = isgn * rexp * rtop / rbot;
return r;
}
//****************************************************************************80
bool s_to_r8vec ( string s, int n, double rvec[] )
//****************************************************************************80
//
// Purpose:
//
// S_TO_R8VEC reads an R8VEC from a string.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, the string to be read.
//
// Input, int N, the number of values expected.
//
// Output, double RVEC[N], the values read from the string.
//
// Output, bool S_TO_R8VEC, is true if an error occurred.
//
{
int begin;
bool error;
int i;
int lchar;
int length;
begin = 0;
length = s.length ( );
error = 0;
for ( i = 0; i < n; i++ )
{
rvec[i] = s_to_r8 ( s.substr(begin,length), &lchar, &error );
if ( error )
{
return error;
}
begin = begin + lchar;
length = length - lchar;
}
return error;
}
//****************************************************************************80
int s_word_count ( string s )
//****************************************************************************80
//
// Purpose:
//
// S_WORD_COUNT counts the number of "words" in a string.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 05 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, string S, the string to be examined.
//
// Output, int S_WORD_COUNT, the number of "words" in the string.
// Words are presumed to be separated by one or more blanks.
//
{
bool blank;
int char_count;
int i;
int word_count;
word_count = 0;
blank = true;
char_count = s.length ( );
for ( i = 0; i < char_count; i++ )
{
if ( isspace ( s[i] ) )
{
blank = true;
}
else if ( blank )
{
word_count = word_count + 1;
blank = false;
}
}
return word_count;
}
//****************************************************************************80
void timestamp ( )
//****************************************************************************80
//
// Purpose:
//
// TIMESTAMP prints the current YMDHMS date as a time stamp.
//
// Example:
//
// 31 May 2001 09:45:54 AM
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 08 July 2009
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// None
//
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct std::tm *tm_ptr;
size_t len;
std::time_t now;
now = std::time ( NULL );
tm_ptr = std::localtime ( &now );
len = std::strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm_ptr );
std::cout << time_buffer << "\n";
return;
# undef TIME_SIZE
}
| [
"[email protected]"
] | |
ea5126d9a611cd41768dcf8f93ee563c1751f70a | 3e194ed62e1c2889200956f4869f4302fd8ec1e2 | /CodeChef/Apr2010Contest/addingFractions.cpp | 95e6b7f757649527066410d12f69472c1c84a88e | [] | no_license | Mythili007/CodePractice | 12200c4f0159a13768102162b81e7ad20664f7c3 | 8de758858887d71d23e2316a6396ec05398db197 | refs/heads/master | 2021-06-05T19:15:45.589220 | 2021-05-07T19:28:12 | 2021-05-07T19:28:12 | 135,747,445 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t-- > 0)
{
int n;
cin >> n;
int *num = new int[n];
int *denom = new int[n];
string *st = new string[n];
float num, denom;
for (int i = 0; i < n; i++)
{
cin>>num;
// int a = int(ceil(num));
cout<<"num: "<<num<<endl;
}
}
return 0;
} | [
"[email protected]"
] | |
8305eae626301940e9126f722a9079f4bafdbe10 | ce1f0eef1ddd30a608c4957c843c716365a3eeb4 | /Codechef Practice/Beginner/Chefandstrings.cpp | 7909ca31718cabe9cbd16b8fb080db1159b673eb | [] | no_license | TanishqChamoli/Codechef | 11d09ebc9867de4b57ce8e3503f285626c5093cf | c1d58382c0cddb5d1b7c0b1289038d74f8296544 | refs/heads/master | 2022-12-24T06:20:43.417074 | 2020-10-05T18:07:44 | 2020-10-05T18:07:44 | 290,392,480 | 0 | 1 | null | 2020-10-05T18:07:45 | 2020-08-26T04:13:05 | C++ | UTF-8 | C++ | false | false | 365 | cpp | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
long long int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int ans = n;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
}
}
}
return 0;
} | [
"[email protected]"
] | |
6a66b1d5433632fe56915bc351066507bb2d5d61 | 4741ab90c72013c22a83d78f51a66f4dd312e4a5 | /launcher.cpp | 7787c0e42a5f41a4661cfc1cfc0f78d3731b5c85 | [] | no_license | Sh1ft0x0EF/Metahook-Plus-0.4 | 16d550f739257d30d360e0b4a812a3ffc4e2fd4e | cab94403c576f68087d6932339b4e76c54ec6c6e | refs/heads/master | 2016-09-09T20:20:59.974688 | 2015-08-05T15:47:05 | 2015-08-05T15:47:05 | 40,254,118 | 10 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 6,564 | cpp | #include <windows.h>
#include "metahook.h"
#include <IEngine.h>
#include "LoadBlob.h"
#include "ExceptHandle.h"
#include "sys.h"
#pragma warning(disable : 4733)
#pragma comment(lib, "ws2_32.lib")
IFileSystem *g_pFileSystem;
HINTERFACEMODULE LoadFilesystemModule(void)
{
HINTERFACEMODULE hModule = Sys_LoadModule("filesystem_stdio.dll");
if (!hModule)
{
MessageBox(NULL, "Could not load filesystem dll.\nFileSystem crashed during construction.", "Fatal Error", MB_ICONERROR);
return NULL;
}
return hModule;
}
void SetEngineDLL(const char *&pszEngineDLL)
{
pszEngineDLL = "hw.dll";
registry->WriteString("EngineDLL", pszEngineDLL);
}
BOOL OnVideoModeFailed(void)
{
registry->WriteInt("ScreenWidth", 640);
registry->WriteInt("ScreenHeight", 480);
registry->WriteInt("ScreenBPP", 16);
registry->WriteString("EngineDLL", "sw.dll");
return (MessageBox(NULL, "The specified video mode is not supported.\nThe game will now run in software mode.", "Video mode change failure", MB_OKCANCEL | MB_ICONWARNING) == IDOK);
}
BlobFootprint_t g_blobfootprintClient;
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
HANDLE hObject = NULL;
BOOL (*IsDebuggerPresent)(void) = (BOOL (*)(void))GetProcAddress(GetModuleHandle("kernel32.dll"), "IsDebuggerPresent");
if (!IsDebuggerPresent())
{
hObject = CreateMutex(NULL, FALSE, "ValveHalfLifeLauncherMutex");
DWORD dwStatus = WaitForSingleObject(hObject, 0);
if (dwStatus && dwStatus != WAIT_ABANDONED)
{
MessageBox(NULL, "Could not launch game.\nOnly one instance of this game can be run at a time.", "Error", MB_ICONERROR);
return 0;
}
}
WSAData WSAData;
WSAStartup(2, &WSAData);
registry->Init();
CommandLine()->CreateCmdLine(GetCommandLine());
CommandLine()->AppendParm("-nomaster", NULL);
char szFileName[256];
Sys_GetExecutableName(szFileName, sizeof(szFileName));
char *szExeName = strrchr(szFileName, '\\') + 1;
if (stricmp(szExeName, "hl.exe") && CommandLine()->CheckParm("-game") == NULL)
{
szExeName[strlen(szExeName) - 4] = '\0';
CommandLine()->AppendParm("-game", szExeName);
}
const char *_szGameName;
static char szGameName[32];
const char *szGameStr = CommandLine()->CheckParm("-game", &_szGameName);
strcpy(szGameName, _szGameName);
if (szGameStr && !strnicmp(&szGameStr[6], "czero", 5))
CommandLine()->AppendParm("-forcevalve", NULL);
if (registry->ReadInt("CrashInitializingVideoMode", FALSE))
{
registry->WriteInt("CrashInitializingVideoMode", FALSE);
if (strcmp(registry->ReadString("EngineDLL", "hw.dll"), "hw.dll"))
{
if (registry->ReadInt("EngineD3D", FALSE))
{
registry->WriteInt("EngineD3D", FALSE);
if (MessageBox(NULL, "The game has detected that the previous attempt to start in D3D video mode failed.\nThe game will now run attempt to run in openGL mode.", "Video mode change failure", MB_OKCANCEL | MB_ICONWARNING) != IDOK)
return 0;
}
else
{
registry->WriteString("EngineDLL", "sw.dll");
if (MessageBox(NULL, "The game has detected that the previous attempt to start in openGL video mode failed.\nThe game will now run in software mode.", "Video mode change failure", MB_OKCANCEL | MB_ICONWARNING) != IDOK)
return 0;
}
registry->WriteInt("ScreenWidth", 640);
registry->WriteInt("ScreenHeight", 480);
registry->WriteInt("ScreenBPP", 16);
}
}
while (1)
{
HINTERFACEMODULE hFileSystem = LoadFilesystemModule();
if (!hFileSystem)
break;
MH_Init(szGameName);
CreateInterfaceFn fsCreateInterface = (CreateInterfaceFn)Sys_GetFactory(hFileSystem);
g_pFileSystem = (IFileSystem *)fsCreateInterface(FILESYSTEM_INTERFACE_VERSION, NULL);
g_pFileSystem->Mount();
g_pFileSystem->AddSearchPath(Sys_GetLongPathName(), "ROOT");
static char szNewCommandParams[2048];
const char *pszEngineDLL;
int iResult = ENGINE_RESULT_NONE;
szNewCommandParams[0] = 0;
SetEngineDLL(pszEngineDLL);
g_blobfootprintClient.m_hDll = NULL;
IEngine *engineAPI = NULL;
HINTERFACEMODULE hEngine;
bool bUseBlobDLL = false;
if (FIsBlob(pszEngineDLL))
{
Sys_CloseDEP();
SetupExceptHandler3();
NLoadBlobFile(pszEngineDLL, &g_blobfootprintClient, (void **)&engineAPI);
bUseBlobDLL = true;
}
else
{
hEngine = Sys_LoadModule(pszEngineDLL);
if (!hEngine)
{
static char msg[512];
wsprintf(msg, "Could not load %s.\nPlease try again at a later time.", pszEngineDLL);
MessageBox(NULL, msg, "Fatal Error", MB_ICONERROR);
break;
}
CreateInterfaceFn engineCreateInterface = (CreateInterfaceFn)Sys_GetFactory(hEngine);
engineAPI = (IEngine *)engineCreateInterface(VENGINE_LAUNCHER_API_VERSION, NULL);
if (!engineCreateInterface || !engineAPI)
Sys_FreeModule(hEngine);
}
if (engineAPI)
{
MH_LoadEngine(bUseBlobDLL ? NULL : (HMODULE)hEngine);
iResult = engineAPI->Run(hInstance, Sys_GetLongPathName(), CommandLine()->GetCmdLine(), szNewCommandParams, Sys_GetFactoryThis(), Sys_GetFactory(hFileSystem));
MH_ExitGame(iResult);
if (bUseBlobDLL)
FreeBlob(&g_blobfootprintClient);
else
Sys_FreeModule(hEngine);
}
if (iResult == ENGINE_RESULT_NONE || iResult > ENGINE_RESULT_UNSUPPORTEDVIDEO)
break;
bool bContinue;
switch (iResult)
{
case ENGINE_RESULT_RESTART:
{
bContinue = true;
break;
}
case ENGINE_RESULT_UNSUPPORTEDVIDEO:
{
bContinue = OnVideoModeFailed();
break;
}
}
CommandLine()->RemoveParm("-sw");
CommandLine()->RemoveParm("-startwindowed");
CommandLine()->RemoveParm("-windowed");
CommandLine()->RemoveParm("-window");
CommandLine()->RemoveParm("-full");
CommandLine()->RemoveParm("-fullscreen");
CommandLine()->RemoveParm("-soft");
CommandLine()->RemoveParm("-software");
CommandLine()->RemoveParm("-gl");
CommandLine()->RemoveParm("-d3d");
CommandLine()->RemoveParm("-w");
CommandLine()->RemoveParm("-width");
CommandLine()->RemoveParm("-h");
CommandLine()->RemoveParm("-height");
CommandLine()->RemoveParm("-novid");
if (strstr(szNewCommandParams, "-game"))
CommandLine()->RemoveParm("-game");
if (strstr(szNewCommandParams, "+load"))
CommandLine()->RemoveParm("+load");
CommandLine()->AppendParm(szNewCommandParams, NULL);
g_pFileSystem->Unmount();
Sys_FreeModule(hFileSystem);
MH_Shutdown();
if (!bContinue)
break;
}
registry->Shutdown();
if (hObject)
{
ReleaseMutex(hObject);
CloseHandle(hObject);
}
WSACleanup();
MH_Shutdown();
TerminateProcess(GetCurrentProcess(), 1);
return 1;
} | [
"[email protected]"
] | |
5184e19dd0e6c740edf5ae24752b92274dddad23 | 949714310a640856b524724fbda04493636de60e | /M11_classes_inheritance/M2_multiple_inheritance/example_1/main.cpp | 034a7c38c85d111f470d4a1272f7bacf2ffa5ccc | [] | no_license | jcwalmsley/CourseNotes_Cpp | 0fc5fbf5a7f66a681952d88537009e4c3b992c8b | f7c15f065a01f14c0bc58c8ba1135ba70f157c36 | refs/heads/master | 2022-03-27T08:36:20.601483 | 2019-12-28T13:56:50 | 2019-12-28T13:56:50 | 178,411,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | cpp | /*
C++ classes can inherit from more than one class. This is known as "Multiple Inheritance".
The form for declaring multiple inheritance is:
class DerivedClass : access BaseClass1, ... ,access BaseClassN
For example, in the statement shown below, the derived class is TeachingAssociate. It inherits attributes from Staff and from GradStudent.
class TeachingAssociate: public Staff, public GradStudent
Let's look at an example of multiple inheritance.
*/
/*Goal: understand multiple inheritance*/
#include "main.hpp"
int main()
{
TA t1;
t1.setSupervisor("Dr. Caohuu");
t1.setId(55555);
t1.setTitle("Adjunct Prof.");
cout<<t1.getSupervisor()<<" "<<t1.getId()<<" "<<t1.getTitle();
return 0;
}
| [
"[email protected]"
] | |
2fca11bca5bba58c3484ce537a87421e22100938 | b15e43669d18603ee2221fa9e4bf782dee361f73 | /src/glutils.hpp | 77b29c7c5491852d87a2d3eb778304732daedd89 | [] | no_license | shogerr/cards | ae212d7b459729d0d59a67333d5829b4bfff9dc0 | 407292e6d5250f4ac226d3f1e2fea79fd7827452 | refs/heads/master | 2020-03-30T00:10:33.920760 | 2018-09-27T01:04:33 | 2018-09-27T01:04:33 | 150,508,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 320 | hpp | #ifndef __GLUTILS_HPP_
#define __GLUTILS_HPP_
#include <GL/glew.h>
#include <vector>
#include <iostream>
#define LOGE(...) (std::cout << __VA_ARGS__);
GLuint createProgram(std::vector<std::pair<GLenum, std::string>>* shaderSource);
GLuint createShader(GLenum shaderType, const char* src);
#endif // __GLUTILS_HPP_
| [
"ekem@zinc"
] | ekem@zinc |
133cfff4e4e550de1f59674e9895342ddeb81f5e | d293694daaea6dd869698e8432ef144eb339fd60 | /opencensus/stats/recording.h | 880ae46cba1c2e00cfaef6a4057782ff0dba64de | [
"Apache-2.0"
] | permissive | census-instrumentation/opencensus-cpp | b76c979e54cf2e9c53fdeba4a33aaf12d75776ff | 50eb5de762e5f87e206c011a4f930adb1a1775b1 | refs/heads/master | 2023-09-04T23:07:47.635622 | 2023-05-02T19:13:52 | 2023-05-02T19:13:52 | 91,836,765 | 148 | 80 | Apache-2.0 | 2023-05-02T19:13:53 | 2017-05-19T18:59:46 | C++ | UTF-8 | C++ | false | false | 1,848 | h | // Copyright 2017, OpenCensus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// IWYU pragma: private, include "opencensus/stats/stats.h"
// IWYU pragma: friend opencensus/stats/.*
#ifndef OPENCENSUS_STATS_RECORDING_H_
#define OPENCENSUS_STATS_RECORDING_H_
#include <initializer_list>
#include "opencensus/stats/measure.h"
#include "opencensus/tags/tag_map.h"
namespace opencensus {
namespace stats {
// Records a list of Measurements under the current Context's tags. The
// recommended style is to create Measurements as an initializer list, e.g.:
//
// Record({{measure_double, 2.5}, {measure_int, 1ll}});
//
// Only floating point values may be recorded against MeasureDoubles and only
// integral values against MeasureInt64s, to prevent silent loss of precision.
// If a record call fails to compile, ensure that all types match (using
// static_cast to double or int64_t if necessary).
void Record(std::initializer_list<Measurement> measurements);
// Records a list of Measurements under the specified 'tags'. The current
// Context's tags are ignored. e.g:
//
// Record({{measure_double, 2.5}}, {{key, "value"}});
void Record(std::initializer_list<Measurement> measurements,
opencensus::tags::TagMap tags);
} // namespace stats
} // namespace opencensus
#endif // OPENCENSUS_STATS_RECORDING_H_
| [
"[email protected]"
] | |
e2c2f9767583079238fee405f781347328ec8d82 | 08120290e74cea3cfcd7f22c3a45cf4e6c9a3b98 | /myvector/dw/dw.cpp | a8a37079879f89214cdf28c9960d92b11077113a | [] | no_license | ttky123/Algo_Study | bfe322816420d3a8aa1534d413cb25df96c2369d | 4195640b02e3a44340b9d90711ead66f800144c9 | refs/heads/master | 2022-12-11T13:54:22.213601 | 2020-09-16T06:40:55 | 2020-09-16T06:40:55 | 295,961,990 | 0 | 0 | null | null | null | null | WINDOWS-1258 | C++ | false | false | 3,368 | cpp | #include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
class MyIntVector {
public:
MyIntVector()
: data{ NULL }, sz{ NULL }, space{ NULL } {}
MyIntVector(size_t init_sz) // constructor.
: data{ new int[init_sz] }, sz{ init_sz }, space{ init_sz } {}
MyIntVector(const MyIntVector& source) // copy constructor
: data{ new int[source.sz] }, sz{ source.sz }, space{ source.space } {
copy(source.data, source.data + space, data);
}
~MyIntVector() { delete[] data; } // destructor
MyIntVector& operator = (const MyIntVector& source) { // = overloading
int *new_data;
if (this == &source)
return *this;
if (sz != source.sz)
{
new_data = new int[source.sz];
delete[] data;
data = new_data;
sz = source.sz;
}
space = source.space;
copy(source.data, source.data + space, data);
}
void operator += (const MyIntVector& source) {
if (sz + source.sz > space)
reserve(sz + source.sz);
copy(source.data, source.data + source.sz, data + sz);
sz += source.sz;
}
int& operator[] (int num) {
//error»ư¼º
if (sz <= num) {
cout << "Error : Out Of Range." << endl;
exit(-1);
}
return data[num];
}
MyIntVector operator + (const MyIntVector& source) {
if (sz != source.sz) {
cout << "Error : size is not equal.";
exit(-2);
}
MyIntVector temp(sz);
for (int i = 0; i < sz; i++)
temp[i] = data[i] + source.data[i];
return temp;
}
MyIntVector operator - (const MyIntVector& source) {
if (sz != source.sz) {
cout << "Error : size is not equal.";
exit(-2);
}
MyIntVector temp(sz);
for (int i = 0; i < sz; i++)
temp[i] = data[i] - source.data[i];
return temp;
}
int operator * (const MyIntVector& source) {
if (sz != source.sz) {
cout << "Error : size is not equal.";
exit(-2);
}
int sum = 0;
for (int i = 0; i < sz; i++)
sum += (data[i] * source.data[i]);
return sum;
}
MyIntVector& operator -() {
for (int i = 0; i < sz; i++)
data[i] = -data[i];
return *this;
}
bool operator == (const MyIntVector source) {
if (sz != source.sz) {
cout << "Error : size is not equal.";
exit(-2);
}
for (int i = 0; i < sz; i++) {
if (data[i] != source.data[i])
return false;
}
return true;
}
MyIntVector& operator ()(int num) {
for (int i = 0; i < sz; i++)
data[i] = num;
return *this;
}
void reserve(size_t new_space) {
if (new_space <= space) return;
int* larger_arr = new int[new_space];
copy(data, data + space, larger_arr);
delete[] data;
data = larger_arr;
space = new_space;
}
void push_back(int x) {
if (sz == 0) reserve(1);
else if (sz == space)
reserve(space + 1);
data[sz] = x;
++sz;
}
size_t capacity() const {
return space;
}
size_t size() const {
return sz;
}
bool isEmpty() const {
if (sz == 0)
return true;
else
return false;
}
void clear() {
if (sz == 0)
return;
int * new_arr = new int[space];
delete[] data;
data = new_arr;
sz = 0;
}
private:
int *data;
size_t sz;
size_t space;
};
int main()
{
MyIntVector a, b, c;
a.push_back(1);
a.push_back(2);
a.push_back(3);
b.push_back(1);
b.push_back(2);
b.push_back(0);
a += b;
for (int i = 0; i < 6; i++) cout << a[i] << endl;
cout << a.size() << b.size() << c.size() << endl;
cout << a.capacity() << b.capacity() << c.capacity() << endl;
return 0;
} | [
"[email protected]"
] | |
d02019b98aecabd5def9f1d14d145806653cce55 | f95975d9454984803586de7f0600f3ecf9918f60 | /lang_service/java/com/intel/daal/algorithms/multinomial_naive_bayes/partial_model.cpp | cbb22860fab9e28806cf60ffd9282095633b6398 | [
"Intel",
"Apache-2.0"
] | permissive | jjuribe/daal | f4e05656ca5f01e56debdbd2de51eeb2f506ca3d | 242d358db584dd4c9c65826b345fe63313ff8f2a | refs/heads/master | 2020-09-15T01:33:34.752543 | 2019-11-21T08:27:26 | 2019-11-21T08:27:26 | 223,316,648 | 0 | 0 | Apache-2.0 | 2019-11-22T03:33:41 | 2019-11-22T03:33:39 | null | UTF-8 | C++ | false | false | 2,367 | cpp | /* file: partial_model.cpp */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <jni.h>
#include "daal.h"
#include "com_intel_daal_algorithms_multinomial_naive_bayes_PartialModel.h"
using namespace daal;
using namespace daal::algorithms;
using namespace daal::data_management;
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_multinomial_1naive_1bayes_PartialModel_cGetClassGroupSum
(JNIEnv *env, jobject thisObj, jlong modelAddr)
{
NumericTablePtr *nt = new NumericTablePtr();
multinomial_naive_bayes::PartialModelPtr res = *(multinomial_naive_bayes::PartialModelPtr *)modelAddr;
*nt = res->getClassGroupSum();
return (jlong)nt;
}
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_multinomial_1naive_1bayes_PartialModel_cGetClassSize
(JNIEnv *env, jobject thisObj, jlong modelAddr)
{
NumericTablePtr *nt = new NumericTablePtr();
multinomial_naive_bayes::PartialModelPtr res = *(multinomial_naive_bayes::PartialModelPtr *)modelAddr;
*nt = res->getClassSize();
return (jlong)nt;
}
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_multinomial_1naive_1bayes_PartialModel_cGetNFeatures
(JNIEnv *env, jobject thisObj, jlong modelAddr)
{
multinomial_naive_bayes::PartialModelPtr res = *(multinomial_naive_bayes::PartialModelPtr *)modelAddr;
return (jlong)(res->getNFeatures());
}
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_multinomial_1naive_1bayes_PartialModel_cGetNObservations
(JNIEnv *env, jobject thisObj, jlong modelAddr)
{
multinomial_naive_bayes::PartialModelPtr res = *(multinomial_naive_bayes::PartialModelPtr *)modelAddr;
return (jlong)(res->getNObservations());
}
| [
"[email protected]"
] | |
a6f487abc7fb5fec244b2d7b68fabecb38deaf09 | 4ca2b09fb25a1e30ed02f7f471e675e9621c6b5e | /Navigation/AS5045B/Bit_banging/Bit_banging.ino | 4ea074aa341ff31c7bc8fc2415754e3dd1d05814 | [] | no_license | MRSD2018/minebot | c37ca9631d626e746500f04695710c556282c7f6 | 10b36904d292a9f067edaf7cd4cc2aa5d0c9f43f | refs/heads/master | 2021-01-23T17:09:25.776356 | 2018-04-02T16:08:02 | 2018-04-02T16:08:02 | 102,762,889 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,120 | ino | <<<<<<< HEAD
extern int clock_pin; // output to clock
extern int CSn_pin; // output to chip select
extern int input_pin; // read AS5045
extern int input_stream; // one bit read from pin
extern long packed_data; // two bytes concatenated from inputstream
extern long angle; // holds processed angle value
extern float angle_Float;
extern float true_angle;
extern float calib_angle;
extern float offset_angle; //17.02
extern float resting_angle;
extern float rotary_angle;
extern float starting_angle;
extern long printing_angle;
extern long angle_mask; // 0x111111111111000000: mask to obtain first 12 digits with position info
extern long status_mask; // 0x000000000000111111; mask to obtain last 6 digits containing status info
extern long status_bits; // holds status/error information
extern int DECn; // bit holding decreasing magnet field error data
extern int INCn; // bit holding increasing magnet field error data
extern int OCF; // bit holding startup-valid bit
extern int COF; // bit holding cordic DSP processing error data
extern int LIN; // bit holding magnet field displacement error data
extern int debug; // SET THIS TO 0 TO DISABLE PRINTING OF ERROR CODES
int parse = 0;
void setup() {
Serial.begin(9600);
setup_rotary_encoder();
calibrate_rotary_encoder();
}
void loop(){
delay(200);
// if(Serial.available()>0)
// {
// parse = Serial.parseInt();
// if(parse == 0){calibrate_rotary_encoder();}
// if(parse == 1){rotary_data();}
// }
float answer = rotary_data();
Serial.println(answer);
}
=======
extern int clock_pin; // output to clock
extern int CSn_pin; // output to chip select
extern int input_pin; // read AS5045
extern int input_stream; // one bit read from pin
extern long packed_data; // two bytes concatenated from inputstream
extern long angle; // holds processed angle value
extern float angle_Float;
extern float true_angle;
extern float calib_angle;
extern float offset_angle; //17.02
extern float resting_angle;
extern float rotary_angle;
extern float starting_angle;
extern long printing_angle;
extern long angle_mask; // 0x111111111111000000: mask to obtain first 12 digits with position info
extern long status_mask; // 0x000000000000111111; mask to obtain last 6 digits containing status info
extern long status_bits; // holds status/error information
extern int DECn; // bit holding decreasing magnet field error data
extern int INCn; // bit holding increasing magnet field error data
extern int OCF; // bit holding startup-valid bit
extern int COF; // bit holding cordic DSP processing error data
extern int LIN; // bit holding magnet field displacement error data
extern int debug; // SET THIS TO 0 TO DISABLE PRINTING OF ERROR CODES
int parse = 0;
void setup() {
Serial.begin(115200);
setup_rotary_encoder();
calibrate_rotary_encoder();
}
void loop(){
delay(200);
// if(Serial.available()>0)
// {
// parse = Serial.parseInt();
// if(parse == 0){calibrate_rotary_encoder();}
// if(parse == 1){rotary_data();}
// }
float answer = rotary_data();
Serial.println(answer);
}
>>>>>>> 2702f454d51990978334a05f56b994e10fce6f8c
| [
"[email protected]"
] | |
4d107e508358d09d131bf086c63d926356b90281 | 0c44da76a30138ebaee6700e2e33df5204ef21fc | /PSME/agent/storage/discovery/src/discoverers/iscsi/storage_zone_discoverer.cpp | e5544d0edc69388c79cb7bd8a12401699551e6f5 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | rwleea/intelRSD | 263e4c86801792be88e528d30d5a1d3c85af3a62 | 8e404abc211211a2d49776b8e3bf07d108c4bd4b | refs/heads/master | 2023-02-20T22:26:07.222243 | 2022-08-04T22:08:00 | 2022-08-04T22:08:00 | 64,722,362 | 0 | 0 | null | 2016-08-02T03:49:59 | 2016-08-02T03:49:58 | null | UTF-8 | C++ | false | false | 2,511 | cpp | /*!
* @brief Storage Zone discoverer implementation.
*
* @copyright Copyright (c) 2018-2019 Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License") override;
* 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.
*
* @file storage_zone_discoverer.cpp
*/
#include "storage_agent_context.hpp"
#include "discovery/discoverers/storage_zone_discoverer.hpp"
#include "agent-framework/database/database_entity.hpp"
#include "agent-framework/discovery/builders/zone_builder.hpp"
#include "agent-framework/module/common_components.hpp"
using namespace agent_framework::model;
using namespace agent::storage;
using namespace agent::storage::discovery;
using namespace database;
std::vector<Zone> StorageZoneDiscoverer::discover(const Uuid& parent_uuid) {
std::vector<Zone> zones{};
auto& pa = PersistentAttributes::get_instance();
for (const auto& record : Aggregate<PersistentAttributes>::get_aggregates(pa, literals::Zone::ZONE)) {
auto zone = agent_framework::discovery::ZoneBuilder::build_default(parent_uuid);
zone.set_uuid(record.get_uuid());
try {
for (const auto& endpoint_uuid : record.get_multiple_values(literals::Endpoint::ENDPOINT)) {
try {
agent_framework::module::get_manager<Endpoint>().get_entry(endpoint_uuid);
agent_framework::module::get_m2m_manager<Zone, Endpoint>().add_entry(record.get_uuid(), endpoint_uuid);
}
catch (const agent_framework::exceptions::InvalidUuid&) {
log_warning("storage-discovery",
"Zone " << record.get_uuid() << " points to a missing Endpoint " << endpoint_uuid);
zone.set_status({enums::State::Disabled, enums::Health::Critical});
}
}
}
catch (const std::out_of_range&) {
log_debug("storage-discovery", "Zone " << record.get_uuid() << " has no Endpoints");
}
zones.emplace_back(std::move(zone));
}
return zones;
} | [
"[email protected]"
] | |
e265fd527956f1542ae2462bd0d73d47ac89a4c6 | 4484d88a5c9305e6092932a5e4cd79f4d84862ef | /arc/019/019b.cpp | d0b94f948efaf6eaa895a97d33503bf78a54b673 | [] | no_license | kumastry/atcoder | 44dd20b9e784ecc2c92b772ef31fd84e007eb8cd | 076360ece55bd918a3bd60f8a7ac3c69dd1044e9 | refs/heads/main | 2023-07-13T06:44:42.296796 | 2021-08-12T18:36:27 | 2021-08-12T18:36:27 | 325,573,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,441 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <cstdio>
#include <set>
#include <map>
#include <list>
#include <cstdlib>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define MOD 1000000007
#define PI 3.1415926535897932
#define INF 1e9
#define rep(i, n) for (int i = 0; i < n; i++)
#define repe(i, j, n) for (int i = j; i < n; i++)
#define repi(i, n) for (int i = 0; i <= n; i++)
#define repie(i, j, n) for (int i = j; i <= n; i++)
#define all(x) x.begin(), x.end()
#define println() cout << endl
#define P pair<int, int>
#define fi first
#define se second
typedef long long ll;
long long modinv(long long a, long long m)
{
long long b = m, u = 1, v = 0;
while (b)
{
long long t = a / b;
a -= t * b;
swap(a, b);
u -= t * v;
swap(u, v);
}
u %= m;
if (u < 0)
u += m;
return u;
}
void solve1() {
string s; cin >> s;
string r(s); reverse(all(r));
cout << s << endl;
cout << r << endl;
int ans = 0;
int n = (int)r.size();
for(int i = 0; i<n; i++) {
if(i != n-i-1) {
if(s[i] == r[i]) {
ans += 25;
} else {
ans += 24;
}
} else {
}
}
cout << ans << endl;
}
int main()
{
solve1();
}
| [
"[email protected]"
] | |
195b410663d3521171018aeb4a824f7ed942a9b8 | 0814d3782a69326d304deea96ad4c849fce9377a | /dev/a2-carsoccer/ball.h | 91b473a0cbe8a7d52505a718fee2ba66b15505ef | [] | no_license | ryanYirui/csci4611-2020 | c75e99c556a993f4f747532703ed2c0f610916ba | 8cca7547cf04ca962ceb3388c86d2bca9b3fbaa9 | refs/heads/master | 2023-02-06T06:54:26.030025 | 2020-12-25T22:21:46 | 2020-12-25T22:21:46 | 324,441,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | h | /** CSci-4611 Assignment 2: Car Soccer
*/
#ifndef BALL_H_
#define BALL_H_
#include <mingfx.h>
/// Small data structure for a ball
class Ball {
public:
/// The constructor sets the radius and calls Reset() to start the ball at
/// the center of the field
Ball() : radius_(2.6) {
Reset();
}
/// Nothing special needed in the constructor
virtual ~Ball() {}
void Reset() {
position_ = Point3(0, radius_, 0);
}
float radius() { return radius_; }
Point3 position() { return position_; }
void set_position(const Point3 &p) { position_ = p; }
Vector3 velocity() { return velocity_; }
void set_velocity(const Vector3 &v) { velocity_ = v; } //aslo set the velocity i will use
private:
// You will probably need to store some additional data here, e.g., velocity
Point3 position_;
float radius_;
Vector3 velocity_; //velocity
};
#endif
| [
"[email protected]"
] | |
173be259988e622bbeb132a9e2b0bd89cb950a36 | 53c3c3ee9f51556f64375076a677ef892c6d3654 | /fancy_core/Common/Callback.h | 5cf20690ca4383b5e1f2a3e482f4bd8a4132400f | [] | no_license | domme/FANCY | 75133d47bb6c349e8d6ce60cc7777fcd907a1bb2 | f6451ead9a4758b16bee3f019e6fbff7487a5f70 | refs/heads/master | 2023-06-24T15:49:59.992434 | 2023-06-18T21:02:06 | 2023-06-18T21:02:06 | 7,263,701 | 29 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,583 | h | #pragma once
#include <functional>
namespace Fancy {
//---------------------------------------------------------------------------//
template<typename SignatureT>
struct Callback;
//---------------------------------------------------------------------------//
template<typename ReturnT, typename... Args>
struct Callback<ReturnT(Args...)>
{
Callback() : myInstance(nullptr) {}
Callback(const std::function<ReturnT(Args...)>& aFunction, void* anInstance)
: myInstance(anInstance)
{
myFunction = aFunction;
}
std::function<ReturnT(Args...)> myFunction;
void* myInstance;
};
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
// Bind 0 Args
//---------------------------------------------------------------------------//
template<class ClassT, class ReturnT>
Callback<ReturnT(void)>
Bind(ClassT* anInstance, ReturnT(ClassT::*aMemFnPtr) (void))
{
std::function<ReturnT(void)> func = std::bind(aMemFnPtr, anInstance);
return Callback<ReturnT(void)>(func, anInstance);
}
//---------------------------------------------------------------------------//
template<class ReturnT>
Callback<ReturnT(void)>
Bind(ReturnT(*aFnPtr) (void))
{
std::function<ReturnT(void)> func = aFnPtr;
return Callback<ReturnT(void)>(func, nullptr);
}
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
// Bind 1 Arg
//---------------------------------------------------------------------------//
template<class ClassT, class ReturnT, class Arg1T>
Callback<ReturnT(Arg1T)>
Bind(ClassT* anInstance, ReturnT(ClassT::*aMemFnPtr) (Arg1T))
{
std::function<ReturnT(Arg1T)> func = std::bind(aMemFnPtr, anInstance, std::placeholders::_1);
return Callback<ReturnT(Arg1T)>(func, anInstance);
}
//---------------------------------------------------------------------------//
template<class ClassT, class ReturnT, class Arg1T>
Callback<ReturnT(Arg1T)>
Bind(ClassT* anInstance, ReturnT(ClassT::*aMemFnPtr) (Arg1T), const Arg1T& anArg)
{
std::function<ReturnT(Arg1T)> func = std::bind(aMemFnPtr, anInstance, anArg);
return Callback<ReturnT(Arg1T)>(func, anInstance);
}
//---------------------------------------------------------------------------//
template<class ReturnT, class Arg1T>
Callback<ReturnT(Arg1T)>
Bind(ReturnT(*aFnPtr) (Arg1T))
{
std::function<ReturnT(Arg1T)> func = aFnPtr;
return Callback<ReturnT(Arg1T)>(func, nullptr);
}
//---------------------------------------------------------------------------//
template<class ReturnT, class Arg1T>
Callback<ReturnT(Arg1T)>
Bind(ReturnT(*aFnPtr) (Arg1T), const Arg1T& anArg)
{
std::function<ReturnT(Arg1T)> func = std::bind(aFnPtr, anArg);
return Callback<ReturnT(Arg1T)>(func, nullptr);
}
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
// Bind 2 Args
//---------------------------------------------------------------------------//
template<class ClassT, class ReturnT, class Arg1T, class Arg2T>
Callback<ReturnT(Arg1T, Arg2T)>
Bind(ClassT* anInstance, ReturnT(ClassT::*aMemFnPtr) (Arg1T, Arg2T))
{
std::function<ReturnT(Arg1T, Arg2T)> func = std::bind(aMemFnPtr, anInstance, std::placeholders::_1, std::placeholders::_2);
return Callback<ReturnT(Arg1T, Arg2T)>(func, anInstance);
}
//---------------------------------------------------------------------------//
template<class ClassT, class ReturnT, class Arg1T, class Arg2T>
Callback<ReturnT(Arg1T, Arg2T)>
Bind(ClassT* anInstance, ReturnT(ClassT::*aMemFnPtr) (Arg1T, Arg2T), const Arg1T& anArg1, const Arg2T& anArg2)
{
std::function<ReturnT(Arg1T, Arg2T)> func = std::bind(aMemFnPtr, anInstance, anArg1, anArg2);
return Callback<ReturnT(Arg1T, Arg2T)>(func, anInstance);
}
//---------------------------------------------------------------------------//
template<class ReturnT, class Arg1T, class Arg2T>
Callback<ReturnT(Arg1T, Arg2T)>
Bind(ReturnT(*aFnPtr) (Arg1T, Arg2T))
{
std::function<ReturnT(Arg1T, Arg2T)> func = std::bind(aFnPtr, std::placeholders::_1, std::placeholders::_2);
return Callback<ReturnT(Arg1T, Arg2T)>(func, nullptr);
}
//---------------------------------------------------------------------------//
template<class ReturnT, class Arg1T, class Arg2T>
Callback<ReturnT(Arg1T, Arg2T)>
Bind(ReturnT(*aFnPtr) (Arg1T, Arg2T), const Arg1T& anArg1, const Arg2T& anArg2)
{
std::function<ReturnT(Arg1T, Arg2T)> func = std::bind(aFnPtr, anArg1, anArg2);
return Callback<ReturnT(Arg1T, Arg2T)>(func, nullptr);
}
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
// Bind 3 Args
//---------------------------------------------------------------------------//
template<class ClassT, class ReturnT, class Arg1T, class Arg2T, class Arg3T>
Callback<ReturnT(Arg1T, Arg2T, Arg3T)>
Bind(ClassT* anInstance,ReturnT(ClassT::*aMemFnPtr) (Arg1T, Arg2T, Arg3T))
{
std::function<ReturnT(Arg1T, Arg2T, Arg3T)> func
= std::bind(aMemFnPtr, anInstance, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
return Callback<ReturnT(Arg1T, Arg2T, Arg3T)>(func, anInstance);
}
//---------------------------------------------------------------------------//
template<class ClassT, class ReturnT, class Arg1T, class Arg2T, class Arg3T>
Callback<ReturnT(Arg1T, Arg2T, Arg3T)>
Bind(ClassT* anInstance,
ReturnT(ClassT::*aMemFnPtr) (Arg1T, Arg2T, Arg3T),
const Arg1T& anArg1,
const Arg2T& anArg2,
const Arg3T& anArg3)
{
std::function<ReturnT(Arg1T, Arg2T, Arg3T)> func
= std::bind(aMemFnPtr, anInstance, anArg1, anArg2, anArg3);
return Callback<ReturnT(Arg1T, Arg2T, Arg3T)>(func, anInstance);
}
//---------------------------------------------------------------------------//
template<class ReturnT, class Arg1T, class Arg2T, class Arg3T>
Callback<ReturnT(Arg1T, Arg2T, Arg3T)>
Bind(ReturnT(*aFnPtr) (Arg1T, Arg2T, Arg3T))
{
std::function<ReturnT(Arg1T, Arg2T, Arg3T)> func
= std::bind(aFnPtr, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
return Callback<ReturnT(Arg1T, Arg2T, Arg3T)>(func, nullptr);
}
//---------------------------------------------------------------------------//
template<class ReturnT, class Arg1T, class Arg2T, class Arg3T>
Callback<ReturnT(Arg1T, Arg2T, Arg3T)>
Bind(ReturnT(*aFnPtr) (Arg1T, Arg2T, Arg3T),
const Arg1T& anArg1,
const Arg2T& anArg2,
const Arg3T& anArg3)
{
std::function<ReturnT(Arg1T, Arg2T, Arg3T)> func
= std::bind(aFnPtr, anArg1, anArg2, anArg3);
return Callback<ReturnT(Arg1T, Arg2T, Arg3T)>(func, nullptr);
}
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
// Bind 4 Args
//---------------------------------------------------------------------------//
template<class ClassT, class ReturnT, class Arg1T, class Arg2T, class Arg3T, class Arg4T>
Callback<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)>
Bind(ClassT* anInstance, ReturnT(ClassT::*aMemFnPtr) (Arg1T, Arg2T, Arg3T, Arg4T))
{
std::function<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)> func
= std::bind(aMemFnPtr, anInstance, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
return Callback<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)>(func, anInstance);
}
//---------------------------------------------------------------------------//
template<class ClassT, class ReturnT, class Arg1T, class Arg2T, class Arg3T, class Arg4T>
Callback<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)>
Bind(ClassT* anInstance, ReturnT(ClassT::*aMemFnPtr) (Arg1T, Arg2T, Arg3T, Arg4T), const Arg1T& anArg1, const Arg2T& anArg2, const Arg3T& anArg3, const Arg4T& anArg4)
{
std::function<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)> func
= std::bind(aMemFnPtr, anInstance, anArg1, anArg2, anArg3, anArg4);
return Callback<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)>(func, anInstance);
}
//---------------------------------------------------------------------------//
template<class ReturnT, class Arg1T, class Arg2T, class Arg3T, class Arg4T>
Callback<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)>
Bind(ReturnT(*aFnPtr) (Arg1T, Arg2T, Arg3T, Arg4T))
{
std::function<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)> func
= std::bind(aFnPtr, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
return Callback<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)>(func, nullptr);
}
//---------------------------------------------------------------------------//
template<class ReturnT, class Arg1T, class Arg2T, class Arg3T, class Arg4T>
Callback<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)>
Bind(ReturnT(*aFnPtr) (Arg1T, Arg2T, Arg3T, Arg4T), const Arg1T& anArg1, const Arg2T& anArg2, const Arg3T& anArg3, const Arg4T& anArg4)
{
std::function<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)> func
= std::bind(aFnPtr, anArg1, anArg2, anArg3, anArg4);
return Callback<ReturnT(Arg1T, Arg2T, Arg3T, Arg4T)>(func, nullptr);
}
//---------------------------------------------------------------------------//
}
| [
"[email protected]"
] | |
95c9dd3aee43a83f7fab1f306ac620eec56c4b5b | 42ba73134eeca961230044e4cef29a5fc35e3529 | /TktkDirectX12GameLib/_Test3DActionGame/src/GameObject/_CommonScripts/SelfDeadTimer/Act3D_SelfDeadTimer.cpp | 2f164234a95b5e77694aeeda6ddb8b23638a8406 | [] | no_license | tktk2104/TktkDirectX12GameLib | 5b9ef672ce0a99bbce8a156751b423ef840729b3 | 4d037ec603d9f30d8c4ed3fb4474cfaea49c8ac9 | refs/heads/master | 2023-02-22T14:38:10.101382 | 2020-12-03T04:55:05 | 2020-12-03T04:55:05 | 287,092,170 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 543 | cpp | #include "Act3D_SelfDeadTimer.h"
Act3D_SelfDeadTimer::Act3D_SelfDeadTimer(float deadTimeSec)
: m_deadTimeSec(deadTimeSec)
{
}
void Act3D_SelfDeadTimer::start()
{
// タイマーを初期化
m_deadSecTimer = m_deadTimeSec;
}
void Act3D_SelfDeadTimer::update()
{
// タイマーのカウントがゼロになったら
if (m_deadSecTimer < 0.0f)
{
// このコンポーネントの所持者を殺す
getGameObject()->destroy();
return;
}
// タイマーをカウントダウン
m_deadSecTimer -= tktk::DX12Game::deltaTime();
}
| [
"[email protected]"
] | |
f2b647c089b755fc6dfb404f7efa1472e90d1140 | 857bc06a760e91d6033a7e0bc0703d7ac09ed84d | /src/Robot.cpp | 023dcdf577b2fb37b748c3b22f443b0c0c7efcad | [] | no_license | guijiaqing/sfm_lib | cde81ca2f16ec748daea43b87d4fa920baeecae1 | d0104f0c8d7c9653d31f572931289e3174b7ddd6 | refs/heads/master | 2023-01-30T07:16:30.080557 | 2020-12-16T13:20:32 | 2020-12-16T13:20:32 | 321,986,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,823 | cpp | #include "Robot.h"
Robot::Robot(ros::NodeHandle &nh):nh_(nh),robot_state_(NORMAL){//整机状态normal
ROS_INFO("no param robot");
comm_ = new CommunicateInterface(nh,this);
add_Task();//默认加入Init_task 到 queueTask
}
Robot::~Robot(){
clear_Task();//清理内存
}
TaskState* Robot::nextTask_do(){//返回下一个任务
task_Copy2Old(taskState_);//删除之前,保存当前任务
if(!taskqueue_.empty()){//有任务
ROS_INFO("take one task in list");
return taskqueue_.front();//取任务
}else{//没有任务
return new FreeTaskState();//空闲状态
return NULL;
}
}
void Robot::task_Copy2Old(TaskState *tasks){//备份已经执行的任务
taskstack_old_.push(tasks);//把当前的存起来
ROS_INFO("pop one task in list");
taskqueue_.pop();//删除当前任务
}
TaskState* Robot::unTask_do(){//执行已经执行过的上一个任务,相当于撤销
}
void Robot::set_RobotStation(RobotStation sta){//设置机器人整机状态
robot_state_ = sta;
}
RobotStation Robot::get_RobotStation(){//获取机器人整机状态
return robot_state_;
}
int Robot::clear_Task(){//清空任务
while(!taskqueue_.empty()){
delete taskqueue_.front();
taskqueue_.pop();
}
while(!taskstack_old_.empty()){
delete taskstack_old_.top();
taskstack_old_.pop();
}
}
void Robot::add_Task(std::string taskname){//添加初始化任务
InitTaskState *initptr = new InitTaskState();//初始化任务
initptr->task_name_ = taskname;//给任务命名
initptr->init_nav_input = FREETAR;//给导航初始化输入
taskState_ = initptr;
taskState_->enter(this);
//taskqueue_.push(initptr);//添加任务
}
void Robot::add_Task(sfm_lib::targets_list::Request &targetTask){//添加执行任务
ROS_INFO("add task queue 2:%d",(int)(taskqueue_.size()));
while (!taskqueue_.empty()) taskqueue_.pop();
taskqueue_.push(new FreeTaskState());
int task_len = targetTask.target_points.size();
for(int i=0;i<task_len;i++){
ROS_INFO("0");
OneTaskState *taskptr = new OneTaskState();
ROS_INFO("1");
taskptr->task_name_ = "oneTask-"+std::to_string(i);//任务名称
taskptr->target_pose_ = targetTask.target_points[i];//目标位姿
taskptr->init_nav_input = TARGET;//导航目标状态
ROS_INFO("2");
taskqueue_.push(taskptr);//添加任务
ROS_INFO("3");
}
ROS_INFO("add task queue 1:%d",task_len);
ROS_INFO("add task queue 2:%d",(int)(taskqueue_.size()));
}
void Robot::changeTask(TaskInput task_input){//任务切换
ROS_INFO("enter changefun");
TaskState* tasknew = taskState_->handleInput(this,task_input);
if(tasknew!=NULL){
ROS_INFO("changefun delete");
delete taskState_;
taskState_ = tasknew;
taskState_->enter(this);
}
ROS_INFO("changefun done");
}
| [
"[email protected]"
] | |
94f52907d97a3190ca62adaaffebb4a3ff2f73a4 | 556766fa74cffccf5832ff55ab5b6078ae747bf8 | /src/tests/test_nn_search/nn_search_ANN.cpp | c292dd91b2b74a1147279dcb335a98593154cc96 | [] | no_license | deep-programmer/geogram | 00898a2a9c3f9997dfb3ee7f720a0babbc3e8c3b | 05b3ef4edf0b87b5e52ff7f93a520e0e98ab3951 | refs/heads/master | 2020-03-13T19:11:47.380662 | 2018-04-13T15:30:39 | 2018-04-13T15:30:39 | 131,248,784 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,897 | cpp | /*
* Copyright (c) 2012-2014, Bruno Levy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ALICE Project-Team nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact: Bruno Levy
*
* [email protected]
* http://www.loria.fr/~levy
*
* ALICE Project
* LORIA, INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
*/
#include "nn_search_ANN.h"
namespace GEO {
NearestNeighborSearch_ANN::NearestNeighborSearch_ANN(
coord_index_t dim
) :
NearestNeighborSearch(dim),
ann_tree_(nil) {
}
void NearestNeighborSearch_ANN::set_points(index_t nb_points, const double* points) {
set_points(nb_points, points, dimension());
}
bool NearestNeighborSearch_ANN::stride_supported() const {
return true;
}
void NearestNeighborSearch_ANN::set_points(
index_t nb_points, const double* points, index_t stride
) {
nb_points_ = nb_points;
points_ = points;
stride_ = stride;
// Patched ANN so that we no longer need
// to generate an array of pointers to
// the points, See ANN.h
#ifdef ANN_CONTIGUOUS_POINT_ARRAY
delete ann_tree_;
ann_tree_ = new ANNkd_tree(
ANNpointArray(points_, stride_),
int(nb_points),
int(dimension())
);
#else
delete ann_tree_;
ann_tree_ = nil;
ann_points_.resize(nb_points);
for(index_t i = 0; i < nb_points; i++) {
ann_points_[i] = const_cast<double*>(points) + stride_ * i;
}
ann_tree_ = new ANNkd_tree(
&ann_points_[0], int(nb_points), int(dimension())
);
#endif
}
void NearestNeighborSearch_ANN::get_nearest_neighbors(
index_t nb_neighbors,
const double* query_point,
index_t* neighbors,
double* neighbors_sq_dist
) const {
ann_tree_->annkSearch(
const_cast<double*>(query_point),
int(nb_neighbors), (ANNidxArray) neighbors, neighbors_sq_dist,
(exact_ ? 0.0 : 0.1)
);
}
NearestNeighborSearch_ANN::~NearestNeighborSearch_ANN() {
delete ann_tree_;
ann_tree_ = nil;
}
}
| [
"[email protected]"
] | |
d853bf9885c1d591b0676edf192242b4a416cb9f | 9f25ac38773b5ccdc0247c9d43948d50e60ab97a | /chrome/browser/ui/ash/projector/projector_client_impl.cc | 5e1ad9454d426bdb65b322930903dcc5aeef4215 | [
"BSD-3-Clause"
] | permissive | liang0/chromium | e206553170eab7b4ac643ef7edc8cc57d4c74342 | 7a028876adcc46c7f7079f894a810ea1f511c3a7 | refs/heads/main | 2023-03-25T05:49:21.688462 | 2021-04-28T06:07:52 | 2021-04-28T06:07:52 | 362,370,889 | 1 | 0 | BSD-3-Clause | 2021-04-28T07:04:42 | 2021-04-28T07:04:41 | null | UTF-8 | C++ | false | false | 3,228 | cc | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/ash/projector/projector_client_impl.h"
#include "ash/public/cpp/projector/projector_controller.h"
#include "base/optional.h"
#include "chrome/browser/accessibility/soda_installer.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/speech/on_device_speech_recognizer.h"
#include "media/base/media_switches.h"
namespace {
// On-device speech recognition is only available in US English.
const char kEnglishLanguageCode[] = "en-US";
bool ShouldUseWebSpeechFallback() {
return !base::FeatureList::IsEnabled(media::kUseSodaForLiveCaption);
}
} // namespace
ProjectorClientImpl::ProjectorClientImpl() {
ash::ProjectorController::Get()->SetClient(this);
bool recognition_available =
OnDeviceSpeechRecognizer::IsOnDeviceSpeechRecognizerAvailable(
kEnglishLanguageCode) ||
ShouldUseWebSpeechFallback();
ash::ProjectorController::Get()->OnSpeechRecognitionAvailable(
recognition_available);
if (!recognition_available) {
observed_soda_installer_.Observe(speech::SodaInstaller::GetInstance());
}
}
ProjectorClientImpl::~ProjectorClientImpl() = default;
void ProjectorClientImpl::StartSpeechRecognition() {
// ProjectorController should only request for speech recognition after it
// has been informed that recognition is available.
// TODO(crbug.com/1165437): Dynamically determine language code.
DCHECK(OnDeviceSpeechRecognizer::IsOnDeviceSpeechRecognizerAvailable(
kEnglishLanguageCode) ||
ShouldUseWebSpeechFallback());
DCHECK_EQ(speech_recognizer_.get(), nullptr);
speech_recognizer_ = std::make_unique<OnDeviceSpeechRecognizer>(
weak_ptr_factory_.GetWeakPtr(), ProfileManager::GetPrimaryUserProfile(),
kEnglishLanguageCode, /*recognition_mode_ime=*/false);
speech_recognizer_->Start();
}
void ProjectorClientImpl::StopSpeechRecognition() {
speech_recognizer_.reset();
recognizer_status_ = SPEECH_RECOGNIZER_OFF;
}
void ProjectorClientImpl::OnSpeechResult(
const std::u16string& text,
bool is_final,
const base::Optional<SpeechRecognizerDelegate::TranscriptTiming>& timing) {
DCHECK(timing.has_value() || ShouldUseWebSpeechFallback());
if (timing.has_value()) {
ash::ProjectorController::Get()->OnTranscription(
text, timing->audio_start_time, timing->audio_end_time,
timing->word_offsets, is_final);
} else {
// This is only used for development.
ash::ProjectorController::Get()->OnTranscription(
text, base::nullopt, base::nullopt, base::nullopt, is_final);
}
}
void ProjectorClientImpl::OnSpeechRecognitionStateChanged(
SpeechRecognizerStatus new_state) {
recognizer_status_ = new_state;
// TODO(yilkal): Handle the new state appropriately.
}
void ProjectorClientImpl::OnSodaInstalled() {
// OnDevice has been installed! Notify ProjectorController in ash.
DCHECK(OnDeviceSpeechRecognizer::IsOnDeviceSpeechRecognizerAvailable(
kEnglishLanguageCode));
ash::ProjectorController::Get()->OnSpeechRecognitionAvailable(true);
}
| [
"[email protected]"
] | |
ad0146f1060517f6da2d135a0ea7d0d0af9cbceb | 6edda4cef6bea60a7d38041a833508bcd51a0fbc | /1867.cpp | 08add536b6b799bf2819d9f42b4417a53d2480d6 | [] | no_license | IIIIIIIIIU/onlysky | addd908364c2e4f42dfdf09b0ea7995b354b78f6 | c534c66a3e208734f3fd6f3eb9b76e82a9e6d036 | refs/heads/master | 2021-09-14T21:45:40.795263 | 2018-05-20T07:49:28 | 2018-05-20T07:49:28 | 104,289,423 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,096 | cpp | #include <cstdio>
#include <iostream>
#include <vector>
#include <iomanip>
#include <cassert>
#include <algorithm>
const int Big_B = 1000000000; const int Big_L = 9;
using namespace std;
inline int intcmp_ (int a, int b) { if (a > b) return 1; return a < b ? -1 : 0; }
struct Int
{
#define rg register
inline int max (int a, int b) { return a > b ? a : b; }
inline int min (int a, int b) { return a < b ? a : b; }
std :: vector <int> c; Int () {} typedef long long LL;
Int (int x) { for (; x > 0; c.push_back (x % Big_B), x /= Big_B); }
Int (LL x) { for (; x > 0; c.push_back (x % Big_B), x /= Big_B); }
inline void CrZ () { for (; !c.empty () && c.back () == 0; c.pop_back ()); }
inline Int &operator += (const Int &rhs)
{
c.resize (max (c.size (), rhs.c.size ())); rg int i, t = 0, S;
for (i = 0, S = rhs.c.size (); i < S; ++ i)
c[i] += rhs.c[i] + t, t = c[i] >= Big_B, c[i] -= Big_B & (-t);
for (i = rhs.c.size (), S = c.size (); t && i < S; ++ i)
c[i] += t, t = c[i] >= Big_B, c[i] -= Big_B & (-t);
if (t) c.push_back (t); return *this;
}
inline Int &operator -= (const Int &rhs)
{
c.resize (max (c.size (), rhs.c.size ())); rg int i, t = 0, S;
for (i = 0, S = rhs.c.size (); i < S; ++ i)
c[i] -= rhs.c[i] + t, t = c[i] < 0, c[i] += Big_B & (-t);
for (i = rhs.c.size (), S = c.size (); t && i < S; ++ i)
c[i] -= t, t = c[i] < 0, c[i] += Big_B & (-t);
CrZ (); return *this;
}
inline Int &operator *= (const Int &rhs)
{
rg int na = c.size (), i, j, S, ai;
c.resize (na + rhs.c.size ()); LL t;
for (i = na - 1; i >= 0; -- i)
{
ai = c[i], t = 0, c[i] = 0;
for (j = 0, S = rhs.c.size (); j < S; ++ j)
{
t += c[i + j] + (LL) ai * rhs.c[j];
c[i + j] = t % Big_B, t /= Big_B;
}
for (j = rhs.c.size (), S = c.size (); t != 0 && i + j < S; ++ j)
t += c[i + j], c[i + j] = t % Big_B, t /= Big_B;
assert (t == 0);
}
CrZ (); return *this;
}
inline Int &operator /= (const Int &rhs) { return *this = div (rhs); }
inline Int &operator %= (const Int &rhs) { return div (rhs), *this; }
inline Int &shlb (int l = 1)
{
if (c.empty ()) return *this; c.resize (c.size () + l);rg int i;
for (i = c.size () - 1; i >= l; -- i) c[i] = c[i - l];
for (i = 0; i < l; ++ i) c[i] = 0;
return *this;
}
inline Int &shrb (int l = 1)
{
for (rg int i = 0; i < c.size () - l; ++ i) c[i] = c[i + l];
c.resize (max (c.size () - l, 0)); return *this;
}
inline int Comp (const Int &rhs) const
{
if (c.size () != rhs.c.size ()) return intcmp_ (c.size (), rhs.c.size ());
for (rg int i = c.size () - 1; i >= 0; -- i)
if (c[i] != rhs.c[i]) return intcmp_ (c[i], rhs.c[i]);
return 0;
}
inline Int div (const Int &rhs)
{
assert (!rhs.c.empty ()); Int q, r; rg int i; if (rhs > *this) return 0;
q.c.resize (c.size () - rhs.c.size () + 1); rg int _l, _r, mid;
for (i = c.size () - 1; i > c.size () - rhs.c.size (); -- i) r.shlb (), r += c[i];
for (i = c.size () - rhs.c.size (); i >= 0; -- i)
{
r.shlb (); r += c[i];
if (r.Comp (rhs) < 0) q.c[i] = 0;
else
{
_l = 0, _r = Big_B;
for (; _l != _r; )
{
mid = _l + _r >> 1;
if ((rhs * mid).Comp (r) <= 0) _l = mid + 1; else _r = mid;
}
q.c[i] = _l - 1, r -= rhs * q.c[i];
}
}
q.CrZ (), *this = r; return q;
}
friend inline Int operator + (const Int &lhs, const Int &rhs)
{ Int res = lhs; return res += rhs; }
friend inline Int operator - (const Int &lhs, const Int &rhs)
{ Int res = lhs; return res -= rhs; }
friend inline Int operator * (const Int &lhs, const Int &rhs)
{ Int res = lhs; return res *= rhs; }
friend inline Int operator / (const Int &lhs, const Int &rhs)
{ Int res = lhs; return res.div (rhs); }
friend inline Int operator % (const Int &lhs, const Int &rhs)
{ Int res = lhs; return res.div (rhs), res; }
friend inline ostream &operator << (ostream &out, const Int &rhs)
{
if (rhs.c.size () == 0) out << "0";
else
{
out << rhs.c.back ();
for (rg int i = rhs.c.size () - 2; i >= 0; -- i)
out << setfill ('0') << setw (Big_L) << rhs.c[i];
}
return out;
}
friend inline bool operator < (const Int &lhs, const Int &rhs)
{ return lhs.Comp (rhs) < 0; }
friend inline bool operator <= (const Int &lhs, const Int &rhs)
{ return lhs.Comp (rhs) <= 0; }
friend inline bool operator > (const Int &lhs, const Int &rhs)
{ return lhs.Comp (rhs) > 0; }
friend inline bool operator >= (const Int &lhs, const Int &rhs)
{ return lhs.Comp (rhs) >= 0; }
friend inline bool operator == (const Int &lhs, const Int &rhs)
{ return lhs.Comp (rhs) == 0; }
friend inline bool operator != (const Int &lhs, const Int &rhs)
{ return lhs.Comp (rhs) != 0; }
#undef rg
};
typedef Int ll;
ll gcd(ll a,ll b)
{
return b!=0?gcd(b,a%b):a;
}
struct node
{
ll up,down;
node(ll up_=0,ll down_=0)
{
up=up_,down=down_;
}
node operator+(const node &pos)const
{
if(up==0&&pos.up==0) return node(0,0);
if(up==0||down==0) return node(pos.up,pos.down);
if(pos.up==0||pos.down==0) return node(up,down);
node res;
res.up=up*pos.down+pos.up*down;
res.down=down*pos.down;
ll tmp=gcd(res.up,res.down);
res.up/=tmp,res.down/=tmp;
// if(res.down<0)
// {
// ll daw=0;
// cout<<pos.up<<' '<<pos.down<<endl;
// cout<<up<<' '<<down<<endl;
// }
return res;
}
node operator*(const ll pos)const
{
node res(up,down*pos);
if(res.up==0) return res;
ll tmp=gcd(res.up,res.down);
res.up/=tmp;
res.down/=tmp;
return res;
}
};
struct node dp[60][60];
ll n,m;
int main()
{
int x,y;
cin>>x>>y;n=x,m=y;
char op[5];
dp[1][1]=node(1,1);
for(int i=1;i<=x;i++)
for(int v=1;v<=i;v++)
{
cin>>op;
if(dp[i][v].up==0||dp[i][v].down==0) continue;
if(op[0]=='*')
{
dp[i+1][v]=dp[i+1][v]+(dp[i][v]*2);
dp[i+1][v+1]=dp[i+1][v+1]+(dp[i][v]*2);
}
else dp[i+2][v+1]=dp[i+2][v+1]+dp[i][v];
}
/*
for(ll i=1;i<=n+1;i++)
{
for(ll v=1;v<=i;v++)
{
printf("%d,%d ",dp[i][v].up,dp[i][v].down);
}
printf("\n");
}
*/
// printf("%lld",dp[n+1][m+1].up);
cout<<dp[x+1][y+1].up;
putchar('/');
cout<<dp[x+1][y+1].down;
return 0;
}
| [
"[email protected]"
] | |
936bdd04be0506383657ab7cfac2584bb7d1ac92 | 7d1dc4ef43930b76635ad88b1dc33b8438b03b23 | /Monitoring/build-online_display-Desktop_Qt_5_4_2_GCC_64bit-Debug/moc_DisplayDrawer.cpp | 03697c9e87bb10c21faeb9766799a298e2941303 | [] | no_license | meleneemil/OLD-nsw-vmm-monitoring | 4ad66027539f2bf9d56ac7553a1c76813ac863c8 | d8e3992b1ed6adaee0dcfe27f5a04b30088ba66b | refs/heads/master | 2021-06-04T15:54:02.602024 | 2016-07-23T16:21:09 | 2016-07-23T16:21:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,151 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'DisplayDrawer.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../monitoring/DisplayDrawer.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#include <QtCore/QVector>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'DisplayDrawer.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.4.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_DisplayDrawer_t {
QByteArrayData data[44];
char stringdata[626];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_DisplayDrawer_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_DisplayDrawer_t qt_meta_stringdata_DisplayDrawer = {
{
QT_MOC_LITERAL(0, 0, 13), // "DisplayDrawer"
QT_MOC_LITERAL(1, 14, 10), // "NotifyFill"
QT_MOC_LITERAL(2, 25, 0), // ""
QT_MOC_LITERAL(3, 26, 42), // "QVector<std::pair<QString,QVe..."
QT_MOC_LITERAL(4, 69, 7), // "rawData"
QT_MOC_LITERAL(5, 77, 24), // "std::vector<std::string>"
QT_MOC_LITERAL(6, 102, 9), // "stripData"
QT_MOC_LITERAL(7, 112, 11), // "eventNumber"
QT_MOC_LITERAL(8, 124, 10), // "NotifyDraw"
QT_MOC_LITERAL(9, 135, 14), // "drawSharedData"
QT_MOC_LITERAL(10, 150, 15), // "changeActiveTab"
QT_MOC_LITERAL(11, 166, 8), // "tabIndex"
QT_MOC_LITERAL(12, 175, 13), // "fill_chip_raw"
QT_MOC_LITERAL(13, 189, 4), // "name"
QT_MOC_LITERAL(14, 194, 12), // "QVector<int>"
QT_MOC_LITERAL(15, 207, 9), // "rawVector"
QT_MOC_LITERAL(16, 217, 17), // "apvRawHistoFiller"
QT_MOC_LITERAL(17, 235, 18), // "readoutHistoFiller"
QT_MOC_LITERAL(18, 254, 19), // "handleBufferedEvent"
QT_MOC_LITERAL(19, 274, 9), // "line_qstr"
QT_MOC_LITERAL(20, 284, 17), // "fillReadoutHistos"
QT_MOC_LITERAL(21, 302, 11), // "std::string"
QT_MOC_LITERAL(22, 314, 11), // "chamberName"
QT_MOC_LITERAL(23, 326, 11), // "readoutName"
QT_MOC_LITERAL(24, 338, 5), // "strip"
QT_MOC_LITERAL(25, 344, 6), // "charge"
QT_MOC_LITERAL(26, 351, 4), // "time"
QT_MOC_LITERAL(27, 356, 3), // "pdo"
QT_MOC_LITERAL(28, 360, 3), // "tdo"
QT_MOC_LITERAL(29, 364, 14), // "fillChipHistos"
QT_MOC_LITERAL(30, 379, 9), // "fecNumber"
QT_MOC_LITERAL(31, 389, 10), // "chipNumber"
QT_MOC_LITERAL(32, 400, 13), // "channelNumber"
QT_MOC_LITERAL(33, 414, 14), // "fillHistograms"
QT_MOC_LITERAL(34, 429, 14), // "drawHistograms"
QT_MOC_LITERAL(35, 444, 20), // "drawStatisticsHistos"
QT_MOC_LITERAL(36, 465, 15), // "drawEventHistos"
QT_MOC_LITERAL(37, 481, 16), // "drawApvRawHistos"
QT_MOC_LITERAL(38, 498, 24), // "drawChipStatisticsHistos"
QT_MOC_LITERAL(39, 523, 19), // "drawPedestalsHistos"
QT_MOC_LITERAL(40, 543, 10), // "reset_slot"
QT_MOC_LITERAL(41, 554, 26), // "resetStatisticsHistos_slot"
QT_MOC_LITERAL(42, 581, 21), // "resetEventHistos_slot"
QT_MOC_LITERAL(43, 603, 22) // "resetApvRawHistos_slot"
},
"DisplayDrawer\0NotifyFill\0\0"
"QVector<std::pair<QString,QVector<int> > >\0"
"rawData\0std::vector<std::string>\0"
"stripData\0eventNumber\0NotifyDraw\0"
"drawSharedData\0changeActiveTab\0tabIndex\0"
"fill_chip_raw\0name\0QVector<int>\0"
"rawVector\0apvRawHistoFiller\0"
"readoutHistoFiller\0handleBufferedEvent\0"
"line_qstr\0fillReadoutHistos\0std::string\0"
"chamberName\0readoutName\0strip\0charge\0"
"time\0pdo\0tdo\0fillChipHistos\0fecNumber\0"
"chipNumber\0channelNumber\0fillHistograms\0"
"drawHistograms\0drawStatisticsHistos\0"
"drawEventHistos\0drawApvRawHistos\0"
"drawChipStatisticsHistos\0drawPedestalsHistos\0"
"reset_slot\0resetStatisticsHistos_slot\0"
"resetEventHistos_slot\0resetApvRawHistos_slot"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_DisplayDrawer[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
21, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 3, 119, 2, 0x0a /* Public */,
8, 0, 126, 2, 0x0a /* Public */,
9, 0, 127, 2, 0x0a /* Public */,
10, 1, 128, 2, 0x0a /* Public */,
12, 2, 131, 2, 0x0a /* Public */,
16, 0, 136, 2, 0x0a /* Public */,
17, 0, 137, 2, 0x0a /* Public */,
18, 1, 138, 2, 0x0a /* Public */,
20, 7, 141, 2, 0x0a /* Public */,
29, 5, 156, 2, 0x0a /* Public */,
33, 0, 167, 2, 0x0a /* Public */,
34, 0, 168, 2, 0x0a /* Public */,
35, 0, 169, 2, 0x0a /* Public */,
36, 0, 170, 2, 0x0a /* Public */,
37, 0, 171, 2, 0x0a /* Public */,
38, 0, 172, 2, 0x0a /* Public */,
39, 0, 173, 2, 0x0a /* Public */,
40, 0, 174, 2, 0x0a /* Public */,
41, 0, 175, 2, 0x0a /* Public */,
42, 0, 176, 2, 0x0a /* Public */,
43, 0, 177, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void, 0x80000000 | 3, 0x80000000 | 5, QMetaType::Int, 4, 6, 7,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, 11,
QMetaType::Void, QMetaType::QString, 0x80000000 | 14, 13, 15,
QMetaType::Void,
QMetaType::Void,
QMetaType::Int, QMetaType::QString, 19,
QMetaType::Void, 0x80000000 | 21, 0x80000000 | 21, QMetaType::Int, QMetaType::Float, QMetaType::Float, QMetaType::Int, QMetaType::Int, 22, 23, 24, 25, 26, 27, 28,
QMetaType::Void, QMetaType::Int, QMetaType::Int, QMetaType::Int, QMetaType::Float, QMetaType::Float, 30, 31, 32, 25, 26,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void DisplayDrawer::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
DisplayDrawer *_t = static_cast<DisplayDrawer *>(_o);
switch (_id) {
case 0: _t->NotifyFill((*reinterpret_cast< QVector<std::pair<QString,QVector<int> > >(*)>(_a[1])),(*reinterpret_cast< std::vector<std::string>(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
case 1: _t->NotifyDraw(); break;
case 2: _t->drawSharedData(); break;
case 3: _t->changeActiveTab((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: _t->fill_chip_raw((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QVector<int>(*)>(_a[2]))); break;
case 5: _t->apvRawHistoFiller(); break;
case 6: _t->readoutHistoFiller(); break;
case 7: { int _r = _t->handleBufferedEvent((*reinterpret_cast< QString(*)>(_a[1])));
if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break;
case 8: _t->fillReadoutHistos((*reinterpret_cast< std::string(*)>(_a[1])),(*reinterpret_cast< std::string(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< float(*)>(_a[4])),(*reinterpret_cast< float(*)>(_a[5])),(*reinterpret_cast< int(*)>(_a[6])),(*reinterpret_cast< int(*)>(_a[7]))); break;
case 9: _t->fillChipHistos((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< float(*)>(_a[4])),(*reinterpret_cast< float(*)>(_a[5]))); break;
case 10: _t->fillHistograms(); break;
case 11: _t->drawHistograms(); break;
case 12: _t->drawStatisticsHistos(); break;
case 13: _t->drawEventHistos(); break;
case 14: _t->drawApvRawHistos(); break;
case 15: _t->drawChipStatisticsHistos(); break;
case 16: _t->drawPedestalsHistos(); break;
case 17: _t->reset_slot(); break;
case 18: _t->resetStatisticsHistos_slot(); break;
case 19: _t->resetEventHistos_slot(); break;
case 20: _t->resetApvRawHistos_slot(); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 4:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QVector<int> >(); break;
}
break;
}
}
}
const QMetaObject DisplayDrawer::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_DisplayDrawer.data,
qt_meta_data_DisplayDrawer, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *DisplayDrawer::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *DisplayDrawer::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_DisplayDrawer.stringdata))
return static_cast<void*>(const_cast< DisplayDrawer*>(this));
return QObject::qt_metacast(_clname);
}
int DisplayDrawer::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 21)
qt_static_metacall(this, _c, _id, _a);
_id -= 21;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 21)
qt_static_metacall(this, _c, _id, _a);
_id -= 21;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
bbd3bce5a5a36feaf8fd6a174bbefc5fed86e46e | e7c2b510eabafe7cb3109ed31a74c691aa0da526 | /FarNet/FarNetMan/Viewer.cpp | dfe28f411d4f6842503951c1e5fadedc52dc63fb | [] | no_license | valery-barysok/FarNet | 7bb3e1a58f335a8faa82ea6f95afac666b5aac71 | 043c34b685e5b963a056d21d4ffb3337c43bb832 | refs/heads/master | 2020-12-06T22:04:51.785180 | 2015-12-07T16:02:52 | 2015-12-07T16:02:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,101 | cpp |
/*
FarNet plugin for Far Manager
Copyright (c) 2006-2015 Roman Kuzmin
*/
#include "StdAfx.h"
#include "Viewer.h"
#include "Viewer0.h"
namespace FarNet
{;
void AnyViewer::ViewText(String^ text, String^ title, OpenMode mode)
{
Works::EditorTools::ViewText(text, title, mode);
}
Viewer::Viewer()
: _id(-1)
, _Title(String::Empty)
, _CodePage(CP_DEFAULT)
{}
void Viewer::Open(OpenMode mode)
{
AssertClosed();
if (ValueUserScreen::Get()) //????
{
ValueUserScreen::Set(false);
Far::Api->UI->SaveUserScreen();
}
// flags
int flags = 0;
if (_DisableHistory)
flags |= VF_DISABLEHISTORY;
switch(_Switching)
{
case FarNet::Switching::Enabled:
flags |= VF_ENABLE_F6;
break;
case FarNet::Switching::Auto:
if (_DeleteSource == FarNet::DeleteSource::None &&
_Closed == nullptr &&
_GotFocus == nullptr &&
_LosingFocus == nullptr &&
_Opened == nullptr)
flags |= VF_ENABLE_F6;
break;
}
switch(mode)
{
case OpenMode::None:
flags |= (VF_NONMODAL | VF_IMMEDIATERETURN); break;
case OpenMode::Wait:
flags |= VF_NONMODAL; break;
}
switch(_DeleteSource)
{
case FarNet::DeleteSource::UnusedFile:
flags |= VF_DELETEONLYFILEONCLOSE; break;
case FarNet::DeleteSource::UnusedFolder:
flags |= VF_DELETEONCLOSE; break;
}
PIN_ES(pinFileName, _FileName);
PIN_ES(pinTitle, _Title);
// from dialog? set modal
WindowKind wt = Far::Api->Window->Kind;
if (wt == WindowKind::Dialog || Far::Api->UI->IsCommandMode)
flags &= ~VF_NONMODAL;
// open: see editor
_id = -1;
Viewer0::_viewerWaiting = this;
Info.Viewer(
pinFileName,
pinTitle,
_Window.Left,
_Window.Top,
_Window.Right,
_Window.Bottom,
flags,
_CodePage); //?? test window values
// redraw Far
if (wt == WindowKind::Dialog)
Far::Api->UI->Redraw();
// errors: see editor
if (_id == -1)
throw gcnew InvalidOperationException("Cannot open the file '" + FileName + "'");
}
IntPtr Viewer::Id::get()
{
return (IntPtr)_id;
}
DeleteSource Viewer::DeleteSource::get()
{
return _DeleteSource;
}
void Viewer::DeleteSource::set(FarNet::DeleteSource value)
{
_DeleteSource = value;
}
Switching Viewer::Switching::get()
{
return _Switching;
}
void Viewer::Switching::set(FarNet::Switching value)
{
AssertClosed();
_Switching = value;
}
bool Viewer::DisableHistory::get()
{
return _DisableHistory;
}
void Viewer::DisableHistory::set(bool value)
{
AssertClosed();
_DisableHistory = value;
}
bool Viewer::IsOpened::get()
{
return _id >= 0;
}
String^ Viewer::FileName::get()
{
return _FileName;
}
void Viewer::FileName::set(String^ value)
{
AssertClosed();
_FileName = value;
}
String^ Viewer::Title::get()
{
return _Title;
}
Int64 Viewer::FileSize::get()
{
ViewerInfo vi; ViewerControl_VCTL_GETINFO(vi, true);
if (vi.ViewerID >= 0 && vi.ViewerID == _id)
return vi.FileSize;
else
return -1;
}
Point Viewer::WindowSize::get()
{
ViewerInfo vi; ViewerControl_VCTL_GETINFO(vi, true);
Point r;
if (vi.ViewerID >= 0 && vi.ViewerID == _id)
{
r.X = (int)vi.WindowSizeX;
r.Y = (int)vi.WindowSizeY;
}
return r;
}
void Viewer::Title::set(String^ value)
{
AssertClosed();
_Title = value;
}
Place Viewer::Window::get()
{
return _Window;
}
void Viewer::Window::set(Place value)
{
AssertClosed();
_Window = value;
}
ViewFrame Viewer::Frame::get()
{
ViewerInfo vi; ViewerControl_VCTL_GETINFO(vi, true);
ViewFrame r;
if (vi.ViewerID >= 0 && vi.ViewerID == _id)
{
r.Offset = vi.FilePos;
r.Column = vi.LeftPos;
}
return r;
}
void Viewer::Frame::set(ViewFrame value)
{
AssertCurrentViewer();
ViewerSetPosition vsp = {sizeof(vsp)};
vsp.Flags = VSP_NORETNEWPOS;
vsp.LeftPos = value.Column;
vsp.StartPos = value.Offset;
Info.ViewerControl(_id, VCTL_SETPOSITION, 0, &vsp);
}
Int64 Viewer::SetFrame(Int64 pos, int left, ViewFrameOptions options)
{
AssertCurrentViewer();
ViewerSetPosition vsp = {sizeof(vsp)};
vsp.Flags = (DWORD)options;
vsp.LeftPos = left;
vsp.StartPos = pos;
Info.ViewerControl(_id, VCTL_SETPOSITION, 0, &vsp);
return vsp.StartPos;
}
void Viewer::Close()
{
AssertCurrentViewer();
Info.ViewerControl(_id, VCTL_QUIT, 0, 0);
}
void Viewer::Redraw()
{
AssertCurrentViewer();
Info.ViewerControl(_id, VCTL_REDRAW, 0, 0);
}
void Viewer::SelectText(Int64 symbolStart, int symbolCount)
{
AssertCurrentViewer();
if (symbolCount <= 0)
{
Info.ViewerControl(_id, VCTL_SELECT, 0, 0);
}
else
{
ViewerSelect vs = {sizeof(vs)};
vs.BlockLen = symbolCount;
vs.BlockStartPos = symbolStart;
Info.ViewerControl(_id, VCTL_SELECT, 0, &vs);
}
}
void Viewer::AssertClosed()
{
if (IsOpened) throw gcnew InvalidOperationException("Viewer must not be open for this operation.");
}
ViewerViewMode Viewer::ViewMode::get()
{
ViewerInfo vi; ViewerControl_VCTL_GETINFO(vi, true);
if (vi.ViewerID < 0 || vi.ViewerID != _id)
return ViewerViewMode::Text;
else
return (ViewerViewMode)vi.CurMode.ViewMode;
}
void Viewer::ViewMode::set(ViewerViewMode value)
{
AssertCurrentViewer();
ViewerSetMode vsm = {sizeof(vsm)};
vsm.Flags = 0;
vsm.Type = VSMT_VIEWMODE;
vsm.iParam = (intptr_t)value;
Info.ViewerControl(_id, VCTL_SETMODE, 0, &vsm);
}
bool Viewer::WrapMode::get()
{
ViewerInfo vi; ViewerControl_VCTL_GETINFO(vi, true);
if (vi.ViewerID < 0 || vi.ViewerID != _id)
return false;
else
return (vi.CurMode.Flags & VMF_WRAP) != 0;
}
void Viewer::WrapMode::set(bool value)
{
AssertCurrentViewer();
ViewerSetMode vsm = {sizeof(vsm)};
vsm.Flags = 0;
vsm.Type = VSMT_WRAP;
vsm.iParam = value;
Info.ViewerControl(_id, VCTL_SETMODE, 0, &vsm);
}
bool Viewer::WordWrapMode::get()
{
ViewerInfo vi; ViewerControl_VCTL_GETINFO(vi, true);
if (vi.ViewerID < 0 || vi.ViewerID != _id)
return false;
else
return (vi.CurMode.Flags & VMF_WORDWRAP) != 0;
}
void Viewer::WordWrapMode::set(bool value)
{
AssertCurrentViewer();
ViewerSetMode vsm = {sizeof(vsm)};
vsm.Flags = 0;
vsm.Type = VSMT_WORDWRAP;
vsm.iParam = value;
Info.ViewerControl(_id, VCTL_SETMODE, 0, &vsm);
}
int Viewer::CodePage::get()
{
if (!IsOpened)
return (int)_CodePage;
ViewerInfo vi; ViewerControl_VCTL_GETINFO(vi, true);
if (vi.ViewerID < 0 || vi.ViewerID != _id)
return 0;
return (int)vi.CurMode.CodePage;
}
void Viewer::CodePage::set(int value)
{
AssertClosed();
_CodePage = value;
}
DateTime Viewer::TimeOfOpen::get()
{
return _TimeOfOpen;
}
void Viewer::Activate()
{
int nWindow = Far::Api->Window->Count;
for(int i = 0; i < nWindow; ++i)
{
WindowKind kind = Far::Api->Window->GetKindAt(i);
if (kind != WindowKind::Viewer)
continue;
String^ name = Far::Api->Window->GetNameAt(i);
if (name == _FileName)
{
Far::Api->Window->SetCurrentAt(i);
return;
}
}
throw gcnew InvalidOperationException("Cannot find the window by name.");
}
}
| [
"[email protected]"
] | |
20d072f7f9fb831fd36de16254df2b5ebfaa2075 | 9b6eced5d80668bd4328a8f3d1f75c97f04f5e08 | /bthci/bthci2/CommandsEvents/interface/remotehostsupportedfeaturesnotificationevent.h | 270cefd4ad99dc4fcffbaeff0ce6958c4fd03f40 | [] | no_license | SymbianSource/oss.FCL.sf.os.bt | 3ca94a01740ac84a6a35718ad3063884ea885738 | ba9e7d24a7fa29d6dd93808867c28bffa2206bae | refs/heads/master | 2021-01-18T23:42:06.315016 | 2010-10-14T10:30:12 | 2010-10-14T10:30:12 | 72,765,157 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,812 | h | // Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// This file was generated automatically from the template eventheader.tmpl
// on Thu, 29 May 2008 15:23:56 (time stamp)
//
//
/**
@file
@publishedPartner
@released
*/
#ifndef REMOTEHOSTSUPPORTEDFEATURESNOTIFICATIONEVENT_H
#define REMOTEHOSTSUPPORTEDFEATURESNOTIFICATIONEVENT_H
#include <bluetooth/hci/event.h>
/**
This class represents the RemoteHostSupportedFeaturesNotification HCI Event
*/
class TRemoteHostSupportedFeaturesNotificationEvent : public THCIEventBase
{
public:
// Construct an event object to wrap existing event data received from the Controller
IMPORT_C TRemoteHostSupportedFeaturesNotificationEvent(const TDesC8& aEventData);
// Construct a faked event, storing the supplied event parameters into the supplied empty event data buffer.
IMPORT_C TRemoteHostSupportedFeaturesNotificationEvent(const TBTDevAddr& aBDADDR, TUint64 aHostSupportedFeatures, TDes8& aEventData);
// Destructor
IMPORT_C ~TRemoteHostSupportedFeaturesNotificationEvent();
// The static Cast method is used to obtain a pointer to the derived class object
IMPORT_C static TRemoteHostSupportedFeaturesNotificationEvent& Cast(const THCIEventBase& aEvent);
// Accessor methods for the parameters of the event
IMPORT_C TBTDevAddr BDADDR() const;
IMPORT_C TUint64 HostSupportedFeatures() const;
};
#endif // REMOTEHOSTSUPPORTEDFEATURESNOTIFICATIONEVENT_H
| [
"[email protected]"
] | |
8b1c77872331499bad45f019b14936717ee867ba | 6749b543df5be8d93a8c95ed308054ce31daa0ff | /include/common/cfg.h | 3b607fa108e0c33b044dfa4e85cfe8be28d44d7b | [] | no_license | yutiansut/release_model | f2d6766a23a925d99345e0741df88e6953a70e74 | bbf0aa02346df52baba3b431454884bb99cce3a9 | refs/heads/master | 2023-05-09T03:00:11.784598 | 2021-05-28T01:27:21 | 2021-05-28T01:27:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,380 | h | #pragma once
#include "simpleini/SimpleIni.h"
#include <common/util.h>
namespace husky {
struct dynamic_pattern {
virtual ~dynamic_pattern() {};
virtual bool is_pattern(const char* v, int len) = 0;
virtual std::string convert() = 0;
};
struct yyyyMMdd_pattern : public dynamic_pattern {
~yyyyMMdd_pattern() override {};
bool is_pattern(const char* v, int len) override {
return strncmp("yyyyMMdd", v, len) == 0;
}
std::string convert() override {
return husky::local_time_format();
}
};
struct dn_pattern : public dynamic_pattern {
~dn_pattern() override {};
bool is_pattern(const char* v, int len) override {
return strncmp("dn", v, len) == 0;
}
std::string convert() override {
return husky::dn() == husky::DAY ? "day" : "night";
}
};
class cfg {
private:
std::vector<dynamic_pattern*> pattern_collection;
public:
~cfg() {
for (auto* ptr : pattern_collection) {
delete ptr;
}
}
cfg(const std::string &path): _file_path(path) {
_ini.SetUnicode();
SI_Error rc = _ini.LoadFile(path.c_str());
if (rc < 0) {
throw std::invalid_argument("parse " + path + " error");
};
pattern_collection.push_back(new yyyyMMdd_pattern());
pattern_collection.push_back(new dn_pattern());
}
void reload() {
_ini.Reset();
_ini.LoadFile(_file_path.c_str());
}
template<typename N>
std::vector<N> get_vector(const std::string& key, char delim = ',') {
std::vector<N> result;
for (const auto& s: husky::split_by(get_string(key), delim))
result.push_back(parseStr<N>(s));
return result;
}
const char* get(const std::string& key) const {
const auto& temp = husky::split_by(key, '.');
if (temp.size() > 2 || temp.size() == 0) {
throw std::invalid_argument("cfg key " + key + " error");
}
if (temp.size() == 1) {
return _ini.GetValue("", key.c_str());
} else {
return _ini.GetValue(temp[0].c_str(), temp[1].c_str());
}
}
const std::string get_string(const std::string& key, std::string v = "") const {
const char* val = this->get(key);
return val == nullptr ? v : val;
}
int get_int(const std::string& key, int v = 0) const {
const char* val = this->get(key);
return val == nullptr ? v : std::stoi(val);
}
unsigned long get_unsigned_long(const std::string& key, int v = 0) const {
const char* val = this->get(key);
return val == nullptr ? v : std::stoul(val);
}
float get_float(const std::string& key, float v = 0) const {
const char* val = this->get(key);
return val == nullptr ? v : std::stof(val);
}
bool get_bool(const std::string& key, bool v = false) {
const char* val = this->get(key);
return val == nullptr ? v : (strcmp(val, "true") == 0 ? true : false);
}
double get_double(const std::string& key, double v = 0) {
const char* val = this->get(key);
return val == nullptr ? v : std::stod(val);
}
std::string parse_dynamic(std::string str) {
for (unsigned int i = 0; i < str.size();) {
char s_type = str[i];
if (s_type == '#' || s_type == '$') {
int replace_begin = i;
i += 2;
std::vector<char> temp;
while (str[i] != '}') {
temp.push_back(str[i]);
++i;
}
temp.push_back('\0');
if (s_type == '$') {
std::string env_replacement = std::getenv(temp.data());
str = str.replace(str.begin() + replace_begin,
str.begin() + replace_begin + temp.size() + 2,
env_replacement);
i = replace_begin + env_replacement.length();
} else { // '#'
for (dynamic_pattern *pattern: pattern_collection) {
if (pattern->is_pattern(temp.data(), temp.size())) {
std::string replacement = pattern->convert();
str = str.replace(str.begin() + replace_begin,
str.begin() + replace_begin + temp.size() + 2,
replacement);
i = replace_begin + replacement.length();
break;
}
}
}
temp.clear();
} else {
++i;
}
}
return str;
}
private:
CSimpleIniA _ini;
std::string _file_path;
};
} | [
"[email protected]"
] | |
bc4c8fe5afc8f1c32ccc1eb748f4710bb4fe9df5 | 8f6f2f1c105b106f8b1b8309bb59630f5a166f05 | /course/course_1_1_1_hello_window.cpp | fd4b2e2cc1fb19ef417c5146eba52d279ba14694 | [] | no_license | lyl12345/LearnOpenGLQt | 230024ce813d512c72001401220fb1d66e8fbd15 | 7b1f7a62b8ed10de4c541ae8a3db4605f2fb5d54 | refs/heads/master | 2022-12-05T08:23:52.313521 | 2020-08-18T12:44:49 | 2020-08-18T12:44:49 | 276,817,848 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 364 | cpp | #include "course_1_1_1_hello_window.h"
Course_1_1_1_hello_window::Course_1_1_1_hello_window()
{
initializeOpenGLFunctions();
}
void Course_1_1_1_hello_window::render()
{
glClear(GL_COLOR_BUFFER_BIT);
}
QList<QtProperty *> Course_1_1_1_hello_window::getPropertyList(QtVariantPropertyManager *manager)
{
GETPROPERTYLIST(Course_1_1_1_hello_window)
}
| [
"[email protected]"
] | |
bdd4bc25d9677770b1b9c04960a1fbd2d8d64bf8 | 662b5b2d0a675245e5dff8e092e2a36fa98ea7d2 | /gdl90_2_g496.ino | ce52f7c910ef7b52b1fad7ebeef37f1a7e43499c | [] | no_license | rocketbob/gdl90_2_g496 | 879c6add6c74870797cd575734a50cc7664e4105 | fb70f813bcfe787d1cc532b9c0acf1ef6253cf54 | refs/heads/master | 2021-09-29T00:36:29.213098 | 2021-09-23T14:50:22 | 2021-09-23T14:50:22 | 206,821,713 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,036 | ino | #include <WiFi.h>
#include <WiFiUDP.h>
#include <HardwareSerial.h>
unsigned int UDPPort = 4000; // local port to listen on
const int bufferSize = 450;
byte packetBuffer[bufferSize]; //buffer to hold incoming packet
byte messageBuffer[bufferSize];
const int wifiSelectPin = 4;
const int trafficAudioPin = 13; //traffic audio output trip pin
int trafficAudioTimer = millis();
bool trafficAudioState = false;
const int maxTargets = 8;
const int warnAltitude = 9; //warning altitude in 100ft (9)
const byte warnDistance = 16; // warning distance in 1/8's of miles (16)
const int warnMinAltitude = 1; //min warning altitude in 100ft to avoid ownships warnings
const byte warnMinDistance = 4; //min warn distance in 1/8's of miles
float maxTrafficDistance = 30; //max display distance in nm (20)
int maxTrafficAltitude = 50; //max display altitude difference in 100's of feet (40)
int tPersist = 30000; //traffic persist in milliseconds
float mLat = 40.128464; // My position variables
float mLon = -86.228897;
int mAltitude = 930;
int mGS = 50;
int tStatus = 0; // Traffic variables
int tAddressType = 0;
int tAddress = 0;
float tLat = 0;
float tLon = 0;
int tAltitude = 0;
int tAltitudeDelta = 0;
int tVertVelocity = 0;
int tHeading = 0;
int tTimestamp[maxTargets] = { 0,0,0,0,0,0,0,0 };
int tICAO[maxTargets] = { 0,0,0,0,0,0,0,0 };
int tIcon[maxTargets] = { 0,0,0,0,0,0,0,0 };
byte tClimb[maxTargets] = { 0,0,0,0,0,0,0,0 };
int tDir[maxTargets] = { 0,0,0,0,0,0,0,0 };
int tHundredsAltitude[maxTargets] = { 0,0,0,0,0,0,0,0 };
byte tByteDistance[maxTargets] = { 0,0,0,0,0,0,0,0 };
float tDistance = 0;
byte tNumberOf = 0;
byte tWriteNumber = 0;
int timer = 0;
byte checksum = 0;
int myICAO = 0xA8E6E0; // drew address
//int myICAO = 0xA0835D; // test
WiFiUDP Udp;
HardwareSerial HwSerial1(1);
void setup() {
pinMode(trafficAudioPin, OUTPUT);
digitalWrite(trafficAudioPin, LOW);
delay(100);
digitalWrite(trafficAudioPin, HIGH);
timer = millis();
HwSerial1.begin(9600); // Serial port to Garmin 396/496 (pin D4 on NodeMCU)
Serial.begin(115200); // Debug serial port (usb on NodeMCU)
pinMode(wifiSelectPin, INPUT);
if (digitalRead(wifiSelectPin) == LOW) {
WiFi.begin("stratux"); // ADS-B SSID
Serial.println();
Serial.println("Stratux");
maxTrafficDistance = 30; // set max distance and alt longer for bench testing (30)
maxTrafficAltitude = 490; //(490)
}
else {
//WiFi.begin("Ping-4D6F"); //Drew
WiFi.begin("Ping-EA8D"); //Tom
Serial.println();
Serial.println("Ping");
}
Serial.println();
Serial.print("Wait for WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: " + WiFi.localIP().toString());
Udp.begin(UDPPort);
}
float calculateDegrees(int highByte, int midByte, int lowByte) {
int position = 0;
float xx;
position = highByte;
position <<= 8;
position |= midByte;
position <<= 8;
position |= lowByte;
position &= 0xFFFFFFFF;
if ((position & 0x800000) != 0) {
int yy;
position |= 0xFF000000;
yy = (int)position;
xx = (float)(yy);
}
else {
xx = (position & 0x7FFFFF);
}
xx *= 2.1457672E-5;
return xx;
}
float findTrafficDirection(float latD, float lonD) { // convert pythag angle to bearing
//Serial.print(" findTdir");
if (latD == 0 && lonD == 0) {
float result = 0;
return result;
}
if (latD == 0 && lonD > 0) {
float result = 90;
return result;
}
if (latD == 0 && lonD < 0) {
float result = 270;
return result;
}
if (lonD == 0 && latD > 0) {
float result = 0;
return result;
}
if (lonD == 0 && latD < 0) {
float result = 180;
return result;
}
if (latD > 0 && lonD > 0) {
//if (abs(latD) == 0) latD = .001;
float result = 180 / PI * (atan(lonD / latD));
return result;
}
if (latD < 0 && lonD > 0) {
//if (abs(lonD) == 0) lonD = .001;
float result = (180 / PI * (atan((lonD) / (latD)))) + 180;
return result;
}
if (latD < 0 && lonD < 0) {
//if (abs(latD) == 0) latD = .001;
float result = (180 / PI * (atan((lonD) / (latD)))) + 180;
return result;
}
if (latD > 0 && lonD < 0) {
//if (abs(lonD) == 0) lonD = .001;
float result = (180 / PI * (atan(lonD / (latD)))) + 360;
/*
Serial.print(" ");
Serial.print("atan");
Serial.print(" ");
Serial.print(atan(latD/abs(lonD)));
Serial.print(" ");
*/
return result;
}
}
void writeByte(byte byteInput) {
HwSerial1.write(byteInput);
checksum = checksum + byteInput;
if (byteInput == 0x10) {
HwSerial1.write(0x10); //Duplicate the byte if same as DLE - not in checksum
}
}
void writeInt(int intInput) { //Split int into two bytes
byte low = intInput;
byte high = intInput >> 8;
writeByte(low);
writeByte(high);
}
void sendNOTIS() {
checksum = 0; //Reset checksum
HwSerial1.write(0x10); //DLE - not in checksum
writeByte(0x8C); //Message ID
writeByte(0x08); //Data length
writeByte(0x04); //?
writeByte(0x00); //?
writeByte(0x00); //3F for traffic not available
writeByte(0x00); //?
writeInt(0); //Compass heading (degrees)
writeByte(0x00); //?3f
writeByte(0x00); //?
HwSerial1.write(-checksum); //Checksum
HwSerial1.write(0x10); //DLE - not in checksum
HwSerial1.write(0x03); //ETX - not in checksum
//Serial.println("NOTIS");
}
void sendTIS() {
checksum = 0; //Reset checksum
if (tNumberOf == 0) {
sendNOTIS();
}
else {
HwSerial1.write(0x10); //DLE - not in checksum
writeByte(0x8C); //Message ID
writeByte(8 + (8 * tNumberOf)); //Data length
writeByte(0x04); //?
writeByte(0x00); //?
writeByte(tNumberOf); //Number of targets
writeByte(0x00); //?
writeInt(0); //Compass heading (degrees) when sending relative bearing traffic
writeByte(0x00); //?
writeByte(0x00); //?
for (int t = 0; t < tNumberOf; t++) {
if (tByteDistance[t] <= warnDistance && tHundredsAltitude[t] <= warnAltitude) { //Set traffic warning if within warn dist and altitude
if (tByteDistance[t] >= warnMinDistance && tHundredsAltitude[t] >= warnMinAltitude && mGS >= 20) {
writeByte(0x01);
triggerTrafficAudioOut();
}
else {
writeByte(0x00);
}
}
else {
writeByte(0x00); //Traffic 00=normal 01=alert 02=normal?
}
writeByte(tClimb[t]); //Traffic vertical direction 0=level 1=climbing 2=descending
writeByte(tIcon[t]); //Traffic icon heading 0=N 1=NE 2=E 3=SE 4=S 5=SW 6=W 7=NW 8=NONE? 9=NONE
writeByte(tByteDistance[t]); //Traffic distance (nm*8)
writeInt(tDir[t]); //Traffic azimuth (degrees)
writeInt(tHundredsAltitude[t]); //Traffic altitude (feet/100)
}
/*
writeByte(0x00); //Traffic 00=normal 01=alert 02=normal?
writeByte(0x01); //Traffic vertical direction 0=level 1=climbing 2=descending
writeByte(0x09); //Traffic icon heading 0=N 1=NE 2=E 3=SE 4=S 5=SW 6=W 7=NW 8=NONE? 9=NONE
writeByte(0x10); //Traffic distance (nm*8)
writeInt(0); //Traffic azimuth (degrees)
writeInt(25); //Traffic altitude (feet/100)
*/
HwSerial1.write(-checksum); //Checksum
HwSerial1.write(0x10); //DLE - not in checksum
HwSerial1.write(0x03); //ETX - not in checksum
}
}
void clearLastTraffic() {
Serial.println(" clrLast");
tIcon[tNumberOf] = 0; // clear data from ignored traffic
tClimb[tNumberOf] = 0;
tDir[tNumberOf] = 0;
tHundredsAltitude[tNumberOf] = 0;
tByteDistance[tNumberOf] = 0;
tNumberOf--;
}
void triggerTrafficAudioOut() {
if (trafficAudioState == false && millis() > (trafficAudioTimer + (10 * 1000))) {
digitalWrite(trafficAudioPin, LOW);
trafficAudioState = true;
//Serial.print("audio");
}
}
void trafficAudioOut() {
if (millis() > (trafficAudioTimer + 500 + (10 * 1000))) {
digitalWrite(trafficAudioPin, HIGH);
trafficAudioState = false;
trafficAudioTimer = millis();
}
}
void loop() {
trafficAudioOut();
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, bufferSize);
if (len > 0) {
packetBuffer[len] = 0;
}
int m = 0;
for (int i = 0; i < len; i++) { // Unpack buffer. Remove extra bytes.
if (packetBuffer[i] == 0x7D) { // escape control character
i++; // look at next character
if (packetBuffer[i] == 0x5E) { // this is 0x7E ^ 0x20, which is an escaped 0x7E
messageBuffer[m] = 0x7E;
//Serial.print("Replaced "); Serial.print(packetBuffer[i], HEX); Serial.print(" with "); Serial.println(messageBuffer[m], HEX);
}
else if (packetBuffer[i] == 0x5D) { // this is 0x7D ^ 0x20, which is an escaped 0x7D
messageBuffer[m] = 0x7D;
//Serial.print("Replaced "); Serial.print(packetBuffer[i], HEX); Serial.print(" with "); Serial.println(messageBuffer[m], HEX);
}
}
else { // all OTHER characters
messageBuffer[m] = packetBuffer[i]; // copy unescaped characters
}
m++;
}
len = m; // this is the new length of the message with escape symbols (0x7D) removed
/*// Print hex values--------------------------------------------
for (int j = 0; j < len; j++) {
Serial.print(" ");
if (messageBuffer[j] < 0x10) { Serial.print("0"); }
Serial.print(messageBuffer[j], HEX);
}
Serial.println("");
//*/
for (int j = 0; j < len; j++) {
if (messageBuffer[j] == 0x7E) { // Watch for DLE
switch (messageBuffer[j + 1]) {
case 10: { //ownship message
// Lat Lon
mLat = calculateDegrees((int)(messageBuffer[j + 6] & 0xFF), (int)(messageBuffer[j + 7] & 0xFF), (int)(messageBuffer[j + 8] & 0xFF));
mLon = calculateDegrees((int)(messageBuffer[j + 9] & 0xFF), (int)(messageBuffer[j + 10] & 0xFF), (int)(messageBuffer[j + 11] & 0xFF));
// Altitude
int upper = (((int)messageBuffer[j + 12]) & 0xFF) << 4;
int lower = (((int)messageBuffer[j + 13]) & 0xF0) >> 4;
mAltitude = upper + lower;
mAltitude *= 25;
mAltitude -= 1000;
// Groundspeed
int uppergs = ((int)messageBuffer[j + 15] & 0xFF) << 4;
int lowergs = ((int)messageBuffer[j + 16] & 0xF0) >> 4;
mGS = uppergs + lowergs;
if (digitalRead(wifiSelectPin) == LOW) {// to simulate GPS and baro alt during bench testing
mLat = 40.128464;
mLon = -86.228897;
mAltitude = 930;
mGS = 50;
}
j = j + 31;
//**
Serial.print("M ");
Serial.print(mLat, 6);
Serial.print(" ");
Serial.print(mLon, 6);
Serial.print(" ");
Serial.print(mAltitude);
Serial.print(" ");
Serial.print(mGS);
Serial.println("");
//**
break;
}
case 20: { // Traffic message
//if (tNumberOf >= maxTargets) { tNumberOf--; }
// Alert status
tStatus = (messageBuffer[j + 2] & 0xF0) >> 4; // Alert status is meaningless in Stratux. Must determine traffic status on our own.
// Address
tAddressType = (int)(messageBuffer[j + 2] & 0x0F);
tAddress = ((((int)messageBuffer[j + 3]) & 0xFF) << 16) + ((((int)(messageBuffer[j + 4]) & 0xFF) << 8)) + ((((int)messageBuffer[j + 5]) & 0xFF));
// Lat Lon
tLat = calculateDegrees((int)(messageBuffer[j + 6] & 0xFF), (int)(messageBuffer[j + 7] & 0xFF), (int)(messageBuffer[j + 8] & 0xFF)); // Parse Lat/Lon in degrees
tLon = calculateDegrees((int)(messageBuffer[j + 9] & 0xFF), (int)(messageBuffer[j + 10] & 0xFF), (int)(messageBuffer[j + 11] & 0xFF));
float tLatDelta = ((tLat - mLat) * 60); // Lat distance (nm)
float tLonDelta = ((tLon - mLon) * 60) * cos(mLat / 360 * 2 * PI); // Lon distance (nm)
tDistance = sqrt(abs(tLonDelta * tLonDelta) + abs(tLatDelta * tLatDelta)); // Calculate pythag distance
// Altitude
int upper = (((int)messageBuffer[j + 12]) & 0xFF) << 4;
int lower = (((int)messageBuffer[j + 13]) & 0xF0) >> 4;
tAltitude = upper + lower;
tAltitude *= 25;
tAltitude -= 1000;
tAltitudeDelta = tAltitude - mAltitude; // Calculate relative altitude of traffic
// Vertical velocity
int upperb = ((int)messageBuffer[j + 16] & 0x0F) << 8;
int lowerb = (int)messageBuffer[j + 17] & 0xFF;
tVertVelocity = (upperb | lowerb);
// Heading
tHeading = (((int)messageBuffer[j + 18] & 0xFF)) * 360 / 256;
// ignore distance traffic
if (tDistance > maxTrafficDistance || (tAltitudeDelta / 100) > maxTrafficAltitude || (tAltitudeDelta / 100) < maxTrafficAltitude * -1 || ((byte)((int)tDistance * 8) < warnMinDistance && (tAltitudeDelta / 100) < warnMinAltitude)) {
//tNumberOf++;
Serial.println("");
Serial.println("deleted");
break;
}
// check for my ICAO address
if (tAddress == myICAO) {
Serial.println("");
Serial.println("deleted my ICAO");
break;
}
// check for duplicate icao address
bool overWrite = false;
for (int i = 0; i < tNumberOf; i++) {
if (tAddress == tICAO[i]) {
overWrite = true;
tWriteNumber = i;
}
}
// if display full then overwrite more distant traffic
if (tNumberOf >= maxTargets && overWrite == false) {
byte tMostDistant = 0;
int tMostDistantNumber = 0;
for (int i = 0; i < tNumberOf; i++) {
if (tByteDistance[i] > tMostDistant) {
tMostDistant = tByteDistance[i];
tMostDistantNumber = i;
}
}
if (((byte)((int)tDistance * 8)) <= tMostDistant) {
overWrite = true;
tWriteNumber = tMostDistantNumber;
}
else {
break;
}
}
if (overWrite == false) {
tWriteNumber = tNumberOf;
}
// write data into arrays
tICAO[tWriteNumber] = tAddress;
tByteDistance[tWriteNumber] = (byte)((int)tDistance * 8); //Convert miles to 1/8th miles
tDir[tWriteNumber] = (int)(findTrafficDirection(tLatDelta, tLonDelta));
tHundredsAltitude[tWriteNumber] = tAltitudeDelta / 100; //Convert feet into 100's of feet
if (tVertVelocity >= 3 && tVertVelocity <= 510) { tClimb[tWriteNumber] = 1; } // Convert vert velocity to climb/descent arrow byte
if (tVertVelocity >= 3586 && tVertVelocity <= 4093) { tClimb[tWriteNumber] = 2; }
if (tVertVelocity < 3) { tClimb[tWriteNumber] = 0; }
if (tVertVelocity > 4093) { tClimb[tWriteNumber] = 0; }
if ((((messageBuffer[j + 18] + 16) / 32) & 0x0F) == 8) { // Constrain tHeading to 1 nibble
tIcon[tWriteNumber] = (((messageBuffer[j + 18] + 16) / 32) & 0x0F) - 8;
}
else {
tIcon[tWriteNumber] = (((messageBuffer[j + 18] + 16) / 32) & 0x0F);
}
tTimestamp[tWriteNumber] = millis();
j = j + 31;
Serial.print("T ");
Serial.print(tStatus);
Serial.print(" ");
Serial.print(tAddressType);
Serial.print(" ");
Serial.print(tAddress, HEX);
Serial.print(" ");
Serial.print(tLat, 6);
Serial.print(" ");
Serial.print(tLon, 6);
Serial.print(" ");
Serial.print(tAltitude);
Serial.print("ft ");
//Serial.println("");
Serial.print(" ");
Serial.print(tLatDelta);
Serial.print(" ");
Serial.print(tLonDelta);
Serial.print(" ");
Serial.print("");
/*Serial.print(tLatDelta);
Serial.print(" ");
Serial.print(tLonDelta);
Serial.print(" ");*/
//Serial.print(tStatus);
//Serial.print(" ");
Serial.print(tDistance, 1);
Serial.print("nm ");
//Serial.print(tByteDistance[tNumberOf], HEX);
//Serial.print("-8s ");
Serial.print(tDir[tWriteNumber]);
Serial.print("deg ");
Serial.print(tAltitudeDelta / 100);
Serial.print("00ft ");
Serial.print(tClimb[tWriteNumber]);
Serial.print(" ");
Serial.print(tHeading);
Serial.print("deg ");
Serial.print(tIcon[tWriteNumber]);
Serial.print("dir ");
Serial.print(tTimestamp[tWriteNumber]);
Serial.println(" ");
if (overWrite == false) {
tNumberOf++;
}
//if (tNumberOf > maxTargets) { tNumberOf--; }
break;
}
}
}
}
}
if ((millis() - timer) > 1000) { // send traffic every second
sendTIS();
timer = millis(); // reset timer from last traffic transmission
Serial.println("");
//Serial.println("");
Serial.print("sending ");
Serial.println(tNumberOf);
/*
Serial.println("");
Serial.print(tLat);
Serial.print(" ");
Serial.println(tLon);
Serial.print(mLat);
Serial.print(" ");
Serial.println(mLon);
*/
//tNumberOf = 0;
int tempNum = tNumberOf;
for (int i = 0; i < tempNum; i++) { // clear old traffic data
Serial.print(tTimestamp[i]);
Serial.print(" ");
if (millis() >= (tTimestamp[i] + tPersist)) { // is traffic record over 30 sec old?
if (i == tNumberOf && tNumberOf != 0) { // is expired traffic the last record?
tICAO[i] = 0;
tIcon[i] = 0;
tClimb[i] = 0;
tDir[i] = 0;
tHundredsAltitude[i] = 0;
tByteDistance[i] = 0;
tTimestamp[i] = 0;
tNumberOf--;
}
if (i == tNumberOf && tNumberOf == 0) { // clear 0th record
tICAO[i] = 0;
tIcon[i] = 0;
tClimb[i] = 0;
tDir[i] = 0;
tHundredsAltitude[i] = 0;
tByteDistance[i] = 0;
tTimestamp[i] = 0;
}
if (i != tNumberOf && tNumberOf != 0) {
tICAO[i] = tICAO[tNumberOf - 1];
tIcon[i] = tIcon[tNumberOf - 1]; // copy info from last traffic record to current one
tClimb[i] = tClimb[tNumberOf - 1];
tDir[i] = tDir[tNumberOf - 1];
tHundredsAltitude[i] = tHundredsAltitude[tNumberOf - 1];
tByteDistance[i] = tByteDistance[tNumberOf - 1];
tTimestamp[i] = tTimestamp[tNumberOf - 1];
tICAO[tNumberOf - 1] = 0;
tIcon[tNumberOf - 1] = 0; // delete last traffic record
tClimb[tNumberOf - 1] = 0;
tDir[tNumberOf - 1] = 0;
tHundredsAltitude[tNumberOf - 1] = 0;
tByteDistance[tNumberOf - 1] = 0;
tTimestamp[tNumberOf - 1] = 0;
tNumberOf--;
}
}
}
Serial.println(" ");
}
} | [
"[email protected]"
] | |
6c56f8cffe3311dd41d35d146feade0169b55b39 | 4b9f86bc750d1159394d9c46be92805bcbc32b4c | /libbpe/simple.cpp | a1363d81c3b325f5119e96050ff264ed3cec3a6e | [] | no_license | nilehmann/RePair-WaveletTree-Graph | a3e700c12d58eb10cd7c5b061d37172f976b0690 | 4f7b47e260b62ee57a7dbb392ccd9257c8ea9455 | refs/heads/master | 2016-09-05T09:00:31.192972 | 2013-09-08T18:04:10 | 2013-09-08T18:04:10 | 12,629,112 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 468 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/times.h>
#include <iostream>
#include <sstream>
#include "bpe.h"
//double ticks = 100.0;
using namespace std;
bool manual = false;
int main (int argc, char **argv)
{
int p[] = {0x035F, 0xFF00};
ulong *p2 = new ulong[2];
p2[0] = p[0];
p2[1] = p[1];
BPE *bpe = new BPE(p2,128 , true,-2,64);//DV
fprintf(stderr,"%d\n", bpe->rank1(1));
}
| [
"[email protected]"
] | |
6482bc4f203a033575ae780ecc8c5391d595bc1d | 26c11fcbc96b144acd07372b45ea4fab29bf231e | /mediadecoder/src/main/cpp/audiodecoder-jni.cpp | 322dcf625f0a0dcc3b97b803659563a31c72d547 | [] | no_license | Office-Murtaza/MVYShortVideoEditorAndroidPublic | cb281ee199adabd7503fb465ceedec50c0e4ecc5 | dff78af64d374775bdc1b71325740a04984057a8 | refs/heads/master | 2023-08-22T01:39:41.580718 | 2021-10-08T22:25:02 | 2021-10-08T22:25:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,413 | cpp | #pragma clang diagnostic ignored"-Wdeprecated-declarations"
#include <jni.h>
#include <string>
#include <sys/param.h>
#include <vector>
#include <android/log.h>
#include <sstream>
#ifdef __cplusplus
extern "C" {
#endif
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
static const char *TAG = "AudioDecoder";
namespace MVY{
// 音频帧数据
typedef struct {
double pts;
double duration;
double length;
int sampleRate;
int channels;
uint8_t *buffer;
size_t bufferSize;
} AudioFrame;
// 错误枚举
typedef enum {
MovieErrorNone,
MovieErrorOpenFile,
MovieErrorStreamInfoNotFound,
MovieErrorStreamNotFound,
MovieErrorCodecNotFound,
MovieErrorOpenCodec,
MovieErrorAllocateFrame,
MovieErrorReSampler,
} MovieError;
typedef struct AudioDecoder {
// 解码器
AVCodecContext *mvyCodecContext;
// 视频流ID
int mvyAudioStream;
// 视频帧
AVFrame *mvyAudioFrame;
// 重采样器
SwrContext *swrContext;
// 重采样器 buffer
uint8_t *swrBuffer;
// 重采样器 buffer大小
size_t swrBufferSize;
// 输出采样率
int outputSampleRate;
// 通道数
int outputChannels;
// 文件格式
AVFormatContext *mvyFormatContext;
// eos 标记
int eos;
// 没有更多帧可读
int no_decoded_frame;
// 内部错误
int internal_error;
} AudioDecoder;
}
using MVY::AudioDecoder;
using MVY::AudioFrame;
// 创建对象
static AudioDecoder* initAudioDecoder() {
AudioDecoder *audioDecoder = (AudioDecoder *)malloc(sizeof(AudioDecoder));
memset(audioDecoder, 0, sizeof(AudioDecoder));
audioDecoder->outputSampleRate = 16000;
audioDecoder->outputChannels = 1;
audioDecoder->swrBufferSize = 4096;
audioDecoder->swrBuffer = static_cast<uint8_t *>(realloc(audioDecoder->swrBuffer, audioDecoder->swrBufferSize));
return audioDecoder;
}
// 销毁对象
static void deinitAudioDecoder(AudioDecoder* audioDecoder) {
if (audioDecoder->swrBuffer) {
free(audioDecoder->swrBuffer);
audioDecoder->swrBuffer = NULL;
audioDecoder->swrBufferSize = 0;
}
free(audioDecoder);
}
// 打开文件
static MVY::MovieError openFile(AudioDecoder* audioDecoder, const char *path, const char *fileName) {
AVFormatContext *formatCtx = NULL;
int result = avformat_open_input(&formatCtx, path, NULL, NULL);
if (result < 0) {
if (formatCtx) {
avformat_free_context(formatCtx);
}
std::ostringstream ss;
ss << "MVY::MovieErrorOpenFile ";
ss << result;
ss << " ";
ss << path;
__android_log_write(ANDROID_LOG_ERROR, TAG, ss.str().data());
return MVY::MovieErrorOpenFile;
}
if (avformat_find_stream_info(formatCtx, NULL) < 0) {
avformat_close_input(&formatCtx);
__android_log_write(ANDROID_LOG_ERROR, TAG, "MVY::MovieErrorStreamInfoNotFound");
return MVY::MovieErrorStreamInfoNotFound;
}
av_dump_format(formatCtx, 0, fileName, false);
audioDecoder->mvyFormatContext = formatCtx;
return MVY::MovieErrorNone;
}
// 打开音频流
static MVY::MovieError openAudioStream(AudioDecoder* audioDecoder) {
MVY::MovieError errCode = MVY::MovieErrorStreamNotFound;
audioDecoder->mvyAudioStream = -1;
for (int i=0; i<audioDecoder->mvyFormatContext->nb_streams; ++i) {
if (AVMEDIA_TYPE_AUDIO == audioDecoder->mvyFormatContext->streams[i]->codec->codec_type) {
AVCodecContext *codecCtx = audioDecoder->mvyFormatContext->streams[i]->codec;
SwrContext *swrContext = NULL;
AVCodec *codec = avcodec_find_decoder(codecCtx->codec_id);
if (!codec) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "MVY::MovieErrorCodecNotFound");
errCode = MVY::MovieErrorCodecNotFound;
continue;
}
codecCtx->thread_count = 4;
codecCtx->thread_type = FF_THREAD_FRAME;
if (avcodec_open2(codecCtx, codec, NULL) < 0) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "MVY::MovieErrorOpenCodec");
errCode = MVY::MovieErrorOpenCodec;
avcodec_close(codecCtx);
continue;
}
swrContext = swr_alloc_set_opts(
NULL,
av_get_default_channel_layout(audioDecoder->outputChannels),
AV_SAMPLE_FMT_S16,
audioDecoder->outputSampleRate,
av_get_default_channel_layout(codecCtx->channels),
codecCtx->sample_fmt,
codecCtx->sample_rate,
0,
NULL);
if (!swrContext || swr_init(swrContext)) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "MVY::MovieErrorReSampler");
if (swrContext) {
swr_free(&swrContext);
}
avcodec_close(codecCtx);
errCode = MVY::MovieErrorReSampler;
continue;
}
audioDecoder->mvyAudioFrame = av_frame_alloc();
if (!audioDecoder->mvyAudioFrame) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "MVY::MovieErrorAllocateFrame");
if (swrContext) {
swr_free(&swrContext);
}
avcodec_close(codecCtx);
errCode = MVY::MovieErrorAllocateFrame;
continue;
}
audioDecoder->mvyAudioStream = i;
audioDecoder->mvyCodecContext = codecCtx;
audioDecoder->swrContext = swrContext;
errCode = MVY::MovieErrorNone;
break;
}
}
return errCode;
}
static void clearStatus(AudioDecoder *videoDecoder){
__android_log_print(ANDROID_LOG_ERROR, TAG, "Clear decoder status\n");
videoDecoder->eos = 0;
videoDecoder->internal_error = 0;
videoDecoder->no_decoded_frame = 0;
}
// 关闭视频流
static void closeAudioStream(AudioDecoder* audioDecoder) {
if (audioDecoder->swrContext) {
swr_free(&audioDecoder->swrContext);
audioDecoder->swrContext = NULL;
}
audioDecoder->mvyAudioStream = -1;
clearStatus(audioDecoder);
if (audioDecoder->mvyAudioFrame) {
av_free(audioDecoder->mvyAudioFrame);
audioDecoder->mvyAudioFrame = NULL;
}
if (audioDecoder->mvyCodecContext) {
avcodec_close(audioDecoder->mvyCodecContext);
audioDecoder->mvyCodecContext = NULL;
}
}
// 关闭文件
static void closeFile(AudioDecoder* audioDecoder) {
audioDecoder->mvyAudioStream = NULL;
if (audioDecoder->mvyFormatContext) {
avformat_close_input(&(audioDecoder->mvyFormatContext));
audioDecoder->mvyFormatContext = NULL;
}
}
// 解码一帧视频
static std::vector<AudioFrame> decodeAFrame(AudioDecoder* audioDecoder) {
std::vector<AudioFrame> result;
if (audioDecoder->mvyAudioStream == -1) {
return result;
}
AVPacket packet;
if(audioDecoder->internal_error == 1) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "Unexpected, decoder has error, should stop now\n");
return result;
}
if(audioDecoder->no_decoded_frame){
__android_log_write(ANDROID_LOG_ERROR, TAG, "No more audio decoded frame\n");
return result;
}
while(true) {
if(audioDecoder->eos == 0) {
auto code = av_read_frame(audioDecoder->mvyFormatContext, &packet);
if (code < 0) {
if (code == AVERROR_EOF) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "prepare empty packet to notify decoder, set eos flags\n");
packet.data = NULL;
packet.size = 0;
audioDecoder->eos = 1;
} else {
// some other errors
__android_log_write(ANDROID_LOG_ERROR, TAG, "Encount some other error");
audioDecoder->internal_error = 1;
return result;
}
} else if(packet.stream_index != audioDecoder->mvyAudioStream) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "Keep reading\n");
av_free_packet(&packet);
continue;
}
} else {
__android_log_write(ANDROID_LOG_ERROR, TAG, "Flush the decoded frame\n");
packet.data = NULL;
packet.size = 0;
}
int gotFrame = 0;
avcodec_decode_audio4(audioDecoder->mvyCodecContext, audioDecoder->mvyAudioFrame, &gotFrame,
&packet);
double timeBase = av_q2d(audioDecoder->mvyFormatContext->streams[audioDecoder->mvyAudioStream]->time_base);
double audioDuration = audioDecoder->mvyFormatContext->streams[audioDecoder->mvyAudioStream]->duration * timeBase * 1000;
if (gotFrame) {
int numFrames;
// 转换采样数据
numFrames = swr_convert(
audioDecoder->swrContext,
&(audioDecoder->swrBuffer),
(int)audioDecoder->swrBufferSize,
(const uint8_t **)audioDecoder->mvyAudioFrame->data,
audioDecoder->mvyAudioFrame->nb_samples);
if (numFrames < 0) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "fail resample audio");
break;
}
const int bufSize = av_samples_get_buffer_size(
NULL,
audioDecoder->outputChannels,
numFrames,
AV_SAMPLE_FMT_S16,
1);
if (bufSize < 0) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "fail resample audio");
break;
}
// 数据返回
AudioFrame frame;
frame.pts = av_frame_get_best_effort_timestamp(audioDecoder->mvyAudioFrame) * timeBase * 1000;
frame.duration = av_frame_get_pkt_duration(audioDecoder->mvyAudioFrame) * timeBase * 1000;
frame.length = audioDuration;
frame.sampleRate = audioDecoder->outputSampleRate;
frame.channels = audioDecoder->outputChannels;
frame.buffer = audioDecoder->swrBuffer;
frame.bufferSize = (size_t) bufSize;
std::ostringstream ss;
ss << " pts : " << frame.pts;
ss << " duration : " << frame.duration;
ss << " length : " << frame.length;
ss << " sampleRate : " << frame.sampleRate;
ss << " channels : " << frame.channels;
ss << " bufferSize : " << frame.bufferSize;
__android_log_write(ANDROID_LOG_ERROR, TAG, ss.str().data());
result.push_back(frame);
break;
} else {
__android_log_write(ANDROID_LOG_ERROR, TAG, "did not get video, read next packet\n");
if (audioDecoder->eos) {
__android_log_write(ANDROID_LOG_ERROR, TAG, "no frames in decoder\n");
audioDecoder->no_decoded_frame = 1;
break;
}
}
}
if(packet.data != NULL)
av_free_packet(&packet);
return result;
}
// 跳转到前一个I帧
static void forwardSeekTo(AudioDecoder* audioDecoder, double millisecond) {
if (audioDecoder->mvyAudioStream != -1) {
double timeBase = av_q2d(audioDecoder->mvyFormatContext->streams[audioDecoder->mvyAudioStream]->time_base);
int64_t ts = (int64_t)(millisecond / 1000.f / timeBase);
av_seek_frame(audioDecoder->mvyFormatContext, audioDecoder->mvyAudioStream, ts, 0);
avcodec_flush_buffers(audioDecoder->mvyCodecContext);
clearStatus(audioDecoder);
}
}
// 跳转到后一个I帧
static void backwardSeekTo(AudioDecoder* audioDecoder, double millisecond) {
if (audioDecoder->mvyAudioStream != -1) {
double timeBase = av_q2d(audioDecoder->mvyFormatContext->streams[audioDecoder->mvyAudioStream]->time_base);
int64_t ts = (int64_t)(millisecond / 1000.f / timeBase);
av_seek_frame(audioDecoder->mvyFormatContext, audioDecoder->mvyAudioStream, ts, AVSEEK_FLAG_BACKWARD);
avcodec_flush_buffers(audioDecoder->mvyCodecContext);
clearStatus(audioDecoder);
}
}
static double getAudioLength(AudioDecoder* audioDecoder) {
if (audioDecoder->mvyAudioStream != -1) {
double timeBase = av_q2d(audioDecoder->mvyFormatContext->streams[audioDecoder->mvyAudioStream]->time_base);
double videoDuration = audioDecoder->mvyFormatContext->streams[audioDecoder->mvyAudioStream]->duration * timeBase * 1000;
return videoDuration;
} else {
return 0;
}
}
JNIEXPORT void JNICALL
Java_com_myvideoyun_decoder_AudioDecoder_registerFFmpeg(JNIEnv *env, jobject instance_) {
av_register_all();
}
JNIEXPORT jint JNICALL
Java_com_myvideoyun_decoder_AudioDecoder_initAudioDecoder(JNIEnv *env, jobject instance) {
return reinterpret_cast<jint>(initAudioDecoder());
}
JNIEXPORT void JNICALL
Java_com_myvideoyun_decoder_AudioDecoder_deinitAudioDecoder(JNIEnv *env, jobject instance_, jint instance) {
if (instance) {
AudioDecoder *audioDecoder = reinterpret_cast<AudioDecoder *>(instance);
deinitAudioDecoder(audioDecoder);
}
}
JNIEXPORT jboolean JNICALL
Java_com_myvideoyun_decoder_AudioDecoder_openFile(JNIEnv *env, jobject instance_, jint instance, jstring path_, jstring fileName_) {
const char *path = env->GetStringUTFChars(path_, 0);
const char *fileName = env->GetStringUTFChars(fileName_, 0);
if (instance) {
AudioDecoder *audioDecoder = reinterpret_cast<AudioDecoder *>(instance);
MVY::MovieError errCode = openFile(audioDecoder, path, fileName);
if (errCode == MVY::MovieErrorNone) {
errCode = openAudioStream(audioDecoder);
if (errCode != MVY::MovieErrorNone) {
closeAudioStream(audioDecoder);
closeFile(audioDecoder);
env->ReleaseStringUTFChars(path_, path);
env->ReleaseStringUTFChars(fileName_, fileName);
return JNI_FALSE;
}
} else {
closeFile(audioDecoder);
env->ReleaseStringUTFChars(path_, path);
env->ReleaseStringUTFChars(fileName_, fileName);
return JNI_FALSE;
}
}
env->ReleaseStringUTFChars(path_, path);
env->ReleaseStringUTFChars(fileName_, fileName);
return JNI_TRUE;
}
JNIEXPORT jobjectArray JNICALL
Java_com_myvideoyun_decoder_AudioDecoder_decodeAFrame(JNIEnv *env, jobject instance_, jint instance) {
AudioDecoder *audioDecoder = reinterpret_cast<AudioDecoder *>(instance);
jclass audioFrameClass = env->FindClass("com/myvideoyun/decoder/AudioFrame");
jmethodID stringMethodInitId = env->GetMethodID(audioFrameClass, "<init>", "()V");
jfieldID ptsField = env->GetFieldID(audioFrameClass, "pts", "D");
jfieldID durationField = env->GetFieldID(audioFrameClass, "duration", "D");
jfieldID lengthField = env->GetFieldID(audioFrameClass, "length", "D");
jfieldID sampleRateField = env->GetFieldID(audioFrameClass, "sampleRate", "I");
jfieldID channelsField = env->GetFieldID(audioFrameClass, "channels", "I");
jfieldID bufferField = env->GetFieldID(audioFrameClass, "buffer", "[B");
jfieldID bufferSizeField = env->GetFieldID(audioFrameClass, "bufferSize", "I");
int index = 0;
std::vector<AudioFrame> frames = decodeAFrame(audioDecoder);
jobjectArray objectArray = env->NewObjectArray(frames.size(), audioFrameClass, NULL);
for (auto frame : frames) {
jobject audioFrame = env->NewObject(audioFrameClass, stringMethodInitId);
env->SetDoubleField(audioFrame, ptsField, frame.pts);
env->SetDoubleField(audioFrame, durationField, frame.duration);
env->SetDoubleField(audioFrame, lengthField, frame.length);
env->SetIntField(audioFrame, sampleRateField, static_cast<jint>(frame.sampleRate));
env->SetIntField(audioFrame, channelsField, static_cast<jint>(frame.channels));
{
jbyteArray byteArray = env->NewByteArray(frame.bufferSize);
jbyte *bytes = env->GetByteArrayElements(byteArray, NULL);
memcpy(bytes, frame.buffer, frame.bufferSize);
env->SetByteArrayRegion(byteArray, 0, frame.bufferSize, bytes);
env->SetObjectField(audioFrame, bufferField, byteArray);
}
env->SetIntField(audioFrame, bufferSizeField, static_cast<jint>(frame.bufferSize));
env->SetObjectArrayElement(objectArray, index, audioFrame);
++index;
}
return objectArray;
}
JNIEXPORT void JNICALL
Java_com_myvideoyun_decoder_AudioDecoder_forwardSeekTo(JNIEnv *env, jobject instance_, jint instance, jdouble millisecond) {
if (instance) {
AudioDecoder *audioDecoder = reinterpret_cast<AudioDecoder *>(instance);
forwardSeekTo(audioDecoder, millisecond);
}
}
JNIEXPORT void JNICALL
Java_com_myvideoyun_decoder_AudioDecoder_backwardSeekTo(JNIEnv *env, jobject instance_, jint instance, jdouble millisecond) {
if (instance) {
AudioDecoder *audioDecoder = reinterpret_cast<AudioDecoder *>(instance);
backwardSeekTo(audioDecoder, millisecond);
}
}
JNIEXPORT jdouble JNICALL
Java_com_myvideoyun_decoder_AudioDecoder_getAudioLength(JNIEnv *env, jobject instance_, jint instance) {
if (instance) {
AudioDecoder *videoDecoder = reinterpret_cast<AudioDecoder *>(instance);
return getAudioLength(videoDecoder);
} else {
return 0;
}
}
JNIEXPORT void JNICALL
Java_com_myvideoyun_decoder_AudioDecoder_closeFile(JNIEnv *env, jobject instance_, jint instance) {
if (instance) {
AudioDecoder *audioDecoder = reinterpret_cast<AudioDecoder *>(instance);
closeAudioStream(audioDecoder);
closeFile(audioDecoder);
}
}
#ifdef __cplusplus
}
#endif
| [
"[email protected]"
] | |
9af9347dfd5b2f237d09816e73e2a5aaa40b1a35 | c51febc209233a9160f41913d895415704d2391f | /library/ATF/_qry_sheet_insertRegister.hpp | 962a6fde68ea71dca33a6f5437d7d4d1c15e6d47 | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 694 | hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_qry_sheet_insertDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Register
{
class _qry_sheet_insertRegister : public IRegister
{
public:
void Register() override
{
auto& hook_core = CATFCore::get_instance();
for (auto& r : Detail::_qry_sheet_insert_functions)
hook_core.reg_wrapper(r.pBind, r);
}
};
}; // end namespace Register
END_ATF_NAMESPACE
| [
"[email protected]"
] | |
31088514c8e1921b2e98613b843d256a8b243995 | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_1/Z6.2+poll+dmb.sy+poal.c.cbmc_out.cpp | 450650f0be1aee7a25ad89eb43c334125e5291e1 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 42,125 | cpp | // 0:vars:3
// 3:atom_1_X0_1:1
// 4:atom_2_X0_1:1
// 5:thr0:1
// 6:thr1:1
// 7:thr2:1
#define ADDRSIZE 8
#define NPROC 4
#define NCONTEXT 1
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NPROC*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NPROC*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NPROC*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NPROC*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NPROC*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NPROC*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NPROC*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NPROC*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NPROC*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NPROC];
int cdy[NPROC];
int cds[NPROC];
int cdl[NPROC];
int cisb[NPROC];
int caddr[NPROC];
int cctrl[NPROC];
int cstart[NPROC];
int creturn[NPROC];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
int r0= 0;
char creg_r0;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
int r6= 0;
char creg_r6;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
int r10= 0;
char creg_r10;
int r11= 0;
char creg_r11;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
buff(0,6) = 0;
pw(0,6) = 0;
cr(0,6) = 0;
iw(0,6) = 0;
cw(0,6) = 0;
cx(0,6) = 0;
is(0,6) = 0;
cs(0,6) = 0;
crmax(0,6) = 0;
buff(0,7) = 0;
pw(0,7) = 0;
cr(0,7) = 0;
iw(0,7) = 0;
cw(0,7) = 0;
cx(0,7) = 0;
is(0,7) = 0;
cs(0,7) = 0;
crmax(0,7) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
buff(1,6) = 0;
pw(1,6) = 0;
cr(1,6) = 0;
iw(1,6) = 0;
cw(1,6) = 0;
cx(1,6) = 0;
is(1,6) = 0;
cs(1,6) = 0;
crmax(1,6) = 0;
buff(1,7) = 0;
pw(1,7) = 0;
cr(1,7) = 0;
iw(1,7) = 0;
cw(1,7) = 0;
cx(1,7) = 0;
is(1,7) = 0;
cs(1,7) = 0;
crmax(1,7) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
buff(2,6) = 0;
pw(2,6) = 0;
cr(2,6) = 0;
iw(2,6) = 0;
cw(2,6) = 0;
cx(2,6) = 0;
is(2,6) = 0;
cs(2,6) = 0;
crmax(2,6) = 0;
buff(2,7) = 0;
pw(2,7) = 0;
cr(2,7) = 0;
iw(2,7) = 0;
cw(2,7) = 0;
cx(2,7) = 0;
is(2,7) = 0;
cs(2,7) = 0;
crmax(2,7) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
buff(3,4) = 0;
pw(3,4) = 0;
cr(3,4) = 0;
iw(3,4) = 0;
cw(3,4) = 0;
cx(3,4) = 0;
is(3,4) = 0;
cs(3,4) = 0;
crmax(3,4) = 0;
buff(3,5) = 0;
pw(3,5) = 0;
cr(3,5) = 0;
iw(3,5) = 0;
cw(3,5) = 0;
cx(3,5) = 0;
is(3,5) = 0;
cs(3,5) = 0;
crmax(3,5) = 0;
buff(3,6) = 0;
pw(3,6) = 0;
cr(3,6) = 0;
iw(3,6) = 0;
cw(3,6) = 0;
cx(3,6) = 0;
is(3,6) = 0;
cs(3,6) = 0;
crmax(3,6) = 0;
buff(3,7) = 0;
pw(3,7) = 0;
cr(3,7) = 0;
iw(3,7) = 0;
cw(3,7) = 0;
cx(3,7) = 0;
is(3,7) = 0;
cs(3,7) = 0;
crmax(3,7) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
mem(6+0,0) = 0;
mem(7+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
co(1,0) = 0;
delta(1,0) = -1;
co(2,0) = 0;
delta(2,0) = -1;
co(3,0) = 0;
delta(3,0) = -1;
co(4,0) = 0;
delta(4,0) = -1;
co(5,0) = 0;
delta(5,0) = -1;
co(6,0) = 0;
delta(6,0) = -1;
co(7,0) = 0;
delta(7,0) = -1;
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !35, metadata !DIExpression()), !dbg !44
// br label %label_1, !dbg !45
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !43), !dbg !46
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !36, metadata !DIExpression()), !dbg !47
// call void @llvm.dbg.value(metadata i64 2, metadata !39, metadata !DIExpression()), !dbg !47
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !48
// ST: Guess
// : Release
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
ASSUME(cw(1,0) >= cr(1,0+0));
ASSUME(cw(1,0) >= cr(1,0+1));
ASSUME(cw(1,0) >= cr(1,0+2));
ASSUME(cw(1,0) >= cr(1,3+0));
ASSUME(cw(1,0) >= cr(1,4+0));
ASSUME(cw(1,0) >= cr(1,5+0));
ASSUME(cw(1,0) >= cr(1,6+0));
ASSUME(cw(1,0) >= cr(1,7+0));
ASSUME(cw(1,0) >= cw(1,0+0));
ASSUME(cw(1,0) >= cw(1,0+1));
ASSUME(cw(1,0) >= cw(1,0+2));
ASSUME(cw(1,0) >= cw(1,3+0));
ASSUME(cw(1,0) >= cw(1,4+0));
ASSUME(cw(1,0) >= cw(1,5+0));
ASSUME(cw(1,0) >= cw(1,6+0));
ASSUME(cw(1,0) >= cw(1,7+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 2;
mem(0,cw(1,0)) = 2;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
is(1,0) = iw(1,0);
cs(1,0) = cw(1,0);
ASSUME(creturn[1] >= cw(1,0));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !40, metadata !DIExpression()), !dbg !49
// call void @llvm.dbg.value(metadata i64 1, metadata !42, metadata !DIExpression()), !dbg !49
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !50
// ST: Guess
// : Release
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
ASSUME(cw(1,0+1*1) >= cr(1,0+0));
ASSUME(cw(1,0+1*1) >= cr(1,0+1));
ASSUME(cw(1,0+1*1) >= cr(1,0+2));
ASSUME(cw(1,0+1*1) >= cr(1,3+0));
ASSUME(cw(1,0+1*1) >= cr(1,4+0));
ASSUME(cw(1,0+1*1) >= cr(1,5+0));
ASSUME(cw(1,0+1*1) >= cr(1,6+0));
ASSUME(cw(1,0+1*1) >= cr(1,7+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+1));
ASSUME(cw(1,0+1*1) >= cw(1,0+2));
ASSUME(cw(1,0+1*1) >= cw(1,3+0));
ASSUME(cw(1,0+1*1) >= cw(1,4+0));
ASSUME(cw(1,0+1*1) >= cw(1,5+0));
ASSUME(cw(1,0+1*1) >= cw(1,6+0));
ASSUME(cw(1,0+1*1) >= cw(1,7+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
is(1,0+1*1) = iw(1,0+1*1);
cs(1,0+1*1) = cw(1,0+1*1);
ASSUME(creturn[1] >= cw(1,0+1*1));
// ret i8* null, !dbg !51
ret_thread_1 = (- 1);
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !54, metadata !DIExpression()), !dbg !68
// br label %label_2, !dbg !51
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !67), !dbg !70
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !57, metadata !DIExpression()), !dbg !71
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !54
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r0 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r0 = buff(2,0+1*1);
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r0 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !59, metadata !DIExpression()), !dbg !71
// %conv = trunc i64 %0 to i32, !dbg !55
// call void @llvm.dbg.value(metadata i32 %conv, metadata !55, metadata !DIExpression()), !dbg !68
// call void (...) @dmbsy(), !dbg !56
// dumbsy: Guess
old_cdy = cdy[2];
cdy[2] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[2] >= old_cdy);
ASSUME(cdy[2] >= cisb[2]);
ASSUME(cdy[2] >= cdl[2]);
ASSUME(cdy[2] >= cds[2]);
ASSUME(cdy[2] >= cctrl[2]);
ASSUME(cdy[2] >= cw(2,0+0));
ASSUME(cdy[2] >= cw(2,0+1));
ASSUME(cdy[2] >= cw(2,0+2));
ASSUME(cdy[2] >= cw(2,3+0));
ASSUME(cdy[2] >= cw(2,4+0));
ASSUME(cdy[2] >= cw(2,5+0));
ASSUME(cdy[2] >= cw(2,6+0));
ASSUME(cdy[2] >= cw(2,7+0));
ASSUME(cdy[2] >= cr(2,0+0));
ASSUME(cdy[2] >= cr(2,0+1));
ASSUME(cdy[2] >= cr(2,0+2));
ASSUME(cdy[2] >= cr(2,3+0));
ASSUME(cdy[2] >= cr(2,4+0));
ASSUME(cdy[2] >= cr(2,5+0));
ASSUME(cdy[2] >= cr(2,6+0));
ASSUME(cdy[2] >= cr(2,7+0));
ASSUME(creturn[2] >= cdy[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !60, metadata !DIExpression()), !dbg !75
// call void @llvm.dbg.value(metadata i64 1, metadata !62, metadata !DIExpression()), !dbg !75
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !58
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = 1;
mem(0+2*1,cw(2,0+2*1)) = 1;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// %cmp = icmp eq i32 %conv, 1, !dbg !59
// %conv1 = zext i1 %cmp to i32, !dbg !59
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !63, metadata !DIExpression()), !dbg !68
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !64, metadata !DIExpression()), !dbg !78
// %1 = zext i32 %conv1 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !66, metadata !DIExpression()), !dbg !78
// store atomic i64 %1, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !61
// ST: Guess
iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW
old_cw = cw(2,3);
cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM
// Check
ASSUME(active[iw(2,3)] == 2);
ASSUME(active[cw(2,3)] == 2);
ASSUME(sforbid(3,cw(2,3))== 0);
ASSUME(iw(2,3) >= max(creg_r0,0));
ASSUME(iw(2,3) >= 0);
ASSUME(cw(2,3) >= iw(2,3));
ASSUME(cw(2,3) >= old_cw);
ASSUME(cw(2,3) >= cr(2,3));
ASSUME(cw(2,3) >= cl[2]);
ASSUME(cw(2,3) >= cisb[2]);
ASSUME(cw(2,3) >= cdy[2]);
ASSUME(cw(2,3) >= cdl[2]);
ASSUME(cw(2,3) >= cds[2]);
ASSUME(cw(2,3) >= cctrl[2]);
ASSUME(cw(2,3) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,3) = (r0==1);
mem(3,cw(2,3)) = (r0==1);
co(3,cw(2,3))+=1;
delta(3,cw(2,3)) = -1;
ASSUME(creturn[2] >= cw(2,3));
// ret i8* null, !dbg !62
ret_thread_2 = (- 1);
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !83, metadata !DIExpression()), !dbg !96
// br label %label_3, !dbg !51
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !95), !dbg !98
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !85, metadata !DIExpression()), !dbg !99
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) acquire, align 8, !dbg !54
// LD: Guess
// : Acquire
old_cr = cr(3,0+2*1);
cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM
// Check
ASSUME(active[cr(3,0+2*1)] == 3);
ASSUME(cr(3,0+2*1) >= iw(3,0+2*1));
ASSUME(cr(3,0+2*1) >= 0);
ASSUME(cr(3,0+2*1) >= cdy[3]);
ASSUME(cr(3,0+2*1) >= cisb[3]);
ASSUME(cr(3,0+2*1) >= cdl[3]);
ASSUME(cr(3,0+2*1) >= cl[3]);
ASSUME(cr(3,0+2*1) >= cx(3,0+2*1));
ASSUME(cr(3,0+2*1) >= cs(3,0+0));
ASSUME(cr(3,0+2*1) >= cs(3,0+1));
ASSUME(cr(3,0+2*1) >= cs(3,0+2));
ASSUME(cr(3,0+2*1) >= cs(3,3+0));
ASSUME(cr(3,0+2*1) >= cs(3,4+0));
ASSUME(cr(3,0+2*1) >= cs(3,5+0));
ASSUME(cr(3,0+2*1) >= cs(3,6+0));
ASSUME(cr(3,0+2*1) >= cs(3,7+0));
// Update
creg_r1 = cr(3,0+2*1);
crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1));
caddr[3] = max(caddr[3],0);
if(cr(3,0+2*1) < cw(3,0+2*1)) {
r1 = buff(3,0+2*1);
} else {
if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) {
ASSUME(cr(3,0+2*1) >= old_cr);
}
pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1));
r1 = mem(0+2*1,cr(3,0+2*1));
}
cl[3] = max(cl[3],cr(3,0+2*1));
ASSUME(creturn[3] >= cr(3,0+2*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !87, metadata !DIExpression()), !dbg !99
// %conv = trunc i64 %0 to i32, !dbg !55
// call void @llvm.dbg.value(metadata i32 %conv, metadata !84, metadata !DIExpression()), !dbg !96
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !88, metadata !DIExpression()), !dbg !102
// call void @llvm.dbg.value(metadata i64 1, metadata !90, metadata !DIExpression()), !dbg !102
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !57
// ST: Guess
// : Release
iw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,0);
cw(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,0)] == 3);
ASSUME(active[cw(3,0)] == 3);
ASSUME(sforbid(0,cw(3,0))== 0);
ASSUME(iw(3,0) >= 0);
ASSUME(iw(3,0) >= 0);
ASSUME(cw(3,0) >= iw(3,0));
ASSUME(cw(3,0) >= old_cw);
ASSUME(cw(3,0) >= cr(3,0));
ASSUME(cw(3,0) >= cl[3]);
ASSUME(cw(3,0) >= cisb[3]);
ASSUME(cw(3,0) >= cdy[3]);
ASSUME(cw(3,0) >= cdl[3]);
ASSUME(cw(3,0) >= cds[3]);
ASSUME(cw(3,0) >= cctrl[3]);
ASSUME(cw(3,0) >= caddr[3]);
ASSUME(cw(3,0) >= cr(3,0+0));
ASSUME(cw(3,0) >= cr(3,0+1));
ASSUME(cw(3,0) >= cr(3,0+2));
ASSUME(cw(3,0) >= cr(3,3+0));
ASSUME(cw(3,0) >= cr(3,4+0));
ASSUME(cw(3,0) >= cr(3,5+0));
ASSUME(cw(3,0) >= cr(3,6+0));
ASSUME(cw(3,0) >= cr(3,7+0));
ASSUME(cw(3,0) >= cw(3,0+0));
ASSUME(cw(3,0) >= cw(3,0+1));
ASSUME(cw(3,0) >= cw(3,0+2));
ASSUME(cw(3,0) >= cw(3,3+0));
ASSUME(cw(3,0) >= cw(3,4+0));
ASSUME(cw(3,0) >= cw(3,5+0));
ASSUME(cw(3,0) >= cw(3,6+0));
ASSUME(cw(3,0) >= cw(3,7+0));
// Update
caddr[3] = max(caddr[3],0);
buff(3,0) = 1;
mem(0,cw(3,0)) = 1;
co(0,cw(3,0))+=1;
delta(0,cw(3,0)) = -1;
is(3,0) = iw(3,0);
cs(3,0) = cw(3,0);
ASSUME(creturn[3] >= cw(3,0));
// %cmp = icmp eq i32 %conv, 1, !dbg !58
// %conv1 = zext i1 %cmp to i32, !dbg !58
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !91, metadata !DIExpression()), !dbg !96
// call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !92, metadata !DIExpression()), !dbg !105
// %1 = zext i32 %conv1 to i64
// call void @llvm.dbg.value(metadata i64 %1, metadata !94, metadata !DIExpression()), !dbg !105
// store atomic i64 %1, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !60
// ST: Guess
iw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW
old_cw = cw(3,4);
cw(3,4) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM
// Check
ASSUME(active[iw(3,4)] == 3);
ASSUME(active[cw(3,4)] == 3);
ASSUME(sforbid(4,cw(3,4))== 0);
ASSUME(iw(3,4) >= max(creg_r1,0));
ASSUME(iw(3,4) >= 0);
ASSUME(cw(3,4) >= iw(3,4));
ASSUME(cw(3,4) >= old_cw);
ASSUME(cw(3,4) >= cr(3,4));
ASSUME(cw(3,4) >= cl[3]);
ASSUME(cw(3,4) >= cisb[3]);
ASSUME(cw(3,4) >= cdy[3]);
ASSUME(cw(3,4) >= cdl[3]);
ASSUME(cw(3,4) >= cds[3]);
ASSUME(cw(3,4) >= cctrl[3]);
ASSUME(cw(3,4) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,4) = (r1==1);
mem(4,cw(3,4)) = (r1==1);
co(4,cw(3,4))+=1;
delta(4,cw(3,4)) = -1;
ASSUME(creturn[3] >= cw(3,4));
// ret i8* null, !dbg !61
ret_thread_3 = (- 1);
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !115, metadata !DIExpression()), !dbg !153
// call void @llvm.dbg.value(metadata i8** %argv, metadata !116, metadata !DIExpression()), !dbg !153
// %0 = bitcast i64* %thr0 to i8*, !dbg !79
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !79
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !117, metadata !DIExpression()), !dbg !155
// %1 = bitcast i64* %thr1 to i8*, !dbg !81
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !81
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !121, metadata !DIExpression()), !dbg !157
// %2 = bitcast i64* %thr2 to i8*, !dbg !83
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !83
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !122, metadata !DIExpression()), !dbg !159
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !123, metadata !DIExpression()), !dbg !160
// call void @llvm.dbg.value(metadata i64 0, metadata !125, metadata !DIExpression()), !dbg !160
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !86
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !126, metadata !DIExpression()), !dbg !162
// call void @llvm.dbg.value(metadata i64 0, metadata !128, metadata !DIExpression()), !dbg !162
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !88
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !129, metadata !DIExpression()), !dbg !164
// call void @llvm.dbg.value(metadata i64 0, metadata !131, metadata !DIExpression()), !dbg !164
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !90
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !132, metadata !DIExpression()), !dbg !166
// call void @llvm.dbg.value(metadata i64 0, metadata !134, metadata !DIExpression()), !dbg !166
// store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !92
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !135, metadata !DIExpression()), !dbg !168
// call void @llvm.dbg.value(metadata i64 0, metadata !137, metadata !DIExpression()), !dbg !168
// store atomic i64 0, i64* @atom_2_X0_1 monotonic, align 8, !dbg !94
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !95
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call9 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !96
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call10 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !97
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !98, !tbaa !99
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r3 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r3 = buff(0,5);
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r3 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// %call11 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !103
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !104, !tbaa !99
// LD: Guess
old_cr = cr(0,6);
cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,6)] == 0);
ASSUME(cr(0,6) >= iw(0,6));
ASSUME(cr(0,6) >= 0);
ASSUME(cr(0,6) >= cdy[0]);
ASSUME(cr(0,6) >= cisb[0]);
ASSUME(cr(0,6) >= cdl[0]);
ASSUME(cr(0,6) >= cl[0]);
// Update
creg_r4 = cr(0,6);
crmax(0,6) = max(crmax(0,6),cr(0,6));
caddr[0] = max(caddr[0],0);
if(cr(0,6) < cw(0,6)) {
r4 = buff(0,6);
} else {
if(pw(0,6) != co(6,cr(0,6))) {
ASSUME(cr(0,6) >= old_cr);
}
pw(0,6) = co(6,cr(0,6));
r4 = mem(6,cr(0,6));
}
ASSUME(creturn[0] >= cr(0,6));
// %call12 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !105
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !106, !tbaa !99
// LD: Guess
old_cr = cr(0,7);
cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,7)] == 0);
ASSUME(cr(0,7) >= iw(0,7));
ASSUME(cr(0,7) >= 0);
ASSUME(cr(0,7) >= cdy[0]);
ASSUME(cr(0,7) >= cisb[0]);
ASSUME(cr(0,7) >= cdl[0]);
ASSUME(cr(0,7) >= cl[0]);
// Update
creg_r5 = cr(0,7);
crmax(0,7) = max(crmax(0,7),cr(0,7));
caddr[0] = max(caddr[0],0);
if(cr(0,7) < cw(0,7)) {
r5 = buff(0,7);
} else {
if(pw(0,7) != co(7,cr(0,7))) {
ASSUME(cr(0,7) >= old_cr);
}
pw(0,7) = co(7,cr(0,7));
r5 = mem(7,cr(0,7));
}
ASSUME(creturn[0] >= cr(0,7));
// %call13 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !107
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cw(0,6+0));
ASSUME(cdy[0] >= cw(0,7+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(cdy[0] >= cr(0,6+0));
ASSUME(cdy[0] >= cr(0,7+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !139, metadata !DIExpression()), !dbg !183
// %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !109
// LD: Guess
old_cr = cr(0,0);
cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,0)] == 0);
ASSUME(cr(0,0) >= iw(0,0));
ASSUME(cr(0,0) >= 0);
ASSUME(cr(0,0) >= cdy[0]);
ASSUME(cr(0,0) >= cisb[0]);
ASSUME(cr(0,0) >= cdl[0]);
ASSUME(cr(0,0) >= cl[0]);
// Update
creg_r6 = cr(0,0);
crmax(0,0) = max(crmax(0,0),cr(0,0));
caddr[0] = max(caddr[0],0);
if(cr(0,0) < cw(0,0)) {
r6 = buff(0,0);
} else {
if(pw(0,0) != co(0,cr(0,0))) {
ASSUME(cr(0,0) >= old_cr);
}
pw(0,0) = co(0,cr(0,0));
r6 = mem(0,cr(0,0));
}
ASSUME(creturn[0] >= cr(0,0));
// call void @llvm.dbg.value(metadata i64 %6, metadata !141, metadata !DIExpression()), !dbg !183
// %conv = trunc i64 %6 to i32, !dbg !110
// call void @llvm.dbg.value(metadata i32 %conv, metadata !138, metadata !DIExpression()), !dbg !153
// %cmp = icmp eq i32 %conv, 2, !dbg !111
// %conv14 = zext i1 %cmp to i32, !dbg !111
// call void @llvm.dbg.value(metadata i32 %conv14, metadata !142, metadata !DIExpression()), !dbg !153
// call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !144, metadata !DIExpression()), !dbg !187
// %7 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !113
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r7 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r7 = buff(0,3);
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r7 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i64 %7, metadata !146, metadata !DIExpression()), !dbg !187
// %conv18 = trunc i64 %7 to i32, !dbg !114
// call void @llvm.dbg.value(metadata i32 %conv18, metadata !143, metadata !DIExpression()), !dbg !153
// call void @llvm.dbg.value(metadata i64* @atom_2_X0_1, metadata !148, metadata !DIExpression()), !dbg !190
// %8 = load atomic i64, i64* @atom_2_X0_1 seq_cst, align 8, !dbg !116
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r8 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r8 = buff(0,4);
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r8 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i64 %8, metadata !150, metadata !DIExpression()), !dbg !190
// %conv22 = trunc i64 %8 to i32, !dbg !117
// call void @llvm.dbg.value(metadata i32 %conv22, metadata !147, metadata !DIExpression()), !dbg !153
// %and = and i32 %conv18, %conv22, !dbg !118
creg_r9 = max(creg_r7,creg_r8);
ASSUME(active[creg_r9] == 0);
r9 = r7 & r8;
// call void @llvm.dbg.value(metadata i32 %and, metadata !151, metadata !DIExpression()), !dbg !153
// %and23 = and i32 %conv14, %and, !dbg !119
creg_r10 = max(max(creg_r6,0),creg_r9);
ASSUME(active[creg_r10] == 0);
r10 = (r6==2) & r9;
// call void @llvm.dbg.value(metadata i32 %and23, metadata !152, metadata !DIExpression()), !dbg !153
// %cmp24 = icmp eq i32 %and23, 1, !dbg !120
// br i1 %cmp24, label %if.then, label %if.end, !dbg !122
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg_r10);
ASSUME(cctrl[0] >= 0);
if((r10==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([106 x i8], [106 x i8]* @.str.1, i64 0, i64 0), i32 noundef 69, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !123
// unreachable, !dbg !123
r11 = 1;
T0BLOCK2:
// %9 = bitcast i64* %thr2 to i8*, !dbg !126
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !126
// %10 = bitcast i64* %thr1 to i8*, !dbg !126
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !126
// %11 = bitcast i64* %thr0 to i8*, !dbg !126
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !126
// ret i32 0, !dbg !127
ret_thread_0 = 0;
ASSERT(r11== 0);
}
| [
"[email protected]"
] | |
7a533e1b252b05b7ab671106899679550661f7f4 | b59f7dba0cee8d1f94b3d7a8b2f71333df77744d | /Classes/module/ActModule.cpp | 7a36ba1ca52cf3ab103242a8678995099844357a | [] | no_license | akaza03/Fighter | d210f0f15170f511ec27245c6aa3535d351c58c1 | 19dce5d8ee84461db77085bd186d7568a60b1c43 | refs/heads/master | 2022-11-28T11:44:32.958355 | 2020-08-05T04:05:41 | 2020-08-05T04:05:41 | 262,900,165 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 470 | cpp | #include "unit/Character.h"
#include "ActModule.h"
void ActModule::operator()(cocos2d::Sprite & sp, ActData & act)
{
// 移動処理
Move()(sp, act);
// 敵が死亡時の吹き飛び処理
Blow()(sp, act);
// 攻撃
Attack()(sp, act);
// 向きの更新
DirCheck()(sp, act);
// アニメーションの更新
AnimUpdate()(sp, act);
// 当たり判定
DamageCheck()(sp, act);
// 移動
SetPos()(sp, act);
// キーの更新
OldKeyUpdate()(sp, act);
}
| [
"[email protected]"
] | |
11bb2a5d25fc0ade6e57c95c8bfc175b66b6d787 | aca810f6dd683a8c4069dff0e9705e7db19fbcca | /validSudoku.cpp | f88fe77cddca7bdb1fd98ae6cc4d8b7d0f65826f | [] | no_license | okeashwin/General | 4c3c6333e5ba343230eb78deb1a510cb168b1731 | 9df41c2cfa4895b944c29eb13de03295bba69758 | refs/heads/master | 2021-01-10T05:50:07.721347 | 2017-09-27T02:31:50 | 2017-09-27T02:31:50 | 44,040,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,132 | cpp | class Solution {
private:
inline void clear(vector<bool>& visited) {
for(int i=0;i<visited.size();i++) {
visited[i]=false;
}
}
public:
bool isValidSudoku(vector<vector<char>>& board) {
int rows=board.size();
int cols=board[0].size();
if(rows==0) {
return true;
}
vector<bool> visited(10, false);
// Traverse column by column
for(int i=0;i<cols;i++) {
for(int j=0;j<rows;j++) {
if(board[j][i]!='.') {
if(visited[board[j][i]-'0']) {
return false;
}
else {
visited[board[j][i]-'0']=true;
}
}
}
clear(visited);
}
// Traverse row by row
for(int i=0;i<rows;i++) {
for(int j=0;j<cols;j++) {
if(board[i][j]!='.') {
if(visited[board[i][j]-'0']) {
return false;
}
else {
visited[board[i][j]-'0']=true;
}
}
}
clear(visited);
}
vector<bool> visited2(10, false);
vector<bool> visited3(10, false);
vector<bool> *ref;
for(int i=0;i<rows;) {
for(int j=0;j<cols;j++) {
if(j<3)
ref=&visited;
else if(j<6)
ref=&visited2;
else
ref=&visited3;
if(board[i][j]!='.') {
if((*ref)[board[i][j]-'0']) {
cout<<i<<'\t'<<j<<endl;
return false;
}
else {
(*ref)[board[i][j]-'0']=true;
}
}
}
i++;
if(i%3==0) {
clear(visited);
clear(visited2);
clear(visited3);
}
}
return true;
}
}; | [
"[email protected]"
] | |
8022b6134dc60334cf4965242fd7110f0c6f0d25 | 38451d040d18cf7e84428fe48cf36608e21070a2 | /rand_gen.cpp | afef951421a88b7d0465d9bf1e7646663c8b20ed | [] | no_license | gmfricke/PowerSearch3D | f693cc1919f72b0ec2f9bd5d56f0f268e777ad70 | 63d8bf4dbdf41557a1be10ba77cd39b1748fd1b9 | refs/heads/master | 2021-01-10T10:48:34.341892 | 2017-08-16T15:26:05 | 2017-08-16T15:26:05 | 45,801,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,140 | cpp | #include "rand_gen.h"
#include <stdlib.h>
rand_gen::rand_gen(){
srand(time(NULL));
}
double rand_gen::uniform_dist(double a, double b){
double r=rand()/(RAND_MAX+1.0);
return a+(b-a)*r;
}
/*
To simulate exponential distribution exp(-lambda*x), the inverse
method is used.
The cumulative distribution function for the exponential
distribution is:1-exp(-lambda*x). The inversion function
is -log(1-U)/lambda. The simplified form is -log(U)/lambda,
where U is a uniform [0,1] random variable.
http://cg.scs.carleton.ca/~luc/rnbookindex.html
*/
double rand_gen::exponential_dist(double lambda){
return(-1*log(uniform_dist(0.,1.))/lambda);
}
/*
Simulate power law with cut-off x^(-alpha)*exp(-lambda*x)
To simulate power-law with cutoff , one can generate an
exponentially distributed random number using the formula
above (as k>0 and integer, so k start at 1)
and then accept or reject it with probability p or 1 - p
respectively (i.e accept U1 <p or reject U1>p, and
U1 is a uniform [0,1] random variable),
where p = (x/x_min)^(-alpha) and x_min=1.
http://www.santafe.edu/~aaronc/powerlaws/
*/
double rand_gen::powerlaw_dist(double alpha, double lamda)
{
double x;
do{
x = exponential_dist(lamda);
} while (pow(x,-1*alpha) < uniform_dist(0.,1.));
return (x);
}
int rand_gen::binomial_dist(int n, double p){
int m=0;
for( int i=0;i<n;i++){
if(uniform_dist(0.,1.)<p) m++;
}
return m;
}
/*
Poisson distribution
f(n, lambda) = lambda^n exp(-lambda)/n!
Algorithm Poisson random number (Knuth):
init: Let L =exp(-lambda), k=0 and p =1
do: k = k+
Generate uniform random number u in [0,1]
and let p =p*u
while p > L.
return k - 1.
*/
int rand_gen::poisson_dist(double lambda){
double L=exp(-1*lambda);
int k;
double p=1.;
k = 0;
do{
k = k + 1;
p = p*uniform_dist(0.,1.);
} while (p > L);
return k - 1;
}
double rand_gen::normal_dist(double sigma, double mu)
{
double V1, V2, S;
double X;
do {
double U1 = uniform_dist(0.,1.);
double U2 = uniform_dist(0.,1.);
V1 = 2 * U1 - 1;
V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
} while(S >= 1 || S == 0);
X = V1 * sqrt(-2 * log(S) / S);
return sigma*X+mu;
}
| [
"[email protected]"
] | |
99d02cc696b9acd19d116d6c01904aeb69cda331 | 776f5892f1395bb8d30731a60466e4c756a44c8c | /contests/abc233/abc233_f/main.cc | c73ef6c8417dcada59929de9738e14111cb5d8b9 | [] | no_license | kkishi/atcoder | fae494af4b47a9f39f05e7536e93d5c4dd21555b | f21d22095699dbf064c0d084a5ce5a09a252dc6b | refs/heads/master | 2023-08-31T18:37:13.293499 | 2023-08-27T21:33:43 | 2023-08-27T21:33:43 | 264,760,383 | 0 | 0 | null | 2023-03-10T05:24:07 | 2020-05-17T21:30:14 | C++ | UTF-8 | C++ | false | false | 972 | cc | #include <bits/stdc++.h>
#include "atcoder.h"
#include "disjoint_set.h"
void Main() {
ints(n);
V<int> p(n);
cin >> p;
each(e, p)-- e;
ints(m);
VV<pair<int, int>> g(n);
DisjointSet ds(n);
rep(i, m) {
ints(a, b);
--a, --b;
if (!ds.Same(a, b)) {
ds.Union(a, b);
g[a].eb(b, i);
g[b].eb(a, i);
}
}
V<int> ans;
rep(i, n) if (i != p[i]) {
Fix([&](auto rec, int node, int parent) -> void {
each(child, _, g[node]) if (child != parent) rec(child, node);
int NODE = node;
if (!Fix([&](auto rec, int node, int parent) -> bool {
if (p[node] == NODE) return true;
each(child, i, g[node]) if (child != parent && rec(child, node)) {
ans.pb(i + 1);
swap(p[node], p[child]);
return true;
}
return false;
})(node, -1)) {
wt(-1);
exit(0);
}
})(i, -1);
}
wt(sz(ans));
wt(ans);
}
| [
"[email protected]"
] | |
c06e98484060a11a38697fe404f15bf76cf8e470 | d7ea642cec35f60d4e3053009a7d858eb3c86f2c | /Patterns/Builder/Docs/Builder.cpp | d5c9ebc97e2540c67026273c06dff4196a8d15eb | [] | no_license | perezite/sandbox | 396091c9c1d4fa6c5275547148a6834853bdb376 | 759d697ca30cedda39a40d7e37d9d49a498b4cb4 | refs/heads/master | 2021-01-17T06:35:23.994689 | 2020-09-25T20:57:52 | 2020-09-25T20:57:52 | 59,944,622 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 471 | cpp | Quad quad;
quad.setPosition(1, 1);
quad.setScale(1, 1);
// Quad quad;
// quad.setPosition(1, 1).setScale(1, 1);
set(quad).with<setPosition>(1, 1).with<setScale>(1, 1);
template <class T>
class Builder {
T& _target;
public:
Builder(T& target) : _target(target) { }
template <class f, A1, A2>
Builder with(const A1& a1, const A2& a2) {
_target.f(a1, a2);
return _target;
}
}
typedef set Builder;
template <class T>
Builder& set(T& object) {
Builder builder;
} | [
"[email protected]"
] | |
ab6219c45e7607099cbd45f2d58993633225c54f | 304ff6d39a8eaa896317a34ec31787606a71656f | /SSAM019H.cpp | 698ac5ad66a3ebb8b709985fb68b9d4621609e7e | [] | no_license | S4ltF1sh/SPOJ | 4ed70e86d47371f436efd4080991bfc8ed3a9e65 | b7694fb770d973649e7804def0352dc075c822c8 | refs/heads/main | 2023-06-01T19:10:05.737305 | 2021-06-22T11:09:46 | 2021-06-22T11:09:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | cpp | //SSAM019H - SỐ FIBONACCI THỨ N
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
const long long MOD = 1e9 + 7;
struct MATRIX
{
long long tmp[2][2] = {{0, 1}, {1, 1}};
};
MATRIX Multi(MATRIX a, MATRIX b, int n)
{
MATRIX Res;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
Res.tmp[i][j] = 0;
for (int k = 0; k < n; k++)
Res.tmp[i][j] = (Res.tmp[i][j] + a.tmp[i][k] * b.tmp[k][j]) % MOD;
}
return Res;
}
MATRIX POW(MATRIX a, int k, int n)
{
if (k == 1)
return a;
if (k % 2 == 0)
{
MATRIX x = POW(a, k / 2, n);
return Multi(x, x, n);
}
else
{
return Multi(a, POW(a, k - 1, n), n);
}
}
void Run()
{
long long k;
cin >> k;
MATRIX a;
a = POW(a, k, 2);
cout << a.tmp[0][1] << "\n";
}
int main()
{
int t;
cin >> t;
while (t--)
Run();
} | [
"[email protected]"
] | |
bef13a4a3c077490ddf98236c282006cc4269b64 | dc6bcfd5b35a303f9d6c1734fd6f5f300ea39377 | /2 Data Structure (DS)/Exercises/Huffman_Coding/main.cpp | 8ceefd0b959631f2a2e1298f7ff01db7cd6978be | [] | no_license | HearyShen/SudaArchive | d2ec1be992ed937b76275d1096be71b61df2e2d5 | 71317dab9720ee27e2a1d16fc0b9a8c20246daf0 | refs/heads/master | 2022-04-16T10:48:49.143807 | 2020-04-17T14:12:04 | 2020-04-17T14:12:04 | 256,519,650 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,717 | cpp | #include <iostream>
#include <fstream>
#include <windows.h>
#include "Huffman_Tree.h"
#include "Pixel.h"
using namespace std;
const int W = 4;
const int H = 4;
//typedef struct tagBITMAPFILEHEADER
//{
// WORD bfType; //位图文件的类型,必须为BM(1-2字节)
// DWORD bfSize; //位图文件的大小,以字节为单位(3-6字节,低位在前)
// WORD bfReserved1; //位图文件保留字,必须为0(7-8字节)
// WORD bfReserved2; //位图文件保留字,必须为0(9-10字节)
// DWORD bfOffBits; //位图数据的起始位置,以相对于位图(11-14字节,低位在前)
// //文件头的偏移量表示,以字节为单位
//}BITMAPFILEHEADER;
//
//typedef struct tagBITMAPINFOHEADER{
// DWORD biSize;//本结构所占用字节数(15-18字节)
// LONG biWidth;//位图的宽度,以像素为单位(19-22字节)
// LONG biHeight;//位图的高度,以像素为单位(23-26字节)
// WORD biPlanes;//目标设备的级别,必须为1(27-28字节)
// WORD biBitCount;//每个像素所需的位数,必须是1(双色),(29-30字节)
// //4(16色),8(256色)16(高彩色)或24(真彩色)之一
// DWORD biCompression;//位图压缩类型,必须是0(不压缩),(31-34字节)
// //1(BI_RLE8压缩类型)或2(BI_RLE4压缩类型)之一
// DWORD biSizeImage;//位图的大小(其中包含了为了补齐行数是4的倍数而添加的空字节),以字节为单位(35-38字节)
// LONG biXPelsPerMeter;//位图水平分辨率,每米像素数(39-42字节)
// LONG biYPelsPerMeter;//位图垂直分辨率,每米像素数(43-46字节)
// DWORD biClrUsed;//位图实际使用的颜色表中的颜色数(47-50字节)
// DWORD biClrImportant;//位图显示过程中重要的颜色数(51-54字节)
//}BITMAPINFOHEADER;
//
//typedef struct tagRGBQUAD{
// BYTE rgbBlue;//蓝色的亮度(值范围为0-255)
// BYTE rgbGreen;//绿色的亮度(值范围为0-255)
// BYTE rgbRed;//红色的亮度(值范围为0-255)
// BYTE rgbReserved;//保留,必须为0
//}RGBQUAD;
//
//
//typedef struct tagBITMAPINFO{
// BITMAPINFOHEADER bmiHeader;//位图信息头
// RGBQUAD bmiColors[1];//颜色表
//}BITMAPINFO;
struct HuffmanHead
{
int CodeTypes;
};
void main()
{
BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;
RGBQUAD rgbQuad[256];
//BITMAPINFO bitmapInfo;
FILE* pfin = fopen("4X4.bmp","rb");
if(pfin == NULL)
cerr<<"error"<<endl;
//ifstream fin("in.bmp");
//ofstream fout("out.bmp");
/*读 in.bmp*/
fread(&fileHeader,sizeof(BITMAPFILEHEADER),1,pfin); //in: BitmapFileHeader
cout<<fileHeader.bfType<<endl
<<fileHeader.bfSize<<endl
<<fileHeader.bfReserved1<<endl
<<fileHeader.bfReserved2<<endl
<<fileHeader.bfOffBits<<endl;
fread(&infoHeader,sizeof(BITMAPINFOHEADER),1,pfin); //in: BitmapInfoHeader
cout<<"宽度(像素):"<<infoHeader.biWidth<<endl
<<"高度(像素):"<<infoHeader.biHeight<<endl
<<"每像素占用位:"<<infoHeader.biBitCount<<endl; //256色度 对应 8位每像素
fread(rgbQuad,sizeof(RGBQUAD),256,pfin); //in: RGBQUAD
fseek(pfin,fileHeader.bfOffBits,SEEK_SET);
char pixels[W*H];
int size = 0;
cout<<"位图数据预览(转int):"<<endl;
while(size < (infoHeader.biWidth * infoHeader.biHeight)) //读取像素并显示
{
fread(&pixels[size],sizeof(char),1,pfin);
cout<<(int)pixels[size]<<" ";
//cout<<pixels[size];
size++;
}
fclose(pfin);//及时关闭文件
cout<<endl;
/*遍历读取的像素点char[],去重并得出权重weight,实际像素种类数目sorted_size,得出sorted_pixels[]*/
Pixel sorted_pixels[W*H];
for(int i=0;i<size;i++)
{
sorted_pixels[i].pixel = pixels[i];
sorted_pixels[i].weight = 0;
}
int size_sorted = size;
//int weight[W*H];
for(int i=0;i<size_sorted;i++)
{
sorted_pixels[i].weight = 1;
for(int j=i+1;j<size_sorted;j++)
{
if(sorted_pixels[i].pixel == sorted_pixels[j].pixel)
{
for(int k=j;k<size_sorted;k++)
{
sorted_pixels[k] = sorted_pixels[k+1];
}
size_sorted--;
sorted_pixels[i].weight++;
j--;
}
}
}
/*根据权值weight,升序排序sorted_pixels[]*/
for(int i=0;i<size_sorted;i++)
{
int min_index = i;
for(int j=i+1;j<size_sorted;j++)
{
if(sorted_pixels[j].weight < sorted_pixels[min_index].weight)
{
min_index = j;
}
}
if(min_index != i)
swap(sorted_pixels[min_index],sorted_pixels[i]);
}
/*准备Huffman编码*/
HuffNode *myHuffTree = new HuffNode[2 * size_sorted - 1];
Code *myHuffCode = new Code[size_sorted];
if (size_sorted>MaxN)
{
cout << "定义的n越界,修改MaxN!" << endl;
exit(0);
}
/*构建赫夫曼树,形成编码,写入sorted_pixels[].HuffmanCode中,并显示*/
Huffman(sorted_pixels, size_sorted, myHuffTree);
HuffmanCode(myHuffTree, size_sorted, myHuffCode);
for(int i=0;i<size_sorted;i++)
{
char hfcode = 0;
cout<<"Code:";
for (int j = 0; j<myHuffCode[i].start; j++)
{
//sorted_pixels[i].HuffmanCode[j] = myHuffCode[i].bit[j];
hfcode = hfcode + myHuffCode[i].bit[j]*pow(2.0,myHuffCode[i].start-j-1);
sorted_pixels[i].hfcode = hfcode;
cout << myHuffCode[i].bit[j];
}
cout<<" Start:"<<myHuffCode[i].start<<" Weight:"<<myHuffCode[i].weight<<endl;
}
/*将对应的sorted_pixels(即像素和赫夫曼编码的 对应表) 写入新文件 *.huf */
FILE* pfhuf = fopen("out.huf","wb");
if(pfhuf == NULL)
cerr<<"error"<<endl;
fwrite(&fileHeader,sizeof(BITMAPFILEHEADER),1,pfhuf);
fwrite(&infoHeader,sizeof(BITMAPINFOHEADER),1,pfhuf);
fwrite(rgbQuad,sizeof(RGBQUAD),256,pfhuf);
fseek(pfhuf,fileHeader.bfOffBits,SEEK_SET);
HuffmanHead hfhead;
hfhead.CodeTypes = size_sorted;
fwrite(&hfhead,sizeof(HuffmanHead),1,pfhuf);//写入赫夫曼编码个数
size = 0;
while(size < size_sorted)
{
fwrite(&sorted_pixels[size],sizeof(Pixel),1,pfhuf);
size++;
}
/*将各个元素对应的赫夫曼编码(压缩后的数据)写入 *.huf */
char hfcode;
for(int i=0;i<(infoHeader.biWidth * infoHeader.biHeight);i++)
{
hfcode = getHuffmanCode(pixels[i],sorted_pixels,size_sorted);
fwrite(&hfcode,sizeof(char),1,pfhuf);
}
fclose(pfhuf);//及时关闭文件
/*读取 *.huf 文件*/
FILE* fin = fopen("out.huf","rb");
if(pfin == NULL)
cerr<<"error"<<endl;
fread(&fileHeader,sizeof(BITMAPFILEHEADER),1,fin);
fread(&infoHeader,sizeof(BITMAPINFOHEADER),1,fin);
fread(rgbQuad,sizeof(RGBQUAD),256,fin);
fseek(pfin,fileHeader.bfOffBits,SEEK_SET);
fread(&hfhead,sizeof(HuffmanHead),1,fin); //读取赫夫曼编码个数
size = 0;
while(size < hfhead.CodeTypes) //读取赫夫曼编码表
{
fread(&sorted_pixels[size],sizeof(Pixel),1,fin);
cout<<"读取的编码表(char->int)"<<(int)sorted_pixels[size].hfcode<<endl;
size++;
}
char hfcodes[W*H];
cout<<"赫夫曼码(char->int)|像素码(char->int)"<<endl;
for(int i=0;i<(infoHeader.biWidth * infoHeader.biHeight);i++)
{
fread(&hfcodes[i],sizeof(char),1,fin); //读取所有像素(赫夫曼编码)
pixels[i] = getBMPpixel(hfcodes[i],sorted_pixels,hfhead.CodeTypes);
cout<<(int)hfcodes[i]<<"|"<<(int)pixels[i];
}
cout<<endl;
fclose(fin);
/*还原 out.bmp*/
FILE* pfout = fopen("out.bmp","wb");
if(pfout == NULL)
cerr<<"error"<<endl;
fwrite(&fileHeader,sizeof(BITMAPFILEHEADER),1,pfout);
fwrite(&infoHeader,sizeof(BITMAPINFOHEADER),1,pfout);
fwrite(rgbQuad,sizeof(RGBQUAD),256,pfout);
fseek(pfout,fileHeader.bfOffBits,SEEK_SET);
size = 0;
while(size < (infoHeader.biWidth * infoHeader.biHeight))
{
//pixel[size] = getBMPpixel(
fwrite(&pixels[size],sizeof(char),1,pfout);
cout<<(int)pixels[size];
size++;
}
fclose(pfout);
} | [
"[email protected]"
] | |
cbc64de158ed744d32376d94fbdf8a2272ae39ea | 5cbe5f3b31d3f7c6eb9c271b1b1ff96fd08fe37f | /RetroGame/RenderEngine/RenderEngineInterop/Font.h | 7fcbdf3802446ecdd94d4e424d2de0ec2fda2910 | [] | no_license | Galli24/RetroGame | e807046475a28a4ccd9403112639f05b8aca0373 | cf53d0e0ed26db21c22e2e487e3bc9506f58c689 | refs/heads/master | 2023-02-26T14:54:33.568054 | 2021-02-07T17:27:12 | 2021-02-07T17:27:12 | 302,600,325 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 471 | h | #pragma once
#include "BaseInterop.h"
#include <cliext/adapter>
#include <cliext/algorithm>
#include <cliext/vector>
#include <cstring>
#include <msclr/marshal_cppstd.h>
#include "../RenderEngine/Font.h"
using namespace System;
namespace RenderEngine {
public ref class Font : BaseInterop<Rendering::Font>
{
public:
Font(String^ path, int size)
{
this->nativeResources = new Rendering::Font(msclr::interop::marshal_as<std::string>(path), size);
}
};
}
| [
"[email protected]"
] | |
44950da599395d670d8116c18bf0c0b240d98f57 | e36287151eed5c3215736575a7e81cf7bda1de5f | /DP3.cpp | bd82d01320485345fa65cd4e1941a23dfed97777 | [] | no_license | akhilagg7/Data-Structure | e2c0e7d47cc231bcf977cc47216a5fb0f3e45030 | 14edf3ed033363dc1b5459a1d0ed15cc5304e7ff | refs/heads/master | 2022-12-25T09:53:21.260592 | 2020-09-30T18:55:27 | 2020-09-30T18:55:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,871 | cpp | #include<iostream>
using namespace std;
int editDist(string s,string t)
{
if(s.size()==0)
{
return t.size();
}
if(t.size()==0)
{
return s.size();
}
if(s[0]==t[0])
{
return editDist(s.substr(1),t.substr(1));
}
int x=editDist(s.substr(1),t)+1;
int y=editDist(s,t.substr(1))+1;
int z=editDist(s.substr(1),t.substr(1))+1;
return min(x,min(y,z));
}
int editDist_better(string s,string t,int **ar)
{
if(s.size()==0)
{
return t.size();
}
if(t.size()==0)
{
return s.size();
}
int m=s.size();
int n=t.size();
if(ar[m][n]!=-1)
{
return ar[m][n];
}
if(s[0]==t[0])
{
ar[m][n]=editDist_better(s.substr(1),t.substr(1),ar);
}
else
{
ar[m-1][n]=editDist_better(s.substr(1),t,ar);
ar[m][n-1]=editDist_better(s,t.substr(1),ar);
ar[m-1][n-1]=editDist_better(s.substr(1),t.substr(1),ar);
ar[m][n]=min(ar[m-1][n],min(ar[m][n-1],ar[m-1][n-1]))+1;
}
return ar[m][n];
}
int editDist_better(string s,string t)
{
int m=s.size();
int n=t.size();
int **ar=new int*[m+1];
for(int i=0;i<=m;i++)
{
ar[i]=new int[n+1];
for(int j=0;j<=n;j++)
{
ar[i][j]=-1;
}
}
return editDist_better(s,t,ar);
}
int editDistDp(string s,string t)
{
int m=s.size();
int n=t.size();
int **ar=new int *[m+1];
for(int i=0;i<=m;i++)
{
ar[i]=new int[n+1];
}
for(int j=0;j<=n;j++)
{
ar[0][j]=j;
}
for(int i=0;i<=m;i++)
{
ar[i][0]=i;
}
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(s[m-i]==t[n-j])
{
ar[i][j]=ar[i-1][j-1];
}
else
{
ar[i][j]=min(ar[i-1][j],min(ar[i-1][j-1],ar[i][j-1]))+1;
}
}
}
return ar[m][n];
}
int main()
{
string s;
string t;
cin>>s>>t;
cout<<editDist(s,t)<<endl;
cout<<editDist_better(s,t)<<endl;
cout<<editDistDp(s,t)<<endl;
}
| [
"[email protected]"
] | |
e0ee09be8399dd5fb2ca7a5122dc4dd74918cf23 | 3d7f40a09ca2a6f58c81877b2f9985e8fabe0d66 | /C++/Week 6/Classwork/making file.cpp | dc886849b8f7909f84ab0a4da3c870e99a61b7c7 | [] | no_license | mkieft/Computing | 36dbd36ba7ef4c1e3c606d5f05ad81559b756562 | ecabc32ca501a60d62b5e9cb68d5c6a2b7033af1 | refs/heads/master | 2022-12-05T03:48:10.173132 | 2020-08-25T18:15:38 | 2020-08-25T18:15:38 | 290,288,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 452 | cpp | ///File: week6/classwork/makeFile.cpp MK
///make a file called ints.txt with ints from 1 to 10
#include <iostream>
#include <fstream> // for working with files
using namespace std;
main(){
ofstream fout ("ints.txt"); //variable that is a file
for ( int i = 1; i <= 1000; i ++){
cout << i << "\n"; //print to see how the file should look
fout << endl << i; //write in the file
}//for
fout.close();
return 0;
}//main
| [
"[email protected]"
] | |
6720ebdc573c7a68a94be71b5e7fbcb9a33d27be | 8567438779e6af0754620a25d379c348e4cd5a5d | /ui/android/window_android.h | 7219c0ac73fa1c185f701323a07f79fd0115cce6 | [
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 3,619 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ANDROID_WINDOW_ANDROID_H_
#define UI_ANDROID_WINDOW_ANDROID_H_
#include <jni.h>
#include <list>
#include <memory>
#include <string>
#include <vector>
#include "base/android/jni_weak_ref.h"
#include "base/android/scoped_java_ref.h"
#include "base/callback.h"
#include "base/macros.h"
#include "base/observer_list.h"
#include "base/time/time.h"
#include "ui/android/ui_android_export.h"
#include "ui/android/view_android.h"
#include "ui/gfx/geometry/vector2d_f.h"
namespace cc {
class BeginFrameSource;
} // namespace cc
namespace display {
class DisplayAndroidManager;
} // namespace display
namespace ui {
class WindowAndroidCompositor;
class WindowAndroidObserver;
// Android implementation of the activity window.
// WindowAndroid is also the root of a ViewAndroid tree.
class UI_ANDROID_EXPORT WindowAndroid : public ViewAndroid {
public:
WindowAndroid(JNIEnv* env, jobject obj, int display_id);
void Destroy(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj);
base::android::ScopedJavaLocalRef<jobject> GetJavaObject();
static bool RegisterWindowAndroid(JNIEnv* env);
// Compositor callback relay.
void OnCompositingDidCommit();
void AttachCompositor(WindowAndroidCompositor* compositor);
void DetachCompositor();
void AddObserver(WindowAndroidObserver* observer);
void RemoveObserver(WindowAndroidObserver* observer);
WindowAndroidCompositor* GetCompositor() { return compositor_; }
cc::BeginFrameSource* GetBeginFrameSource();
// Runs the provided callback as soon as the current vsync was handled.
void AddVSyncCompleteCallback(const base::Closure& callback);
void SetNeedsAnimate();
void Animate(base::TimeTicks begin_frame_time);
void OnVSync(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
jlong time_micros,
jlong period_micros);
void OnVisibilityChanged(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
bool visible);
void OnActivityStopped(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
void OnActivityStarted(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
// Return whether the specified Android permission is granted.
bool HasPermission(const std::string& permission);
// Return whether the specified Android permission can be requested by Chrome.
bool CanRequestPermission(const std::string& permission);
static WindowAndroid* CreateForTesting();
void DestroyForTesting();
private:
class WindowBeginFrameSource;
friend class DisplayAndroidManager;
friend class WindowBeginFrameSource;
~WindowAndroid() override;
void SetNeedsBeginFrames(bool needs_begin_frames);
void RequestVSyncUpdate();
// ViewAndroid overrides.
WindowAndroid* GetWindowAndroid() const override;
// The ID of the display that this window belongs to.
int display_id() const { return display_id_; }
base::android::ScopedJavaGlobalRef<jobject> java_window_;
const int display_id_;
WindowAndroidCompositor* compositor_;
base::ObserverList<WindowAndroidObserver> observer_list_;
std::unique_ptr<WindowBeginFrameSource> begin_frame_source_;
bool needs_begin_frames_;
std::list<base::Closure> vsync_complete_callbacks_;
DISALLOW_COPY_AND_ASSIGN(WindowAndroid);
};
} // namespace ui
#endif // UI_ANDROID_WINDOW_ANDROID_H_
| [
"[email protected]"
] | |
9b23da42d41976583cb8a53db7cdf0960814116c | c1671bd042b11704cc7d8c545d023e718ae99a09 | /eMu - GameServer Sapphire S0/GameServer/Weapon.cpp | b50a8f3104a587058dbee9b245a001733dd73d4b | [] | no_license | Sogues/mu1.1 | e9a31864b2ebc2517f5aeba1ead735d3fedfcfba | 58de7aeee6ca26be861b0f0a81cf0cbf5ad8db11 | refs/heads/master | 2022-04-08T13:32:57.142927 | 2020-03-29T15:13:46 | 2020-03-29T15:13:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,823 | cpp | #include "stdafx.h"
#include "Weapon.h"
#include "user.h"
#include "gObjMonster.h"
#include "ObjAttack.h"
// GS-N 0.99.60T 0x0051A5F0
// GS-N 1.00.18 JPN 0x0054BF60 - Completed
// GS-CS 1.00.18 JPN 0x0054BF60 - Completed
CWeapon g_CsNPC_Weapon;
#define MAX_ST_CS_WEAPON (4)
struct ST_CS_WEAPON
{
BYTE btXBegin; // 0
BYTE btYBegin; // 1
BYTE btXEnd; // 2
BYTE btYEnd; // 3
};
static const ST_CS_WEAPON WEAPON_CS_ATTACKER[MAX_ST_CS_WEAPON] =
{
0x3E, 0x67, 0x48, 0x70, 0x58, 0x68, 0x7C, 0x6F,
0x74, 0x69, 0x7C, 0x70, 0x49, 0x56, 0x69, 0x67
};
static const ST_CS_WEAPON WEAPON_CS_DEFENSER[MAX_ST_CS_WEAPON] =
{
0x3D, 0x58, 0x5D, 0x6C, 0x5C, 0x59, 0x7F, 0x6F,
0x54, 0x34, 0x66, 0x42, 0x00, 0x00, 0x00, 0x00
};
CWeapon::CWeapon()
{
for (int i=0;i<MAX_WEAPON_CAL_DAMAGER_INFO;i++) // #error Cahnge to MAX_WEAPON_DAMAGED_TARGET_INFO
{
this->m_WeaponDamagedTargetInfo[i].RESET();
}
for (int i=0;i<MAX_WEAPON_DAMAGED_TARGET_INFO;i++) // #error Cahnge to MAX_WEAPON_CAL_DAMAGER_INFO
{
this->m_WeaponCalDamageInfo[i].RESET();
}
}
CWeapon::~CWeapon()
{
return;
}
BOOL CWeapon::SetWeaponCalDamageInfo(WORD wObjIndex, BYTE btTargetX, BYTE btTargetY, int iDelayTime)
{
for (int i=0;i<MAX_WEAPON_CAL_DAMAGER_INFO;i++)
{
if ( this->m_WeaponCalDamageInfo[i].m_IsUsed == FALSE )
{
this->m_WeaponCalDamageInfo[i].m_iWeaponObjIndex = wObjIndex;
this->m_WeaponCalDamageInfo[i].m_iTargetX = btTargetX;
this->m_WeaponCalDamageInfo[i].m_iTargetY = btTargetY;
this->m_WeaponCalDamageInfo[i].m_iLimitTime = GetTickCount() + iDelayTime;
this->m_WeaponCalDamageInfo[i].m_IsUsed = TRUE;
return TRUE;
}
}
return FALSE;
}
BOOL CWeapon::GetWeaponCalDamageInfo(WORD wObjIndex, BYTE & btTargetX, BYTE & btTargetY)
{
for( int i=0;i<MAX_WEAPON_CAL_DAMAGER_INFO;i++)
{
if ( this->m_WeaponCalDamageInfo[i].m_IsUsed == TRUE && this->m_WeaponCalDamageInfo[i].m_iWeaponObjIndex == wObjIndex)
{
btTargetX = this->m_WeaponCalDamageInfo[i].m_iTargetX;
btTargetY = this->m_WeaponCalDamageInfo[i].m_iTargetY;
this->m_WeaponCalDamageInfo[i].RESET();
return TRUE;
}
}
return FALSE;
}
int CWeapon::GetAttackDamage(int iObjClass)
{
int iDamage = 0;
if ( iObjClass == 221 )
{
iDamage = 300;
}
else if ( iObjClass == 222 )
{
iDamage = 200;
}
return iDamage;
}
BOOL CWeapon::GetTargetPointXY(int iObjClass, int iTargetPointIndex, BYTE &btX, BYTE &btY, BOOL bRandomPos)
{
if ( iObjClass == 221 )
{
if ( iTargetPointIndex >= 0 && iTargetPointIndex < MAX_ST_CS_WEAPON )
{
int tx = WEAPON_CS_ATTACKER[iTargetPointIndex].btXEnd - WEAPON_CS_ATTACKER[iTargetPointIndex].btXBegin;
int ty = WEAPON_CS_ATTACKER[iTargetPointIndex].btYEnd - WEAPON_CS_ATTACKER[iTargetPointIndex].btYBegin;
if ( bRandomPos != FALSE )
{
btX = WEAPON_CS_ATTACKER[iTargetPointIndex].btXBegin + rand() % tx;
btY = WEAPON_CS_ATTACKER[iTargetPointIndex].btYBegin + rand() % ty;
}
else
{
btX = WEAPON_CS_ATTACKER[iTargetPointIndex].btXBegin + tx / 2;
btY = WEAPON_CS_ATTACKER[iTargetPointIndex].btYBegin + ty / 2;
}
}
}
if ( iObjClass == 222 )
{
if ( iTargetPointIndex >= 0 && iTargetPointIndex < MAX_ST_CS_WEAPON )
{
int tx = WEAPON_CS_DEFENSER[iTargetPointIndex].btXEnd - WEAPON_CS_DEFENSER[iTargetPointIndex].btXBegin;
int ty = WEAPON_CS_DEFENSER[iTargetPointIndex].btYEnd - WEAPON_CS_DEFENSER[iTargetPointIndex].btYBegin;
if ( bRandomPos != FALSE )
{
btX = WEAPON_CS_DEFENSER[iTargetPointIndex].btXBegin + rand() % tx;
btY = WEAPON_CS_DEFENSER[iTargetPointIndex].btYBegin + rand() % ty;
}
else
{
btX = WEAPON_CS_DEFENSER[iTargetPointIndex].btXBegin + tx / 2;
btY = WEAPON_CS_DEFENSER[iTargetPointIndex].btYBegin + ty / 2;
}
}
}
return TRUE;
}
BOOL CWeapon::MissCheck(LPOBJ lpObj, LPOBJ lpTargetObj, int iSkill, int iSkillSuccess, BOOL& bAllMiss)
{
return TRUE;
}
BOOL CWeapon::Attack(LPOBJ lpObj, LPOBJ lpTargetObj, CMagicInf * lpMagic, int iCriticalDamage, int iActionType)
{
int iSkill = 0;
int iSkillSuccess = TRUE;
BYTE MsgDamage = 0;
int ManaChange = 0;
if ( lpMagic != NULL )
{
iSkill = lpMagic->m_Skill;
}
if ( (lpTargetObj->Authority & 2) == 2 )
{
return FALSE;
}
if ( lpObj->MapNumber != lpTargetObj->MapNumber )
{
return FALSE;
}
if ( lpTargetObj->Type == OBJ_USER )
{
if ( gObjIsConnected(lpTargetObj) == FALSE )
{
return FALSE;
}
}
if ( gObjAttackQ(lpTargetObj) == 0 )
{
return FALSE;
}
lpObj->m_TotalAttackCount++;
int MSBFlag = 0;
if ( iCriticalDamage != 0 )
{
MsgDamage = 3;
}
else
{
MsgDamage = 0;
}
int iAttackDamage = this->GetAttackDamage(lpObj->Class);
int iSkillDefense = lpTargetObj->m_SkillDefense;
int iTargetDefense = lpTargetObj->m_Defense + iSkillDefense;
iTargetDefense -= (iTargetDefense * lpTargetObj->m_SkillMagumReduceDefense)/100;
BOOL bAllMiss = FALSE;
if ( this->MissCheck(lpObj, lpTargetObj, iSkill, iSkillSuccess, bAllMiss) == FALSE )
{
return FALSE;
}
if ( bAllMiss != FALSE )
{
iAttackDamage = (iAttackDamage * 30)/100;
}
if ( lpTargetObj->DamageMinus != 0 )
{
int lc11 = iAttackDamage;
iAttackDamage -= (iAttackDamage * lpTargetObj->DamageMinus)/100;
}
int iTargetLevel = lpObj->Level / 10;
if ( iAttackDamage < iTargetLevel )
{
if ( iTargetLevel < 1 )
{
iTargetLevel = 1;
}
iAttackDamage = iTargetLevel;
}
if ( lpTargetObj->m_SkillNumber == 18 )
{
if ( iAttackDamage > 1 )
{
iAttackDamage = iAttackDamage >> 1;
}
}
if ( gObjAngelSprite(lpTargetObj) == TRUE )
{
if ( iAttackDamage > 1 )
{
float lc13 = (float)(iAttackDamage * 8 ) / 10.0f;
iAttackDamage = (int)( lc13 );
}
}
if ( gObjWingSprite(lpTargetObj) == TRUE )
{
CItem * Wing = &lpTargetObj->pInventory[7];
if ( iAttackDamage > 1 )
{
if ( Wing->m_Type > ITEMGET(12,2) )
{
float lc15 = float((int)iAttackDamage * (int)(75 - Wing->m_Level * 2) ) / 100.0f;
iAttackDamage = (int )lc15;
}
else
{
float lc16 = float((int)iAttackDamage * (int)(88 - Wing->m_Level * 2) ) / 100.0f;
iAttackDamage = (int)lc16;
}
}
}
if ( gObjDenorantSprite(lpTargetObj) != FALSE )
{
CItem * Dino = &lpTargetObj->pInventory[8];
int ReduceDamage = 90 - Dino->IsDinorantReduceAttackDamaege();
lpObj->Life -= 1.0f;
if ( lpObj->Life < 0.0f )
{
lpObj->Life = 0;
}
else
{
iAttackDamage = (iAttackDamage * ReduceDamage)/100;
}
GCReFillSend(lpObj->m_Index, lpObj->Life, (BYTE)-1, 0);
}
if ( gObjDarkHorse(lpTargetObj) != FALSE )
{
CItem * DarkHorse = &lpTargetObj->pInventory[8];
int DHPercent = 100-(DarkHorse->m_PetItem_Level+30)/2;
lpTargetObj->Life -= 1.0f;
if ( lpTargetObj->Life < 0.0f )
{
lpTargetObj->Life = 0;
}
else
{
iAttackDamage = (iAttackDamage * DHPercent)/100;
}
GCReFillSend(lpTargetObj->m_Index, lpTargetObj->Life, (BYTE)-1, 0);
}
if ( lpTargetObj->Live != FALSE )
{
if ( lpTargetObj->m_WizardSkillDefense !=0 && iAttackDamage > 0 )
{
int ManaPercent = (WORD)lpTargetObj->Mana * 2 / 100;
if ( ManaPercent < lpTargetObj->Mana )
{
lpTargetObj->Mana -= ManaPercent;
int lc22 = (iAttackDamage * lpTargetObj->m_WizardSkillDefense )/100;
iAttackDamage -= lc22;
ManaChange = TRUE;
}
}
lpTargetObj->Life -= iAttackDamage;
if ( lpTargetObj->Life < 0.0f )
{
lpTargetObj->Life = 0;
}
}
if ( iAttackDamage >= 1 )
{
if ( lpTargetObj->Type == OBJ_USER )
{
gObjArmorRandomDurDown(lpTargetObj, lpObj);
}
}
if ( iAttackDamage >= 5 )
{
if ( lpTargetObj->Type == OBJ_MONSTER )
{
if ( (rand()%26) == 0 )
{
gObjAddMsgSendDelay(lpTargetObj, 4, lpObj->m_Index, 100, 0);
}
}
else if ( (rand()%4) == 0 )
{
if ( gObjUniriaSprite(lpTargetObj) == FALSE )
{
MSBFlag = TRUE;
}
}
}
if ( ManaChange != FALSE )
{
GCManaSend(lpTargetObj->m_Index, lpTargetObj->Mana, (BYTE)-1, 0, lpTargetObj->BP);
}
lpObj->m_Rest = 0;
if ( iAttackDamage > 0 )
{
gObjLifeCheck(lpTargetObj, lpObj, iAttackDamage, 0, MSBFlag, MsgDamage, iSkill);
}
return TRUE;
}
BOOL CWeapon::AddWeaponDamagedTargetInfo(int iWeaponIndex, int iTargetIndex, int iDelayTime)
{
for (int i=0;i<MAX_WEAPON_DAMAGED_TARGET_INFO;i++)
{
if ( this->m_WeaponDamagedTargetInfo[i].m_IsUsed == FALSE )
{
this->m_WeaponDamagedTargetInfo[i].m_iWeaponObjIndex = iWeaponIndex;
this->m_WeaponDamagedTargetInfo[i].m_iTargetObjIndex = iTargetIndex;
this->m_WeaponDamagedTargetInfo[i].m_iDamageDealingTime = GetTickCount() + iDelayTime;
this->m_WeaponDamagedTargetInfo[i].m_IsUsed = TRUE;
return TRUE;
}
}
return FALSE;
}
void CWeapon::WeaponAttackProc()
{
for (int i=0;i<MAX_WEAPON_DAMAGED_TARGET_INFO;i++)
{
if ( this->m_WeaponDamagedTargetInfo[i].m_IsUsed == TRUE )
{
if ( this->m_WeaponDamagedTargetInfo[i].m_iDamageDealingTime > GetTickCount() )
{
continue;
}
LPOBJ lpTargetObj = &gObj[this->m_WeaponDamagedTargetInfo[i].m_iTargetObjIndex];
LPOBJ lpWeaponObj = & gObj[this->m_WeaponDamagedTargetInfo[i].m_iWeaponObjIndex];
if ( gObjIsConnected(lpTargetObj) == FALSE )
{
this->m_WeaponDamagedTargetInfo[i].RESET();
continue;
}
if ( OBJMAX_RANGE(lpWeaponObj->m_Index) == FALSE )
{
this->m_WeaponDamagedTargetInfo[i].RESET();
continue;
}
this->Attack(lpWeaponObj, lpTargetObj, NULL, FALSE, 0);
this->m_WeaponDamagedTargetInfo[i].RESET();
}
}
}
void CWeapon::WeaponAct(int iIndex)
{
for (int i=0;i<MAX_WEAPON_CAL_DAMAGER_INFO;i++)
{
if ( this->m_WeaponCalDamageInfo[i].m_IsUsed == TRUE )
{
if ( this->m_WeaponCalDamageInfo[i].m_iWeaponObjIndex == iIndex )
{
if ( this->m_WeaponCalDamageInfo[i].m_iLimitTime < GetTickCount() )
{
this->m_WeaponCalDamageInfo[i].RESET();
}
}
}
}
} | [
"[email protected]"
] | |
50023361dfe06548caadb2ec44f1cbc289ae608b | 594855ca5b64696332206a44fe5e92a72d7a0a17 | /h/winmove.h | 415ab248a929ac44c05f637e70fe2c57c1c4a806 | [] | no_license | dnichyparuk/bob-flight-sim | 2669e272507cc179512929c1bad9f911f9dd7d44 | 5e70a2d0b452bd2f6b1392c292d82bf757bb05e9 | refs/heads/master | 2021-05-17T00:38:34.429823 | 2014-10-15T14:27:15 | 2014-10-15T14:27:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,535 | h | //------------------------------------------------------------------------------
//Filename winmove.h
//System
//Date Fri 9 Aug 1996
//------------------------------------------------------------------------------
#ifndef WINMOVE_Included
#define WINMOVE_Included
#define DEFAULT_WINMOVE 0
#include "DOSDefs.h"
#include "UniqueID.h"
#include "savegame.h"
#include "misssub.h"
#include "cbuffer.h" //Winmove is included in everything else, so now
#include "shapenum.g"
// directX stuff
typedef struct IDirectPlay4 *LPDIRECTPLAY4A; // directX 6.0
typedef struct IDirectPlayLobby3 *LPDIRECTPLAYLOBBY3A; // directX 6.0
const int RNDPACKETSIZE = 57; // random list size + 2
const int BUFFERLENGTH = 128;
const int HISTBUFFERLENGTH = BUFFERLENGTH * 2;
const int NUMRADIOMESSAGES = 8;
// actual number displayed is this-1 because need spare entry for new chat
const int NUMBUFFEREDMESSAGES = 11;
const int MAXCOMMSMESSAGESIZE = 1064;
// packet required for resynch phase, need abs position
// damage state and score
typedef struct _acstatepacket ACSTATEPACKET;
typedef struct _acstatepacket* LPACSTATEPACKET;
struct _acstatepacket {
ULong PacketID;
COORDS3D Pos;
ANGLES Pitch;
ANGLES Heading;
ANGLES Roll;
SLong Velocity;
UByte MyKills;
UByte MyAssists;
UByte MyDeaths;
Bool alive;
bool resurrect;
bool joining;
};
// new comms ac packet, designed for prediction purposes and wireplay.
// x, y, z, heading, pitch, roll and velocity are deltas from previous
// values.
// first section used for replay as well, dont need any frame or ack info
typedef struct _basic_packet BASICPACKET;
typedef struct _basic_packet* LPBASICPACKET;
struct _basic_packet {
UByte Shift:4;
UByte Bull:4;
UByte Velocity_;
UByte X;
UByte Y;
UByte Z;
UByte Heading;
UByte Pitch;
UByte Roll;
UByte IDCode; // 2bits for additional packet type, 6 bits info
UByte byte1; // extra stuff
UByte byte2; // extra stuff
UByte byte3; // extra stuff
UByte byte4; // extra stuff
UByte byte5; // extra stuff
};
#define EXTRASIZE 6
// for comms need frame and ack info
typedef struct _ac_packet ACPACKET;
typedef struct _ac_packet* LPACPACKET;
struct _ac_packet : public _basic_packet
{
UByte Count; // increments every frame
UByte Ack1;
UByte Ack2;
};
// aggregated packet
typedef struct agg_send_packet AGGSENDPACKET;
typedef struct agg_send_packet* LPAGGSENDPACKET;
struct agg_send_packet {
// bit field represents that player is in this packet
ULong PlayersInPacket;
UByte Count;
ACPACKET player[MAXPLAYERS];
};
// packets sent by player to aggregator
// Done indicates packet has been received back OK and processed
typedef struct send_packet_buff SENDPACKETBUFF;
typedef struct send_packet_buff* LPSENDPACKETBUFF;
struct send_packet_buff {
ACPACKET packet;
Bool Done;
UByte ResendStatus;
};
// aggregated packet sent by aggregator with list of
// who has acked the packet
typedef struct aggsendpackbuff AGGBUFF;
typedef struct aggsendpackbuff* LPAGGBUFF;
struct aggsendpackbuff {
UByte NumPlayersInPacket;
AGGSENDPACKET aggpack;
Bool Acks[MAXPLAYERS];
UByte ResendStatus;
};
// stores ac positions, used with ACPOSENTRY to keep a
// historical record of ac positions for last 50 frames
// this is used in determining AI and AAA actions
typedef struct acposition ACPOSITION;
typedef struct acposition* LPACPOSITION;
struct acposition {
ONLYFIELD(UWord,UniqueID,ID);
COORDS3D Pos;
ANGLES Pitch;
ANGLES Heading;
ANGLES Roll;
SLong Velocity;
UByte Frame;
};
typedef struct acposentry ACPOSENTRY;
typedef struct acposentry* LPACPOSENTRY;
struct acposentry : public acposition
{
// used for various things, including indicating that 1st AIACposition packet has been sent
// and next one should be 2nd half
UByte extrainfo;
ONLYFIELD(UWord,UniqueID,Unfriendly);
LPACPOSENTRY next;
};
// list of who has acked which frames, used to determine which is the
// last frame that all players have received and can therefor be used
// for AI and AAA actions
typedef struct ackbuff ACKBUFF;
typedef struct ackbuff* LPACKBUFF;
struct ackbuff {
UByte Frame;
Bool Acks[MAXPLAYERS];
};
typedef struct idcode IDCODEPACKET;
typedef struct idcode* LPIDCODEPACKET;
struct idcode
{
UByte IDCode;
};
// information needed to cause a collision
typedef struct _comms_collision COMMSCOLLISION;
typedef struct _comms_collision* LPCOMMSCOLLISION;
// UID hitter 14 bits
// UID hit 14 bits
// HitterInfo 9 bits (coltype = 3, colstrength = 6)
// HitData 9 bits
struct _comms_collision : idcode
{
UWord id; // 14-bits
UWord offset; // 9-bits
UByte type; // 3-bits
UByte str; // 6-bits
UWord hitterscorer; // 14bits
};
typedef ULong myDPID;
typedef ULong* myLPDPID;
enum MessageCodes {
PKILLEDBYP=0,YOUCRASHED,YOUCOLLIDEDWITHP,PCRASHED,PCOLLIDEDWITHP,
KILLEDBYP,KILLEDP,PLEFTGAME,YOUDIED,PDIED,PCHEATED
};
// record of packets sent to aggregator
typedef struct _delta_record DELTARECORD;
typedef struct _delta_record* LPDELTARECORD;
struct _delta_record {
COORDS3D lastpos; // SLongs
ANGLES Pitch;
ANGLES Heading; // (yaw)
ANGLES Roll;
SLong Velocity;
UByte SpecCode; // as well as deltas need make sure dont lose
// any kill or resurrect messages etc...
UByte byte1;
UByte byte2;
UByte byte3;
UByte Count;
Bool Done;
} ;
// received packets
typedef struct _buffer_pack BUFFPACK;
typedef struct _buffer_pack* LPBUFFPACK;
struct _buffer_pack
{
UByte Count;
ACPACKET PlayerData[MAXPLAYERS];
Bool Received[MAXPLAYERS];
};
typedef struct _hist_buff HISTBUFF;
typedef struct _hist_buff* LPHISTBUFF;
struct _hist_buff
{
// this position has been received ok
bool OK;
// historical position
COORDS3D Pos;
ANGLES Pitch;
ANGLES Heading;
ANGLES Roll;
SLong Velocity;
UByte Frame;
// deltas for recalculating position
ACPACKET deltas;
};
// list of packets received, used to ack packets
typedef struct _reclist RECLIST;
typedef struct _reclist* LPRECLIST;
struct _reclist
{
UByte packet;
};
// stores bullet/missile/fuel etc launches
typedef struct _bul_entry BULENTRY;
typedef struct _bul_entry* LPBULENTRY;
struct _bul_entry
{
ULong num;
ULong index;
ULong framelaunched;
};
// dplat service provider list
typedef struct _enum_service ENUMSERVICE;
typedef struct _enum_service* LPENUMSERVICE;
struct _enum_service
{
GUID sid; //service ID
char* sname; //service name
UByte* connection; //connection info buffer
ULong connsize; //connection info buffer size
LPENUMSERVICE Next;
};
// dplay session list
typedef struct _enum_session ENUMSESSION;
typedef struct _enum_session* LPENUMSESSION;
struct _enum_session
{
char* sname; //service name
LPENUMSESSION Next;
};
// visitor book information
typedef struct _visitor_info VISITORINFO;
typedef struct _visitor_info* LPVISITORINFO;
struct _visitor_info
{
char* vis_name; // visitors name
Bool vis_status; // set TRUE if visitor can join game
LPVISITORINFO next; // next visitor
};
// any other effect that needs transmitting
typedef struct _special_packet SPECPACKET;
typedef struct _special_packet* LPSPECPACKET;
struct _special_packet : idcode
{
UByte spec1;
UByte spec2;
UByte spec3;
UByte spec4;
UByte spec5;
};
typedef struct uidpacket UIDPACKET;
typedef struct uidpacket* LPUIDPACKET;
struct uidpacket : idcode
{
ONLYFIELD(UWord,UniqueID, uid1);
ONLYFIELD(UWord,UniqueID, uid2);
};
typedef struct _chatmessage CHATMESSAGE;
typedef struct _chatmessage* LPCHATMESSAGE;
struct _chatmessage
{
char chat[128];
char name[32];
};
typedef struct _item_info ITEMINFO;
typedef struct _item_info* LPITEMINFO;
struct _item_info
{
UniqueID item;
UByteP details;
UByteP anim;
LPITEMINFO next;
};
typedef struct _dead_info DEADINFO;
typedef struct _dead_info* LPDEADINFO;
struct _dead_info
{
UByteP block;
LPDEADINFO next;
};
typedef struct _playersaggcheck PLAYERAGGCHECK;
typedef struct _playersaggcheck* LPPLAYERAGGCHECK;
struct _playersaggcheck
{
SWord Frame; // aggregator frame number
bool acked[MAXPLAYERS]; // which players have acked this agg frame
SWord whichframe[MAXPLAYERS]; // players frame numbers in agg packet
UByte used[MAXPLAYERS]; // this entry has been found and used to process a packet
};
typedef struct dead_pilot DEADPILOT;
typedef struct dead_pilot* LPDEADPILOT;
struct dead_pilot
{
int squadron;
UByte position;
bool raf;
LPDEADPILOT next;
};
struct H2HPlayerInfo;
struct H2HPlayer;
class item ;
class AirStruc ;
typedef item Item,*ItemPtr,*itemptr;
typedef AirStruc *AirStrucPtr;
enum ShapeNum;
class MovingItem ;
class DPlay {
public:
enum HostPrefs
{
AIR2AIR=0,
GROUND,
WEAPON,
ENGINEMAN
};
enum CommsEntryStage
{
STAGE_BFIELDS=0,
STAGE_RANDOMLIST,
STAGE_MAX
};
enum PlayerType
{
PLAYER_HOST=1,
PLAYER_GUEST
};
enum PacketIDCodes {
// 00 top 2 bits indicate 1st part of bullet packet
PIDC_BULLET=0,
// 01 top 2 bits indicate coll effect
// 2 uids, next 2 top bits= type of packet
// last 4 bits = part of uid
PIDC_UIDPACKET=64,
PIDC_SCORECLAIM=64, // 01000000
PIDC_WINGMANCOMMAND=80, // 01010000
PIDC_NEXT=96, // 01100000
PIDC_LASTONE=112, // 01110000
// 10 top 2 bits indicate collision packet
PIDC_COLLISION=128,
// 11 top 2 bits indicate collision/special packet
PIDC_RESURRECTEND=192,
PIDC_RESURRECT=193,
PIDC_PACKETERROR=194,
PIDC_INITPACK=195,
PIDC_DUMMYPACKET=196,
PIDC_NEARMISS=197,
PIDC_LANDEDEFFECT=198,
PIDC_AERODEVICE=199,
PIDC_DEATHMOVEEFFECT=201,
PIDC_OWNERCHANGE=202,
PIDC_EMPTY=203,
PIDC_KILLLAUNCHER=204,
PIDC_PLAYERMESSAGE=205,
PIDC_EJECT=207,
PIDC_SHAPECHANGE=208,
PIDC_ACCELGEARUP=209,
PIDC_NEWWP=210,
PIDC_SECONDARYAERODEVICES=213,
PIDC_DONTSEND=214,
PIDC_ENGINERPM=215,
PIDC_ENGINEANIM=216,
// have these last for checking purposes in StorePacket
PIDC_AIACPOSITION1=253,
PIDC_AIACPOSITION2=254,
PIDC_END=255
};
enum PacketType {
PT_BULLET=0,
PT_UIDS=1,
PT_COLLISION=2,
PT_SPECIAL=3,
};
enum GameTypes {
DEATHMATCH=0,
TEAMPLAY,
COMMSQUICKMISSION
};
enum TeamSides {
TS_NONE=0,
TS_BLUE,
TS_RED,
TS_GREEN,
TS_UNASSIGNED
};
enum CommsTimerIDS {
TIMER_PAINTSHOP=2364,
TIMER_ACSELECT,
TIMER_PREFSGAME,
TIMER_PREFSFLIGHT,
TIMER_PREFS3D,
TIMER_PREFS3D2,
TIMER_PREFSVIEWS,
TIMER_PREFSCONTROLS,
TIMER_PREFSOTHERS,
TIMER_READYROOM,
TIMER_VISITORS,
TIMER_MISSIONBRIEF,
TIMER_FRAG,
TIMER_RADIO,
TIMER_MAP,
TIMER_VARIANTS,
TIMER_DEBRIEF
};
enum CommsPlayerStatus {
CPS_NONE=0,
CPS_PAINTSHOP,
CPS_PREFS,
CPS_READYROOM,
CPS_3D,
CPS_GAMESTARTUP, // when host has selected fly
CPS_MAP,
CPS_VISITORBOOK,
CPS_MISSIONBRIEF,
CPS_FRAG,
CPS_RADIO,
CPS_JOINING, // when a player attempts to join 3d
CPS_RESYNCING,
CPS_DEBRIEF,
CPS_VARIANTS
};
DPlay ();
~DPlay ();
// direct play specific vars
LPENUMSERVICE ServiceList; // list of dplay services with names and ids
LPENUMSESSION SessionList; // list of dplay session names
LPDIRECTPLAY4A lpDP4; // oo look DirectX 6
LPGUID lpAppGuid; // Global GUID Number
char* tempdpsessdesc2;
LPDIRECTPLAYLOBBY3A lpDPL; //DirectPlay Lobby
char* templpDPC;
// direct play specific funcs
Bool InitDirectPlay ();
void ExitDirectPlay();
Bool UIMultiPlayInit (); // Main Menu
Bool UISelectServiceProvider(char* servicename);
bool UIGetSessionListUpdate ();
bool UIAssignServices();
void DeleteServiceList();
void DeleteSessionList();
// this players data vars
Bool PlayerCreated; // Ok to send messages (Player Created)
Bool Implemented; // DirectPlay/Session/Player Flag
Bool Host; // True if this machine is host, else guest
ULong UIPlayerType; // Host or Guest, for UI Only
ULong MyTeamKills;
ULong MyTeamDeaths;
ULong EnemyTeamKills;
ULong EnemyTeamDeaths;
myDPID aggID; // aggregator ID
myDPID myDPlayID; //dplay id/wplay id
ULong mySlot; // players position in h2h_player struc, alloc packet
// aggregated packet etc (everything in fact)
myDPID playergroupID;
// make acks buffer bigger to cope with resent packets
CBuffer<RECLIST,BUFFERLENGTH*2> RecPackBuffer;
CBuffer<SENDPACKETBUFF,BUFFERLENGTH> SendPackBuffer;
// game data
// circular buffer to store ac packets.
CBuffer<BUFFPACK,BUFFERLENGTH> PacketBuffer;
// historical buffer for AAA
CBuffer<HISTBUFF, HISTBUFFERLENGTH> HistPosBuffer[MAXPLAYERS];
void UpdateHistBuffer(LPACPACKET Packet,ULong slot);
void AddPacketToHistBuffer(LPACPACKET Packet,ULong slot);
// this frames deltas
DELTARECORD Deltas;
// collision stuff
CBuffer<COMMSCOLLISION,BUFFERLENGTH> CollBuffer;
void NewCollision2 (UWord id, UWord offset, UByte hitbox, UByte typeandstr, UniqueID hitterscorer); //RJS 19Jun00
// special packet
CBuffer<SPECPACKET,BUFFERLENGTH> SpecBuffer;
void NewSpecial(ULong id,UByte byte1=0, UByte byte2=0, UByte byte3=0, UByte byte4=0, UByte byte5=0);
// bullet stuff
void NewBullet (ULong num, ULong index);
CBuffer<BULENTRY,BUFFERLENGTH> BulletBuffer;
// for collision effects (killlauncher calls)
void NewKillLauncher(UniqueID id);
void ProcessKillLauncherPacket(UByteP);
CBuffer<UIDPACKET,BUFFERLENGTH> UIDSBuffer;
// UI vars
Bool FlyNowFlag;
CBuffer<CHATMESSAGE,NUMBUFFEREDMESSAGES> ChatBuffer;
// UI funcs
Bool UINetworkSelectFly ();
Bool UINewPlayer (char*,char*);
#ifdef MISSSUB_Included
void UILeavingMainSheet ();
void UISendDialogue (char*);
#ifdef SAVEGAME_Included
void UIUpdateMainSheet ();
Bool UISendPrefs (ULong);
#endif
#endif
SLong GetNextAvailableSlot();
void InitH2HPArray();
// general stuff
bool viewtime;
ULong deadplayers; // indicates whether player is dead or alive
Bool ResyncPhase;
Bool WorldSyncPhase;
bool WorldSyncPhaseReady;
Bool Initiator;
char SessionName [SESSIONNAMELEN]; // Session Name
char ServiceName[256]; //serviceprovider
char PlayerName[PLAYERNAMELEN]; //players name
char Password[PASSWORDNAMELEN]; //password for session
char GameName[256]; //name of battlefield
char Messages[MAXPLAYERS][NUMRADIOMESSAGES+1][RADIOMESSAGELEN];
UByte RateDivider; // data rate divider
UByte FrameInc; // same as data rate divider - number of frames in each send/receive cycle
Bool firsttimein; // used to initialise stuff on entry to 3d
Bool realfirsttimein;
Bool synched; // true is all players are synched with aggregator
bool csync; // comms is synched
GameTypes GameType; // co-operative/teamplay/deathmatch
Bool Side; // TRUE if UN, FALSE if red
bool SideSelected;
ULong CurrPlayers; // No. of players in the session
ULong AllocPacket [MAXPLAYERS]; // [n]=UniqueID referenced by mySlot
ULong SuicideTime; // time at which suicide is allowed (5 secs after death)
Bool AllowSuicide;
static H2HPlayerInfo H2H_Player[MAXPLAYERS]; // holds info about players
UByte FrameCount; // Frame count (3 csecs)
ULong ActivePlayers;
UWord damageRandom;
UWord effectRandom;
Bool SendPacketToAggregator(LPACPACKET lpAcPacket);
void SendGonePacket();
void CommitSuicide();
void InitRecBits ();
void ResurrectMe (AirStrucPtr ac, bool suicide);
void SetScore (AirStrucPtr victim, ItemPtr killer);
void ResurrectAircraft (AirStrucPtr, Bool);
void RepairAircraft (AirStrucPtr);
void InitResurrect (AirStrucPtr);
void ProcessPlayerGone(ULong player,Bool in3d);
void PredictMove(AirStruc* ac);
void AddDeltas(AirStruc* AC, Bool sign,UByte);
UByte MakeShiftValue();
void SendNeedResyncMessage();
void ResetState();
void SendResyncMessage();
void BeginSyncPhase();
Bool ReceiveSyncPackets();
Bool CreateDPlayInterface();
void PredictGoodMovement(UWord slot);
Bool InitSyncPhase();
Bool SecondSyncPhase();
void InitGameVars();
void MakeAndSendPacket();
void SetRandomList();
Bool ProcessPlayerMessage(char* message,ULong size,ULong from);
Bool ProcessSystemMessage(char* message);
void ProcessDeltaPacket (LPACPACKET Packet,ULong playerID);
void ProcessExtraPacket (LPACPACKET Packet,ULong playerID);
void ProcessExtraPacket (LPACPACKET, AirStrucPtr, ULong);
void StorePacket (LPAGGSENDPACKET packet);
void MakeDeltaPacket (LPBASICPACKET packet);
void MakeExtraPacket (LPBASICPACKET packet, Bool replay);
void UpdateDeltas(LPACPACKET lpAcPacket);
void UpdatePredictedAC(LPACPACKET lpAcPacket);
UByte MakeCollPacket(LPBASICPACKET, UByte);
UByte MakeUIDSPacket(LPBASICPACKET, UByte);
UByte MakeSpecialPacket(LPBASICPACKET, UByte);
UByte MakeBulletPacket(LPBASICPACKET, UByte);
void MakeSpecialBulletPacket(LPBASICPACKET);
void MakeControlSurfacePacket(LPBASICPACKET);
void CountPlayers(bool);
Bool UISendFlyNow();
void InitMainSheetInfo();
void ProcessInfoPackets();
void SetUpPlayersAC();
Bool JoinGame();
void AddPlayerToGame(ULong pid,ULong actype,ULong id);
Bool Joining;
void SendEnteringGameMessage();
// DPID of player to chat to OR, 0=chat to all, 1=chat to myteam
ULong sendtowho;
void InitBuffers();
void ResetDeltas();
UByte ProcessCollisionPacket(UByteP, AirStrucPtr, ULong);
UByte ProcessUIDSPacket(UByteP, ULong);
UByte ProcessSpecialPacket(UByteP, AirStrucPtr, ULong);
UByte ProcessBulletPacket(UByteP, AirStrucPtr);
SLong GetVal(UByte src,UByte shift);
Bool Lobbied;
Bool LaunchedByLobbyCheck();
Bool ConnectToLobby();
Bool FinishLobbySetup();
bool PossibleLobby;
void SetRandomListPos();
Bool StartCommsSession();
Bool SetUpPlayerInfo(char* name);
LPVISITORINFO VisitorsBook;
void AddNameToVisitorsBook(char* name);
void RemoveNameFromVisitorsBook(char* name);
void ToggleVisitorStatus(char* name);
void SendUpdateToVisitorsBook(char* name,Bool status);
Bool PossTransmitColl(ItemPtr item,ItemPtr target,SLong&);
void DeleteLobbyInfo();
Bool GameRunning;
void DeleteVisitorBook();
void NewNearMiss(AirStrucPtr trg, AirStrucPtr hitter);
void ProcessNearMiss(UByteP);
void CheckPassword(char* pword,char* name,ULong player);
Bool SetUpPlayer();
ULong AttemptToJoin();
Bool SlotFree(int pos,int squadron);
Bool AllPlayersHaveSlots();
void DisplayChatDialogue(char*, char*);
void DisplayPlayerInfo();
UByte MainSheetCount;
Bool ReceiveNextMessageToMe(char*&Data, ULong& Length, ULong& from,ULong flags);
void ProcessAggregatedPacket(char* packet);
void CopyPacket (AirStrucPtr, LPACPACKET);
COORDS3D* GetGoodACPosition(ItemBasePtr ac);
void NewAeroDevAction(UByte devID,SWord Attractor);
void ProcessPlayerSlotRequest(char* message,ULong from);
Bool SendSlotRequest(int, int);
Bool ReceiveSlotRequestOK();
void ProcessSlotInfoUpdate(char* pack);
Bool GetGameDetails();
void SendGameDetailsRequest();
Bool ReceiveGameDetails();
void SendGameDetails(ULong);
UByte GameIndex;
void FillCSQuickStruc();
Bool UpdatePlayerInfo();
bool SendMyPlayerInfo(bool request);
void ResetDeadPlayers(AirStrucPtr ac);
void ProcessPrefsPacket(char* pack);
void CheckPacketSizes();
void GetBattlePosition(UByte slot);
Bool JustJoined;
Bool LeaveCommsFlag;
Bool HostQuitFlag;
Bool SwitchPlayerACToAIAC(AirStrucPtr AC);
Bool SwitchAIACToPlayerAC(AirStrucPtr AC, ULong slot);
void FillHistBuffer(AirStrucPtr ac, ULong slot);
Bool SimulateExitKey;
bool hitResurrect;
void NewWingmanCommand(UByte decision, UByte command, UniqueID trg);
UByte ProcessWingmanCommand(UniqueID id1, UniqueID id2, ULong slot);
void Process1stAIACPositionPacket(LPACPACKET,UByte);
void Process2ndAIACPositionPacket(LPACPACKET,UByte);
void Make1stAIACPositionPacket(LPACPACKET p);
void Make2ndAIACPositionPacket(LPACPACKET p);
void AddAIACToPositionList(AirStrucPtr AC);
void DeleteMyAIACPositionToSendList();
void UpdateACFromPositionList(LPACPOSENTRY p);
// used when AI AC has finished combat and a position update is being sent to other players.
// Possibly more than one AC per player - but only one will be sent at a time (but there could
// be bloody packet loss!!)
LPACPOSENTRY AIACPositions[MAXPLAYERS];
void DeleteAIACPositionsList();
void DeleteEntryFromAIACPositionsList(LPACPOSENTRY p,UByte slot);
// list of AI AC that I need to send positions for.
LPACPOSENTRY MyAIACPositionsToSend;
Bool UpdateFrag;
Bool UpdateMission;
bool FragChanged;
void SendCSQuickStrucToPlayers(Bool init);
void UpdateCSQuick(UByte* pack,ULong num);
void SendCS(UByte* info, ULong size, Bool init);
Bool GetCS();
void SendCSRequest();
void SendACDetails();
Bool GetACDetails();
void SendMobDetails();
Bool GetMobDetails();
Bool SyncCommsWorld();
void MakeAnimPack(ULong num,UByteP pack,ShapeNum shape);
void ProcessAnimPack(UByteP pack,ItemPtr item);
Bool GetNumAnims(ULong type,ULong& num);
Bool GetAllAnims(ULong type, ULong need, ULong& got);
void SendNumAnims(ULong num,ULong type);
void SendAnimData(ULong type,ULong num,UniqueID id);
Bool GetSyncData(ULong type,ULong num,ULong& got);
void ProcessACData(UByteP pack);
void ProcessMobData(UByteP pack);
bool SendMyMessages(bool request);
void ReceiveMessages(char*,ULong);
void SendGotWorldMessage();
void SaveRadioMessages();
Bool LoadRadioMessages();
void InitMessages();
bool UpdateMessages();
Bool DisplayInfo;
void OwnerChange(ULong newownerid, AirStrucPtr AIAC);
void ProcessOwnerChangePacket(UByteP);
void InitialiseOwners();
void OwnerChangeDecision(AirStrucPtr me, AirStrucPtr him);
void SelectPlayerToChatTo(ULong player);
void ResetAllocPacket();
void ProcessBFieldInfo(char* info,ULong& bfctrl, FileNum& filelist);
void SendBFieldsToPlayers(bool request);
void ResetCommsGame();
void ExitCommsAndReplay3D();
void CommsMessage(unsigned int mess);
Bool UpdateMissionConditions();
Bool SendMissionConditions(bool request);
void ProcessConditionsPacket(char* message);
void DisplayPlayerJoiningMessage(ULong slot);
bool SendSaveGame(bool score, bool startup);
bool ReceiveSaveGame(bool startup,ULong num,ULong size);
void UpdateSaveGame(UByte* savegamedata,char* data);
bool SaveDummyCommsSaveGame(UByte* data,ULong size);
void GetCommsSavename(char* b);
void GetLastSaveName(char* b);
bool LoadDummySavegame(char* name);
bool singlesession;// if service provider is serial/modem or tcp
// then should be only one session to connect to
// dont bother enumerating sessions
Bool JoinComms();
Bool FindGoodSession();
char* GetPlayerMessage(ULong index);
char* GetPlayerName(ULong);
ULong GetPlayerNumber(ULong);
inline ULong DPID2Slot(ULong id);
inline ULong UID2Slot(UWord id);
ULong UID_2Slot(UWord id);
void ProcessUIDSPacket(LPBASICPACKET p,ULong slot);
void NewUIDSPacket(UniqueID id1,UniqueID id2,UByte code);
void GetUIDSFromPacket(UniqueID& id1, UniqueID& id2,UByteP);
struct SYNCDATA
{
bool resettime;
bool sentinfo;
ULong wsmneeded;
ULong wsmgot;
UByte stage;
ULong wsrneeded;
ULong wsrgot;
ULong itemstage;
ULong mobstage;
ULong acstage;
ULong deadstage;
};
SYNCDATA SyncData;
void InitSyncData(bool startup);
void CalcVels(UByte slot=0,UByte pframes=0);
UByte velcounter;
void NewPlayerMessage(UByte message);
void ProcessPlayerMessagePacket(UByteP,ULong);
void DisplayPlayerMessage(ItemPtr victim, ItemPtr hitter, UByte script_type,UByte messnum=0);
enum Script_Type
{
ST_PLAYERKILLEDCOMMS=0,
ST_PLAYERKILLEDPLAYER,
ST_PLAYERKILLEDFRIENDLY,
ST_PLAYERKILLEDENEMY,
ST_PLAYERLEFTGAME,
ST_PLAYERJOINEDGAME,
ST_PLAYERJOINING,
ST_PLAYERSELACCEL,
ST_PLAYERDESELACCEL,
ST_PLAYERMESSAGE
};
ULong CommsTimeoutLength; // in ms
bool MsgRecipientAll;
bool CommsGameSync();
void ProcessEjectPacket(AirStrucPtr ac);
void ProcessGuestLeavingMessage(ULong from);
void NewShapePacket(UWord,UWord);
void ProcessNewShapePacket(UByteP);
UByte CommsKiller[MAXPLAYERS];
void ProcessResyncPacket(LPACSTATEPACKET,ULong);
UByte resyncsgot;
bool RestartWorldSync;
void SendRestartWorldSyncMessage();
void SendDeadStream();
bool GetDeadStream();
void SendACArray();
bool GetACArray();
void ProcessACArrayPacket(UByte*);
bool GetNumDeadBlocks(ULong& num,int& dtime);
bool GetAllDeadBlocks(ULong need, ULong& got);
void SendPilotsStatus(bool single,ULong reqfrom=0,int sqnum=0, UByte pos=0);
bool GetPilotsStatus();
void ProcessPilotStatusPacket(bool single,UByteP p,int size);
char* CommsPacketPtr;
ULong CommsPacketLength;
bool SendCampaignStruc(bool startup);
bool ReceiveCampaignStruc();
void ClearPackages();
bool ResetSync;
bool resetreceivesync;
void InitialFlagReset();
void SendAccelGearUpMessage();
void ProcessAccelGearUpPacket();
enum AccelTypeComms
{
ACCEL_NONE=0,
ACCEL_FORWARD,
ACCEL_NEXTWP,
ACCEL_MESSAGESUBJECT,
ACCEL_MISSIONIP,
ACCEL_HOME,
ACCEL_WP_NEXTWP,
ACCEL_WP_HIGHLIGHTED_WP
};
AccelTypeComms AccelComms;
void NewWPMessage(UniqueID wp);
void ProcessNewWPPacket(UByteP, AirStrucPtr);
bool PlayerSync;
void SendAAAList();
bool GetAAAList();
void ProcessAAAPacket(char* packet);
void SendBackupRandomList(bool request);
void Process_PM_RandomList(char* packet);
bool GetRandomList();
bool resurrectend;
SByte joiningplayerslot;
void ResetCommsSurfaces();
bool resyncbar;
UByte PacketLength(ULong ID);
void ProcessResurrectPacket(AirStrucPtr);
void ProcessResurrectEndPacket(AirStrucPtr);
void ProcessLandedEffectPacket(UByteP, AirStrucPtr);
void ProcessAeroDevicePacket(UByteP, AirStrucPtr);
void ProcessDeathMoveEffectPacket(UByteP);
void ProcessSpecialBulletPacket(AirStrucPtr);
void MakeEmptyPacket(LPBASICPACKET, UByte);
void ClearDeadPlayersPackets(UByte);
void ExpandAggPacket(LPAGGSENDPACKET, LPAGGSENDPACKET);
void ProcessControlSurfacePacket(UByteP);
void SendFlyRequest();
ULong FlyRequestTimeout;
void Process_PM_RandRequest();
void Process_PM_PlayerUpdate(char*);
void Process_PM_ImHere(char*,ULong);
bool Process_PM_PlayerQuit(ULong);
void Process_PM_Message(char*);
void Process_PM_DataRequest(ULong);
void Process_PM_ScreenChange(ULong,ULong);
void Process_PM_PrefsData(char*);
bool Process_PM_FlyNow();
void Process_PM_PlayerLeavingGame(ULong);
void Process_PM_IAmIn(char*,ULong);
void Process_PM_Password(char*,ULong);
void Process_PM_VisitorUpdate(char*);
bool Process_PM_NeedResync();
void Process_PM_PrefsRequest(ULong);
void Process_PM_BfieldsRequest();
void Process_PM_CSQuickRequest(ULong);
void Process_PM_SaveGame(char*);
void Process_PM_Resync(char*,ULong);
void Process_PM_CSStruc(char*,bool);
void AddChatMessageToBuffer(char*,char*);
void UpdateChatBox();
Bool LobbyConnect();
inline bool CommsOrReplay();
void MoveSurfacesToZero();
void MoveSurfaceToZero(int&);
void AttemptToProcessExtraPacket();
void SendImHereMessage();
bool ValidService(char*);
void SendStatusChange(ULong);
UByte LosePackets;
UByte clearbuffertime;
bool ReceivePacketWithReRequest(ULong, ULong, char*&, ULong&, ULong);
bool TimeoutReceive(ULong, char*&, ULong&);
void CheckForResend();
bool SpookyGhostMode;
ULong BufferSize;
void BackupGhost();
void BackupSeen();
void CheckGhost();
void CheckSeen();
void UpdateBomberGhost();
void UpdateBomberSeen();
DELTARECORD DeltasToApply[MAXPLAYERS][3];// 3 is max data rate for BoB
UByte DeltaIndex;
void ApplyPartialDeltas();
void AddDeltasToApply(LPACPACKET, ULong);
void CalcAndAddPartialDelta(SLong,ULong, ULong);
void CheckSendQueue();
void ResetAllAIFields(AirStrucPtr);
void NewEngineRPMPacket(UWord);
void ProcessEngineRPMPacket(UByteP);
void NewEngineAnimPacket();
void ProcessEngineAnimPacket(UByteP, ULong);
bool SendMessageToGroup(char*, ULong, bool onego=false);
bool SendMessageToPlayer(char*, ULong, ULong, bool onego=false);
bool SendCommsMessage(char*, ULong, ULong,bool onego=false);
bool SendRequestMessage(char* data, ULong, bool onego=false);
void ProcessPlayerMessages();
UByteP listptr;
// stage with flags representing
// [x][0] - I done this stage and have info to send
// [x][1] - I have received a request for this info, send as soon as stage done
bool CommsStage[STAGE_MAX][2];
void WaitForPlayersUniqueIDs();
void SendMyUniqueID(UWord);
void Process_PM_UniqueID(char*, ULong);
bool GotAllPlayersUniqueIDs();
void SendIDRequest();
void ProcessIDRequest();
CBuffer<PLAYERAGGCHECK,BUFFERLENGTH> PlayerAggCheck;
void AddPacketToCheckBuffer(LPAGGSENDPACKET);
UWord BFieldToProcess;
void StoreReceivedBField(char*, ULong);
bool ProcessRequiredBFieldPacket(ULong& bfctrl, FileNum& filelist);
void JumpToWebSite();
bool FirstResurrectFrame;
UByte HostCollPrefs;
void BackupHostPrefs();
void RestoreHostPrefs();
LPDEADPILOT deadpilotlist;
void ClearDeadPilots();
void NewDeadPilot(int squadron, UByte position);
bool IsPilotDead(int squad, UByte pos);
void UpdateDeadPilots(AirStrucPtr);
void CheckAnimPack(UByteP);
struct NiceColours
{
bool GEffects;
bool InjuryEffects;
bool WhiteOuts;
bool ACNames;
bool Clouds;
};
NiceColours effects;
void BombCheck(AirStrucPtr);
bool GetAllGoResponses();
void SendGoResponse();
bool GetHostGo();
void SendHostGo();
void EmptyAggregatorQueue();
bool AllPlayersStillReady();
bool IsThereKillLauncher();
UByte MakeKillLauncherPacket(LPBASICPACKET, UByte);
};
extern DPlay _DPlay;
void SendInitPacket ();
void SendInit2Packet ();
#endif
| [
"[email protected]"
] | |
276ed7c3c9a8f29b2eb2e6c536a13b457853e18a | 5a60d60fca2c2b8b44d602aca7016afb625bc628 | /aws-cpp-sdk-frauddetector/include/aws/frauddetector/model/DeleteDetectorVersionResult.h | 377eaf7163e50d784518268232a737d7f203e8fc | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | yuatpocketgems/aws-sdk-cpp | afaa0bb91b75082b63236cfc0126225c12771ed0 | a0dcbc69c6000577ff0e8171de998ccdc2159c88 | refs/heads/master | 2023-01-23T10:03:50.077672 | 2023-01-04T22:42:53 | 2023-01-04T22:42:53 | 134,497,260 | 0 | 1 | null | 2018-05-23T01:47:14 | 2018-05-23T01:47:14 | null | UTF-8 | C++ | false | false | 854 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/frauddetector/FraudDetector_EXPORTS.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace FraudDetector
{
namespace Model
{
class DeleteDetectorVersionResult
{
public:
AWS_FRAUDDETECTOR_API DeleteDetectorVersionResult();
AWS_FRAUDDETECTOR_API DeleteDetectorVersionResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
AWS_FRAUDDETECTOR_API DeleteDetectorVersionResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
};
} // namespace Model
} // namespace FraudDetector
} // namespace Aws
| [
"[email protected]"
] | |
aa33bc9a44f2b82b115cb128ce254ade5f93886f | 7fd64b86c7e8f63d6238fe93ccf6e62a4b8ebc66 | /codeforces/545/D.cpp | 252d956b4f157494bfaa4a1695ff1508db17e2b4 | [] | no_license | Mohammad-Yasser/harwest | 775ba71303cc2849f71e82652263f31e79bd8e04 | d01834a9a41c828c8c548a115ecefd77ff2d6adc | refs/heads/master | 2023-02-02T23:37:54.186079 | 2013-09-19T19:28:00 | 2020-12-21T14:30:32 | 323,233,072 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
// I doubt this solution can work for a D problem. :D
// But this contest isn't rated for me, so why would I be so serious :v
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; ++i)
cin >> arr[i];
sort(arr, arr + n);
int ans = 0;
long long sum = 0;
for (int idx = 0; idx < n; ++idx)
if (arr[idx] >= sum) sum += arr[idx], ++ans;
cout << ans;
}
| [
"[email protected]"
] | |
7dcd08312a0a0311b79785e51b475cbc9f96c4f4 | 8f288ba858e5915dcecd4ee9559967b0291516b1 | /gameEngine/Sprite.h | 8339c82c5465948dde75e7efe6330ad3a2f32e40 | [
"Apache-2.0"
] | permissive | huangxizhi/opengl_tutorial | a61a3ea8d03ec2da855114f988952811f0929038 | 204323c2fbf91542aeca6412b933bac4b5f36f2b | refs/heads/master | 2021-06-10T05:06:24.196993 | 2016-12-20T11:41:31 | 2016-12-20T11:41:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | h | #pragma once
#include <GL\glew.h>
#include "GLTexture.h"
#include <string>
namespace Engine {
class Sprite
{
public:
Sprite();
~Sprite();
void init(float x, float y, float width, float height, std::string texturePath);
void draw();
private:
float _x;
float _y;
float _width;
float _height;
GLTexture _texture;
GLuint _vboID;
};
}
| [
"[email protected]"
] | |
d142996709b0c836e11bc28f03c52d65ba5331d4 | 46d4705d311387e0bc7b614271353bd445b9a776 | /src/pow.cpp | c08cd671bbd471b5d000200045ef4b732a3ac11c | [
"MIT"
] | permissive | VersusCoin/versus-dev | 12e2fd8f2ba730e59e7e4b454787afb7b4a79ec3 | 333a57584886de67d2dd261fb5672714e9dd20a0 | refs/heads/master | 2021-05-05T05:48:30.359486 | 2018-01-24T11:55:56 | 2018-01-24T11:55:56 | 118,751,174 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,352 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "arith_uint256.h"
#include "chain.h"
#include "chainparams.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include <math.h>
unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const Consensus::Params& params) {
const CBlockIndex *BlockLastSolved = pindexLast;
const CBlockIndex *BlockReading = pindexLast;
uint64_t PastBlocksMass = 0;
int64_t PastRateActualSeconds = 0;
int64_t PastRateTargetSeconds = 0;
double PastRateAdjustmentRatio = double(1);
arith_uint256 PastDifficultyAverage;
arith_uint256 PastDifficultyAveragePrev;
double EventHorizonDeviation;
double EventHorizonDeviationFast;
double EventHorizonDeviationSlow;
uint64_t pastSecondsMin = params.nPowTargetTimespan * 0.025;
uint64_t pastSecondsMax = params.nPowTargetTimespan * 7;
uint64_t PastBlocksMin = pastSecondsMin / params.nPowTargetSpacing;
uint64_t PastBlocksMax = pastSecondsMax / params.nPowTargetSpacing;
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); }
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
PastBlocksMass++;
PastDifficultyAverage.SetCompact(BlockReading->nBits);
if (i > 1) {
// handle negative arith_uint256
if(PastDifficultyAverage >= PastDifficultyAveragePrev)
PastDifficultyAverage = ((PastDifficultyAverage - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev;
else
PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - PastDifficultyAverage) / i);
}
PastDifficultyAveragePrev = PastDifficultyAverage;
PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();
PastRateTargetSeconds = params.nPowTargetSpacing * PastBlocksMass;
PastRateAdjustmentRatio = double(1);
if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds);
}
EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(28.2)), -1.228));
EventHorizonDeviationFast = EventHorizonDeviation;
EventHorizonDeviationSlow = 1 / EventHorizonDeviation;
if (PastBlocksMass >= PastBlocksMin) {
if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast))
{ assert(BlockReading); break; }
}
if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
BlockReading = BlockReading->pprev;
}
arith_uint256 bnNew(PastDifficultyAverage);
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
bnNew *= PastRateActualSeconds;
bnNew /= PastRateTargetSeconds;
}
if (bnNew > UintToArith256(params.powLimit)) {
bnNew = UintToArith256(params.powLimit);
}
return bnNew.GetCompact();
}
unsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const Consensus::Params& params) {
/* current difficulty formula, versus - DarkGravity v3, written by Evan Duffield - [email protected] */
const CBlockIndex *BlockLastSolved = pindexLast;
const CBlockIndex *BlockReading = pindexLast;
int64_t nActualTimespan = 0;
int64_t LastBlockTime = 0;
int64_t PastBlocksMin = 24;
int64_t PastBlocksMax = 24;
int64_t CountBlocks = 0;
arith_uint256 PastDifficultyAverage;
arith_uint256 PastDifficultyAveragePrev;
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) {
return UintToArith256(params.powLimit).GetCompact();
}
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
CountBlocks++;
if(CountBlocks <= PastBlocksMin) {
if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1); }
PastDifficultyAveragePrev = PastDifficultyAverage;
}
if(LastBlockTime > 0){
int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());
nActualTimespan += Diff;
}
LastBlockTime = BlockReading->GetBlockTime();
if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
BlockReading = BlockReading->pprev;
}
arith_uint256 bnNew(PastDifficultyAverage);
int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing;
if (nActualTimespan < _nTargetTimespan/3)
nActualTimespan = _nTargetTimespan/3;
if (nActualTimespan > _nTargetTimespan*3)
nActualTimespan = _nTargetTimespan*3;
// Retarget
bnNew *= nActualTimespan;
bnNew /= _nTargetTimespan;
if (bnNew > UintToArith256(params.powLimit)){
bnNew = UintToArith256(params.powLimit);
}
return bnNew.GetCompact();
}
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
unsigned int retarget = DIFF_DGW;
// mainnet/regtest share a configuration
if (Params().NetworkIDString() == CBaseChainParams::MAIN || Params().NetworkIDString() == CBaseChainParams::REGTEST) {
if (pindexLast->nHeight + 1 >= 700) retarget = DIFF_DGW;
else retarget = DIFF_BTC;
// testnet -- we want a lot of coins in existance early on
} else {
if (pindexLast->nHeight + 1 >= 650) retarget = DIFF_DGW;
else retarget = DIFF_BTC;
}
// Default Bitcoin style retargeting
if (retarget == DIFF_BTC)
{
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
{
if (params.fPowAllowMinDifficultyBlocks)
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 2.5 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Go back by what we want to be 1 day worth of blocks
int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1);
assert(nHeightFirst >= 0);
const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);
assert(pindexFirst);
return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}
// Retarget using Kimoto Gravity Wave
else if (retarget == DIFF_KGW)
{
return KimotoGravityWell(pindexLast, params);
}
// Retarget using Dark Gravity Wave 3
else if (retarget == DIFF_DGW)
{
return DarkGravityWave(pindexLast, params);
}
return DarkGravityWave(pindexLast, params);
}
// for DIFF_BTC only!
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
LogPrintf(" nActualTimespan = %d before bounds\n", nActualTimespan);
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
arith_uint256 bnNew;
arith_uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
/// debug print
LogPrintf("GetNextWorkRequired RETARGET\n");
LogPrintf("params.nPowTargetTimespan = %d nActualTimespan = %d\n", params.nPowTargetTimespan, nActualTimespan);
LogPrintf("Before: %08x %s\n", pindexLast->nBits, bnOld.ToString());
LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString());
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return error("CheckProofOfWork(): nBits below minimum work");
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return error("CheckProofOfWork(): hash doesn't match nBits");
return true;
}
arith_uint256 GetBlockProof(const CBlockIndex& block)
{
arith_uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for a arith_uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
arith_uint256 r;
int sign = 1;
if (to.nChainWork > from.nChainWork) {
r = to.nChainWork - from.nChainWork;
} else {
r = from.nChainWork - to.nChainWork;
sign = -1;
}
r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
if (r.bits() > 63) {
return sign * std::numeric_limits<int64_t>::max();
}
return sign * r.GetLow64();
}
| [
"[email protected]"
] | |
0fc205f9516dbc626c588e32901a76b5e9caec4a | ec681d943400d1ce01c1de6ccdea5245c3a87646 | /cpp.lotdd/c7/7/libraryTest/PersistenceTest.cpp | 175e80c623ce99bd1cdb639d112ac75be9bf9e14 | [] | no_license | hechenyu/book_code | 84ca011308c9d4faaff9050a8bdcc4cbbd0ea1cc | 4e1501bb1918f55be60bed1bd03f3441f0bdc66b | refs/heads/master | 2020-05-21T04:34:03.457535 | 2017-07-12T11:37:40 | 2017-07-12T11:37:40 | 65,210,563 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,574 | cpp | #include "PersistenceTest.h"
#include "gmock/gmock.h"
#include <memory>
#include "KeyedMemoryPersistence.h"
#include "TestSerializable.h"
using namespace std;
using namespace testing;
TEST_P(PersistenceTest, IsEmptyOnCreation)
{
ASSERT_THAT(persister->Size(), Eq(0u));
}
TEST_P(PersistenceTest, SizeSetToOneOnFirstAdd)
{
persister->Add(*objectWithId1);
ASSERT_THAT(persister->Size(), Eq(1u));
}
TEST_P(PersistenceTest, SizeIncrementsWithEachAdd)
{
persister->Add(*objectWithId1);
persister->Add(*objectWithId2);
ASSERT_THAT(persister->Size(), Eq(2u));
}
TEST_P(PersistenceTest, ReturnsNullPointerWhenItemNotFound)
{
auto_ptr<TestSerializable> found = persister->Get("1");
TestSerializable* serializable = found.get();
ASSERT_THAT(serializable, IsNull());
}
TEST_P(PersistenceTest, AddedItemCanBeRetrievedById)
{
persister->Add(*objectWithId1);
ASSERT_THAT(*persister->Get("1"), Eq(*objectWithId1));
}
TEST_P(PersistenceTest, GetAnswersNullWhenNoMatchingEntries)
{
ASSERT_THAT(persister->Get("1").get(), IsNull());
};
TEST_P(PersistenceTest, RetrievedItemIsNewInstance)
{
persister->Add(*objectWithId1);
ASSERT_FALSE(objectWithId1 == persister->Get("1").get());
}
TEST_P(PersistenceTest, CanPersistMultipleObjects)
{
persister->Add(*objectWithId1);
persister->Add(*objectWithId2);
ASSERT_THAT(*(persister->Get("1")), Eq(*objectWithId1));
ASSERT_THAT(*(persister->Get("2")), Eq(*objectWithId2));
}
bool NameMatcher(Serializable& each, const string& name)
{
return (dynamic_cast<TestSerializable&>(each)).Name() == name;
}
TEST_P(PersistenceTest, MatchesAnswersTrueWithMatchingEntries)
{
persister->Add(*objectWithId1);
persister->Add(*objectWithId2);
string object1Name = objectWithId1->Name();
bool exists = persister->Matches(NameMatcher, object1Name);
ASSERT_TRUE(exists);
};
TEST_P(PersistenceTest, MatchesAnswersFalseWhenNoMatchingEntries)
{
bool exists = persister->Matches(NameMatcher, "don't match anything");
ASSERT_FALSE(exists);
};
TEST_P(PersistenceTest, FindAllMatching)
{
TestSerializable coolidge("Calvin", "1");
TestSerializable langr("Jeff", "2");
TestSerializable lynne("Jeff", "3");
persister->Add(coolidge);
persister->Add(langr);
persister->Add(lynne);
vector<Serializable*> matches;
persister->FindAllMatching(NameMatcher, "Jeff", matches);
ASSERT_THAT(matches.size(), Eq(2u));
};
| [
"[email protected]"
] | |
439ab30c46e91f357985e6577d26c4dc33e6d0f6 | d51d72f1b6e834d89c8551bb07487bed84cdaa31 | /src/output/osg/customCode/osg/Array_pmoc.hpp | acb5969ee9298cf6986c54072535916c33963364 | [] | no_license | wangfeilong321/osg4noob | 221204aa15efa18f1f049548ad076ef27371ecad | 99a15c3fd2523c4bd537fa3afb0b47e15c8f335a | refs/heads/master | 2021-01-12T20:00:43.854775 | 2015-11-06T15:37:01 | 2015-11-06T15:37:01 | 48,840,543 | 0 | 1 | null | 2015-12-31T07:56:31 | 2015-12-31T07:56:31 | null | UTF-8 | C++ | false | false | 2,966 | hpp | #ifndef osg_Array_customHPP
#define osg_Array_customHPP 1
//includes
#include <osg/Array_pmoc.hpp>
#include <QObject>
#include <osg/Array>
#include <osg/Array_pmoc.hpp>
namespace osg{
class QMLValueVisitor: public QReflect_ValueVisitor
{
Q_OBJECT
public:
QMLValueVisitor(pmoc::Instance *i=0,QObject* parent=0);
virtual QQuickItem * connect2View(QQuickItem*);
public slots:
virtual void updateModel();
};
class MetaQMLValueVisitor :public MetaQReflect_ValueVisitor{};
}
Q_DECLARE_METATYPE(osg::QMLValueVisitor)
#include <osg/Array_pmoc.hpp>
#include <QObject>
#include <osg/Array>
#include <osg/Array_pmoc.hpp>
namespace osg{
class QMLConstValueVisitor: public QReflect_ConstValueVisitor
{
Q_OBJECT
public:
QMLConstValueVisitor(pmoc::Instance *i=0,QObject* parent=0);
virtual QQuickItem * connect2View(QQuickItem*);
public slots:
virtual void updateModel();
};
class MetaQMLConstValueVisitor :public MetaQReflect_ConstValueVisitor{};
}
Q_DECLARE_METATYPE(osg::QMLConstValueVisitor)
#include <osg/Array_pmoc.hpp>
#include <QObject>
#include <osg/Array>
#include <osg/Array_pmoc.hpp>
namespace osg{
class QMLArrayVisitor: public QReflect_ArrayVisitor
{
Q_OBJECT
public:
QMLArrayVisitor(pmoc::Instance *i=0,QObject* parent=0);
virtual QQuickItem * connect2View(QQuickItem*);
public slots:
virtual void updateModel();
};
class MetaQMLArrayVisitor :public MetaQReflect_ArrayVisitor{};
}
Q_DECLARE_METATYPE(osg::QMLArrayVisitor)
#include <osg/Array_pmoc.hpp>
#include <QObject>
namespace osg{
class QReflect_VertexBufferObject;
} ;
#include <osg/Array>
#include <osg/BufferObject>
#include <osg/BufferObject_pmoc.hpp>
#include <osg/Array_pmoc.hpp>
namespace osg{
class QMLArray: public QReflect_Array
{
Q_OBJECT
public:
QMLArray(pmoc::Instance *i=0,QObject* parent=0);
virtual QQuickItem * connect2View(QQuickItem*);
public slots:
virtual void updateModel();
};
class MetaQMLArray :public MetaQReflect_Array{};
}
Q_DECLARE_METATYPE(osg::QMLArray)
#include <osg/Array_pmoc.hpp>
#include <QObject>
#include <osg/Array>
#include <osg/Array_pmoc.hpp>
namespace osg{
class QMLConstArrayVisitor: public QReflect_ConstArrayVisitor
{
Q_OBJECT
public:
QMLConstArrayVisitor(pmoc::Instance *i=0,QObject* parent=0);
virtual QQuickItem * connect2View(QQuickItem*);
public slots:
virtual void updateModel();
};
class MetaQMLConstArrayVisitor :public MetaQReflect_ConstArrayVisitor{};
}
Q_DECLARE_METATYPE(osg::QMLConstArrayVisitor)
#include <osg/Array_pmoc.hpp>
#include <QObject>
#include <osg/Array>
#include <osg/Array_pmoc.hpp>
#include <osg/Array_pmoc.hpp>
namespace osg{
class QMLIndexArray: public QReflect_IndexArray
{
Q_OBJECT
public:
QMLIndexArray(pmoc::Instance *i=0,QObject* parent=0);
virtual QQuickItem * connect2View(QQuickItem*);
public slots:
virtual void updateModel();
};
class MetaQMLIndexArray :public MetaQReflect_IndexArray{};
}
Q_DECLARE_METATYPE(osg::QMLIndexArray)
#endif //osg_Array_customHPP
| [
"[email protected]"
] | |
a62dadfd7091cd8497071c85bd7193c8b287220e | 42bcc124b6db7bc72ecfccd7f675eb79532cf1e5 | /CvGameCoreDLL_Expansion2/CvUnitMovement.cpp | c5538d009c4d5f1df9c777f5ecb078f412a0f970 | [] | no_license | iskaandismet/Iska-s-DLL-Changes | d7c0572be30c6e62285781864eb42e1e0397aad9 | fec2751e56876b37f2e693ef6f565fb2f1622bed | refs/heads/master | 2022-12-31T21:45:48.534407 | 2020-10-27T19:39:20 | 2020-10-27T19:39:20 | 257,297,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,892 | cpp | #include "CvGameCoreDLLPCH.h"
#include "CvPlot.h"
#include "CvCity.h"
#include "CvUnit.h"
#include "CvGlobals.h"
#include "CvUnitMovement.h"
#include "CvGameCoreUtils.h"
// ---------------------------------------------------------------------------
void CvUnitMovement::GetCostsForMove(const CvUnit* pUnit, const CvPlot* pFromPlot, const CvPlot* pToPlot, int iBaseMoves, int& iRegularCost, int& iRouteCost, int& iRouteFlatCost)
{
CvPlayerAI& kPlayer = GET_PLAYER(pUnit->getOwner());
CvPlayerTraits* pTraits = kPlayer.GetPlayerTraits();
bool bFasterAlongRiver = pTraits->IsFasterAlongRiver();
bool bFasterInHills = pTraits->IsFasterInHills();
bool bIgnoreTerrainCost = pUnit->ignoreTerrainCost();
//int iBaseMoves = pUnit->baseMoves(isWater()?DOMAIN_SEA:NO_DOMAIN);
TeamTypes eUnitTeam = pUnit->getTeam();
CvTeam& kUnitTeam = GET_TEAM(eUnitTeam);
int iMoveDenominator = GC.getMOVE_DENOMINATOR();
bool bRiverCrossing = pFromPlot->isRiverCrossing(directionXY(pFromPlot, pToPlot));
FeatureTypes eFeature = pToPlot->getFeatureType();
CvFeatureInfo* pFeatureInfo = (eFeature > NO_FEATURE) ? GC.getFeatureInfo(eFeature) : 0;
TerrainTypes eTerrain = pToPlot->getTerrainType();
CvTerrainInfo* pTerrainInfo = (eTerrain > NO_TERRAIN) ? GC.getTerrainInfo(eTerrain) : 0;
if(bIgnoreTerrainCost || (bFasterAlongRiver && pToPlot->isRiver()) || (bFasterInHills && pToPlot->isHills()))
{
iRegularCost = 1;
}
else
{
iRegularCost = ((eFeature == NO_FEATURE) ? (pTerrainInfo ? pTerrainInfo->getMovementCost() : 0) : (pFeatureInfo ? pFeatureInfo->getMovementCost() : 0));
// Hill cost, except for when a City is present here, then it just counts as flat land
if((PlotTypes)pToPlot->getPlotType() == PLOT_HILLS && !pToPlot->isCity())
{
iRegularCost += GC.getHILLS_EXTRA_MOVEMENT();
}
if(iRegularCost > 0)
{
iRegularCost = std::max(1, (iRegularCost - pUnit->getExtraMoveDiscount()));
}
}
// Is a unit's movement consumed for entering rough terrain?
if(pToPlot->isRoughGround() && pUnit->IsRoughTerrainEndsTurn())
{
iRegularCost = INT_MAX;
}
else
{
if(!(bIgnoreTerrainCost || bFasterAlongRiver) && bRiverCrossing)
{
iRegularCost += GC.getRIVER_EXTRA_MOVEMENT();
}
iRegularCost *= iMoveDenominator;
if(pToPlot->isHills() && pUnit->isHillsDoubleMove())
{
iRegularCost /= 2;
}
else if((eFeature == NO_FEATURE) ? pUnit->isTerrainDoubleMove(eTerrain) : pUnit->isFeatureDoubleMove(eFeature))
{
iRegularCost /= 2;
}
}
iRegularCost = std::min(iRegularCost, (iBaseMoves * iMoveDenominator));
if(pFromPlot->isValidRoute(pUnit) && pToPlot->isValidRoute(pUnit) && ((kUnitTeam.isBridgeBuilding() || !(pFromPlot->isRiverCrossing(directionXY(pFromPlot, pToPlot))))))
{
CvRouteInfo* pFromRouteInfo = GC.getRouteInfo(pFromPlot->getRouteType());
CvAssert(pFromRouteInfo != NULL);
int iFromMovementCost = (pFromRouteInfo != NULL)? pFromRouteInfo->getMovementCost() : 0;
int iFromFlatMovementCost = (pFromRouteInfo != NULL)? pFromRouteInfo->getFlatMovementCost() : 0;
CvRouteInfo* pRouteInfo = GC.getRouteInfo(pToPlot->getRouteType());
CvAssert(pRouteInfo != NULL);
int iMovementCost = (pRouteInfo != NULL)? pRouteInfo->getMovementCost() : 0;
int iFlatMovementCost = (pRouteInfo != NULL)? pRouteInfo->getFlatMovementCost() : 0;
iRouteCost = std::max(iFromMovementCost + kUnitTeam.getRouteChange(pFromPlot->getRouteType()), iMovementCost + kUnitTeam.getRouteChange(pToPlot->getRouteType()));
iRouteFlatCost = std::max(iFromFlatMovementCost * iBaseMoves, iFlatMovementCost * iBaseMoves);
}
else if(pUnit->getOwner() == pToPlot->getOwner() && (eFeature == FEATURE_FOREST || eFeature == FEATURE_JUNGLE) && pTraits->IsMoveFriendlyWoodsAsRoad())
{
CvRouteInfo* pRoadInfo = GC.getRouteInfo(ROUTE_ROAD);
iRouteCost = pRoadInfo->getMovementCost();
iRouteFlatCost = pRoadInfo->getFlatMovementCost() * iBaseMoves;
}
else
{
iRouteCost = INT_MAX;
iRouteFlatCost = INT_MAX;
}
TeamTypes eTeam = pToPlot->getTeam();
if(eTeam != NO_TEAM)
{
CvTeam* pPlotTeam = &GET_TEAM(eTeam);
CvPlayer* pPlotPlayer = &GET_PLAYER(pToPlot->getOwner());
// Great Wall increases movement cost by 1
if(pPlotTeam->isBorderObstacle() || pPlotPlayer->isBorderObstacle())
{
if(!pToPlot->isWater() && pUnit->getDomainType() == DOMAIN_LAND)
{
// Don't apply penalty to OUR team or teams we've given open borders to
if(eUnitTeam != eTeam && !pPlotTeam->IsAllowsOpenBordersToTeam(eUnitTeam))
{
iRegularCost += iMoveDenominator;
}
}
}
}
}
// ---------------------------------------------------------------------------
int CvUnitMovement::MovementCost(const CvUnit* pUnit, const CvPlot* pFromPlot, const CvPlot* pToPlot, int iBaseMoves, int iMaxMoves, int iMovesRemaining /*= 0*/)
{
int iRegularCost;
int iRouteCost;
int iRouteFlatCost;
CvAssertMsg(pToPlot->getTerrainType() != NO_TERRAIN, "TerrainType is not assigned a valid value");
if(ConsumesAllMoves(pUnit, pFromPlot, pToPlot))
{
if (iMovesRemaining > 0)
return iMovesRemaining;
else
return iMaxMoves;
}
else if(CostsOnlyOne(pUnit, pFromPlot, pToPlot))
{
return GC.getMOVE_DENOMINATOR();
}
else if(IsSlowedByZOC(pUnit, pFromPlot, pToPlot))
{
if (iMovesRemaining > 0)
return iMovesRemaining;
else
return iMaxMoves;
}
GetCostsForMove(pUnit, pFromPlot, pToPlot, iBaseMoves, iRegularCost, iRouteCost, iRouteFlatCost);
return std::max(1, std::min(iRegularCost, std::min(iRouteCost, iRouteFlatCost)));
}
// ---------------------------------------------------------------------------
int CvUnitMovement::MovementCostNoZOC(const CvUnit* pUnit, const CvPlot* pFromPlot, const CvPlot* pToPlot, int iBaseMoves, int iMaxMoves, int iMovesRemaining /*= 0*/)
{
int iRegularCost;
int iRouteCost;
int iRouteFlatCost;
CvAssertMsg(pToPlot->getTerrainType() != NO_TERRAIN, "TerrainType is not assigned a valid value");
if(ConsumesAllMoves(pUnit, pFromPlot, pToPlot))
{
if (iMovesRemaining > 0)
return iMovesRemaining;
else
return iMaxMoves;
}
else if(CostsOnlyOne(pUnit, pFromPlot, pToPlot))
{
return GC.getMOVE_DENOMINATOR();
}
GetCostsForMove(pUnit, pFromPlot, pToPlot, iBaseMoves, iRegularCost, iRouteCost, iRouteFlatCost);
return std::max(1, std::min(iRegularCost, std::min(iRouteCost, iRouteFlatCost)));
}
// ---------------------------------------------------------------------------
bool CvUnitMovement::ConsumesAllMoves(const CvUnit* pUnit, const CvPlot* pFromPlot, const CvPlot* pToPlot)
{
if(!pToPlot->isRevealed(pUnit->getTeam()) && pUnit->isHuman())
{
return true;
}
if (!pUnit->isEmbarked() && (pToPlot->IsAllowsWalkWater() || pFromPlot->IsAllowsWalkWater()))
{
return false;
}
if(!pFromPlot->isValidDomainForLocation(*pUnit))
{
// If we are a land unit that can embark, then do further tests.
if(pUnit->getDomainType() != DOMAIN_LAND || pUnit->IsHoveringUnit() || pUnit->canMoveAllTerrain() || !pUnit->CanEverEmbark())
return true;
}
// if the unit can embark and we are transitioning from land to water or vice versa
if(pToPlot->isWater() != pFromPlot->isWater() && pUnit->CanEverEmbark())
{
// Is the unit from a civ that can disembark for just 1 MP?
//aa0905766k
if(!pToPlot->isWater() && pFromPlot->isWater() && pUnit->isEmbarked())
{
if(GET_PLAYER(pUnit->getOwner()).GetPlayerTraits()->IsEmbarkedToLandFlatCost() || pUnit->IsEmbarkedToLandFlatCost() )
{
return false;
}
}
//
if(!pUnit->canMoveAllTerrain())
{
return true;
}
}
return false;
}
// ---------------------------------------------------------------------------
bool CvUnitMovement::CostsOnlyOne(const CvUnit* pUnit, const CvPlot* pFromPlot, const CvPlot* pToPlot)
{
if(!pToPlot->isValidDomainForAction(*pUnit))
{
// If we are a land unit that can embark, then do further tests.
if(pUnit->getDomainType() != DOMAIN_LAND || pUnit->IsHoveringUnit() || pUnit->canMoveAllTerrain() || !pUnit->CanEverEmbark())
return true;
}
CvAssert(!pUnit->IsImmobile());
if(pUnit->flatMovementCost() || pUnit->getDomainType() == DOMAIN_AIR)
{
return true;
}
// Is the unit from a civ that can disembark for just 1 MP?
if(!pToPlot->isWater() && pFromPlot->isWater() && pUnit->isEmbarked() && GET_PLAYER(pUnit->getOwner()).GetPlayerTraits()->IsEmbarkedToLandFlatCost())
{
return true;
}
return false;
}
// --------------------------------------------------------------------------------
bool CvUnitMovement::IsSlowedByZOC(const CvUnit* pUnit, const CvPlot* pFromPlot, const CvPlot* pToPlot)
{
if (pUnit->IsIgnoreZOC() || CostsOnlyOne(pUnit, pFromPlot, pToPlot))
{
return false;
}
// Zone of Control
if(GC.getZONE_OF_CONTROL_ENABLED() > 0)
{
IDInfo* pAdjUnitNode;
CvUnit* pLoopUnit;
int iFromPlotX = pFromPlot->getX();
int iFromPlotY = pFromPlot->getY();
int iToPlotX = pToPlot->getX();
int iToPlotY = pToPlot->getY();
TeamTypes unit_team_type = pUnit->getTeam();
DomainTypes unit_domain_type = pUnit->getDomainType();
bool bIsVisibleEnemyUnit = pToPlot->isVisibleEnemyUnit(pUnit);
CvTeam& kUnitTeam = GET_TEAM(unit_team_type);
for(int iDirection0 = 0; iDirection0 < NUM_DIRECTION_TYPES; iDirection0++)
{
CvPlot* pAdjPlot = plotDirection(iFromPlotX, iFromPlotY, ((DirectionTypes)iDirection0));
if(NULL != pAdjPlot)
{
// check city zone of control
if(pAdjPlot->isEnemyCity(*pUnit))
{
// Loop through plots adjacent to the enemy city and see if it's the same as our unit's Destination Plot
for(int iDirection = 0; iDirection < NUM_DIRECTION_TYPES; iDirection++)
{
CvPlot* pEnemyAdjPlot = plotDirection(pAdjPlot->getX(), pAdjPlot->getY(), ((DirectionTypes)iDirection));
if(NULL != pEnemyAdjPlot)
{
// Destination adjacent to enemy city?
if(pEnemyAdjPlot->getX() == iToPlotX && pEnemyAdjPlot->getY() == iToPlotY)
{
return true;
}
}
}
}
pAdjUnitNode = pAdjPlot->headUnitNode();
// Loop through all units to see if there's an enemy unit here
while(pAdjUnitNode != NULL)
{
if((pAdjUnitNode->eOwner >= 0) && pAdjUnitNode->eOwner < MAX_PLAYERS)
{
pLoopUnit = (GET_PLAYER(pAdjUnitNode->eOwner).getUnit(pAdjUnitNode->iID));
}
else
{
pLoopUnit = NULL;
}
pAdjUnitNode = pAdjPlot->nextUnitNode(pAdjUnitNode);
if(!pLoopUnit) continue;
TeamTypes unit_loop_team_type = pLoopUnit->getTeam();
if(pLoopUnit->isInvisible(unit_team_type,false)) continue;
// Combat unit?
if(!pLoopUnit->IsCombatUnit())
{
continue;
}
// At war with this unit's team?
if(unit_loop_team_type == BARBARIAN_TEAM || kUnitTeam.isAtWar(unit_loop_team_type))
{
// Same Domain?
DomainTypes loop_unit_domain_type = pLoopUnit->getDomainType();
if(loop_unit_domain_type != unit_domain_type)
{
// this is valid
if(loop_unit_domain_type == DOMAIN_SEA && unit_domain_type)
{
// continue on
}
else
{
continue;
}
}
// Embarked?
if(unit_domain_type == DOMAIN_LAND && pLoopUnit->isEmbarked())
{
continue;
}
// Loop through plots adjacent to the enemy unit and see if it's the same as our unit's Destination Plot
for(int iDirection2 = 0; iDirection2 < NUM_DIRECTION_TYPES; iDirection2++)
{
CvPlot* pEnemyAdjPlot = plotDirection(pAdjPlot->getX(), pAdjPlot->getY(), ((DirectionTypes)iDirection2));
if(!pEnemyAdjPlot)
{
continue;
}
// Don't check Enemy Unit's plot
if(!bIsVisibleEnemyUnit)
{
// Destination adjacent to enemy unit?
if(pEnemyAdjPlot->getX() == iToPlotX && pEnemyAdjPlot->getY() == iToPlotY)
{
return true;
}
}
}
}
}
}
}
}
return false;
}
| [
"[email protected]"
] | |
c20cace9701c5e79e28f998b9ec0881388ff3ada | 203139f9bf54d3a129e674e1ce704a4242b4a995 | /tool/ADSPTOOL/StdAfx.cpp | d9063d9289890f98b59f7d55bb5be989c2213cf3 | [] | no_license | AlexVangelov/ar168l | 289bf442c2b38839c6a227c782d50830e3ae9eb3 | b995f53c8ccd7e5dab888c4b283e0cdb443a28e9 | refs/heads/master | 2021-01-10T20:11:21.416116 | 2015-03-18T03:03:02 | 2015-03-18T03:03:02 | 8,335,621 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 295 | cpp | // stdafx.cpp : source file that includes just the standard includes
// adsptool.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
4102313a2c2bb15e91023942f6d3ce1dfeea5e60 | a8e026f5a49f848ba647cf947ccf038a7d5c7857 | /Week6_3/src/ImageClass.cpp | dd09087038e21df1a9715db5c156edef03e453fc | [] | no_license | pimtron/vscode_oF | d41b28a2fdda5b4d54a3a02a935321ef5a5f46ec | 4889cd0c1d3a09d81e63a0a596f1f5a779211d91 | refs/heads/master | 2021-01-06T21:30:11.448491 | 2020-04-05T14:39:53 | 2020-04-05T14:39:53 | 241,485,365 | 0 | 0 | null | 2020-02-18T22:56:20 | 2020-02-18T22:56:19 | null | UTF-8 | C++ | false | false | 2,063 | cpp | #include "ImageClass.h"
float angle = 0;
Shape::Shape()
{
color = ofColor(ofRandom(255), ofRandom(255), ofRandom(255));
startingX = 500;
startingY = 900;
cornerRadius = 50;
}
Shape::Shape(int x, int y)
{
color = ofColor(ofRandom(240, 255), ofRandom(240, 255), ofRandom(240, 255));
startingX = x;
startingY = y;
size = 50;
rotationZ = 0.0;
rotateZ = 20.0;
rotationY = 0.0;
rotateY = 20.0;
rotationX = 0.0;
rotateX = 20.0;
box2d.init();
box2d.setGravity(0,30);
box2d.createBounds();
circle.setPhysics(3.0, 0.5, 1.0);
}
void Shape::update() {
circle.setup(box2d.getWorld(),0, 0, size);
float y = ofMap(sin(angle), -1, 1, 0, float(ofGetWindowHeight()));
rotationZ = rotationZ + rotateZ;
rotationX = rotationX + rotateX;
//rotationY = rotationY + rotateY;
float xPos = ofMap(sin(ofGetElapsedTimef()), -1, 1, 0, ofGetWidth());
//ofRect(xPos, ofGetHeight()/2, 10,10);
//ofPushMatrix();
//ofSetColor(ofRandom(240, 255), ofRandom(240, 255), ofRandom(240, 255));
//ofTranslate(startingX, startingY);
//startingY = startingY + y;
//startingX = startingX * (sin(ofGetElapsedTimef() * .01));
startingY = startingY + xPos;
startingX = startingX + xPos;
//ofPopMatrix();
color = ofColor(ofRandom(240, 255), ofRandom(240, 255), ofRandom(240, 255));
cornerRadius = ofRandom(10,50);
startingX = ofRandom(startingX - 5, startingX + 5);
size = size - .5;
if (size < 3 ){
size = 0;
};
//angle += 0.01;
}
void Shape::draw()
{
ofSetRectMode(OF_RECTMODE_CENTER);
ofPushMatrix();
ofFill();
ofSetColor(50, 50, 50);
ofTranslate(startingX, startingY);
ofDrawRectRounded(0, 0, size, size, cornerRadius);
ofPopMatrix();
ofSetRectMode(OF_RECTMODE_CENTER);
ofPushMatrix();
ofNoFill();
ofSetColor(50, 50, 50);
ofTranslate(startingX, startingY);
//ofRotateZ(rotationZ);
//ofRotateY(rotationY);
//ofRotateX(rotationX);
//for (int i = 0; i < 30; i++){
//ofRotateDeg(ofGetElapsedTimef());
//ofScale(0.9);
//ofDrawRectRounded(0, 0, size, size, cornerRadius);
//}
ofPopMatrix();
}
Shape::~Shape()
{
} | [
"[email protected]"
] | |
02d7dcbd8bc2126bf9491bda170cc357cb8389e2 | e915778c19cadaefc63bc1413313055e4d4912aa | /MVD_ToolScripting-Exporter-Class9/class9/Alun_Alberto_Tools/src/Parsers.cpp | 45a8badef2fd2446e08a4c510936608074df986a | [] | no_license | lauriChu/MVD_ToolScripting | 0103ca52de22606cb2cc2b812e18273a9e162666 | 9e01889a2415cacc86fd02726f67b065b9e1192d | refs/heads/master | 2020-04-20T23:05:52.761709 | 2019-02-06T21:56:16 | 2019-02-06T21:56:16 | 169,159,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,873 | cpp | #include "Parsers.h"
#include <fstream>
#include "extern.h"
#include "rapidjson/document.h"
#include "rapidjson/istreamwrapper.h"
#include "components/comp_rotator.h"
#include "components/comp_tag.h"
#include <unordered_map>
std::unordered_map<std::string, int> Parsers::geometries;
std::unordered_map<std::string, int> Parsers::textures;
std::unordered_map<std::string, int> Parsers::materials;
std::unordered_map<std::string, int> Parsers::shaders;
void split(std::string to_split, std::string delim, std::vector<std::string>& result) {
size_t last_offset = 0;
while (true) {
//find first delim
size_t offset = to_split.find_first_of(delim, last_offset);
result.push_back(to_split.substr(last_offset, offset - last_offset));
if (offset == std::string::npos) // if at end of string
break;
else //otherwise continue
last_offset = offset + 1;
}
}
//parses a wavefront object into passed arrays
bool Parsers::parseOBJ(std::string filename, std::vector<float>& vertices, std::vector<float>& uvs, std::vector<float>& normals, std::vector<unsigned int>& indices) {
std::string line;
std::ifstream file(filename);
if (file.is_open())
{
//declare containers for temporary and final attributes
std::vector<lm::vec3> temp_vertices;
std::vector<lm::vec2> temp_uvs;
std::vector<lm::vec3> temp_normals;
//container to store map for indices
std::unordered_map<std::string, int> indices_map;
int next_index = 0; //stores next available index
//parse file line by line
while (std::getline(file, line))
{
//split line string
std::vector<std::string> words;
split(line, " ", words);
for (auto it = words.begin(); it != words.end();)
{
if ((*it) == "") it = words.erase(it);
else it++;
}
if (words.empty()) continue; //empty line, skip
if (words[0][0] == '#') continue; //first word starts with #, line is a comment
if (words[0] == "v") { //line contains vertex data
//read words to floats
lm::vec3 pos((float)atof(words[1].c_str()),
(float)atof(words[2].c_str()),
(float)atof(words[3].c_str()));
//add to temporary vector of positions
temp_vertices.push_back(pos);
}
if (words[0] == "vt") { //line contains texture data
//read words to floats
lm::vec2 tex((float)atof(words[1].c_str()),
(float)atof(words[2].c_str()));
//add to temporary vector of texture coords
temp_uvs.push_back(tex);
}
if (words[0] == "vn") { //line contains vertex data
//read words to floats
lm::vec3 norm((float)atof(words[1].c_str()),
(float)atof(words[2].c_str()),
(float)atof(words[3].c_str()));
//add to temporary vector of normals
temp_normals.push_back(norm);
}
//line contains face-vertex data
if (words[0] == "f") {
if (words.size() < 4) continue; // faces with fewer than 3 vertices??!
bool quad_face = false; //boolean to help us deal with quad faces
std::vector<std::string> nums; // container used for split indices
//for each face vertex
for (int i = 1; i < words.size(); i++) {
//check if face vertex has already been indexed
if (indices_map.count(words[i]) == 0) {
if (words[i] == "") continue;
//if not, start by getting all indices
nums.clear();
split(words[i], "/", nums);
int v_ind = atoi(nums[0].c_str()) - 1; //subtract 1 to convert to 0-based array!
int t_ind = atoi(nums[1].c_str()) - 1;
int n_ind = atoi(nums[2].c_str()) - 1;
//add vertices to final arrays of floats
for (int j = 0; j < 3; j++)
vertices.push_back(temp_vertices[v_ind].value_[j]);
for (int j = 0; j < 2; j++)
uvs.push_back(temp_uvs[t_ind].value_[j]);
for (int j = 0; j < 3; j++)
normals.push_back(temp_normals[n_ind].value_[j]);
//add an index to final array
indices.push_back(next_index);
//record that this index is used for this face vertex
indices_map[words[i]] = next_index;
//increment index
next_index++;
}
else {
//face vertex was already added to final arrays
//so search for its stored index
int the_index = indices_map.at(words[i]); //safe to use as we know it exists
//add it to final index array
indices.push_back(the_index);
}
//***CHECK FOR QUAD FACES****
//If the face is a quads (i.e. words.size() == 5), we need to create two triangles
//out of the quad. We have already created one triangle with words[1], [2] and [3]
//now we make another with [4], [1] and [3].
if (i == 4) {
//face-vertex 4 is already added, so we search for indices of 1 and 3 and add them
int index_1 = indices_map.at(words[1]);
indices.push_back(index_1);
int index_3 = indices_map.at(words[3]);
indices.push_back(index_3);
}
}
}
}
file.close();
return true;
}
return false;
}
bool Parsers::parseBin(std::string filename, std::vector<float>& vertices, std::vector<float>& uvs, std::vector<float>& normals, std::vector<unsigned int>& indices)
{
FILE* f = nullptr;
f = fopen(filename.c_str(), "rb");
//declare containers for temporary and final attributes
THeader header;
std::vector<float> temp_vtxs;
//parse file line by line
bool eof_found = false;
while (!eof_found) {
//split line string
TChunk chunk;
auto bytes_read = fread(&chunk, 1, sizeof(chunk), f);
assert(bytes_read == sizeof(chunk));
switch (chunk.magic_id) {
case magicHeader:
bytes_read = fread(&header, 1, chunk.num_bytes, f);
assert(bytes_read == chunk.num_bytes);
break;
case magicVtxs:
temp_vtxs.resize(chunk.num_bytes);
bytes_read = fread(temp_vtxs.data(), 1, chunk.num_bytes, f);
assert(bytes_read == chunk.num_bytes);
break;
case magicIdxs:
indices.resize(chunk.num_bytes);
bytes_read = fread(indices.data(), 1, chunk.num_bytes, f);
assert(bytes_read == chunk.num_bytes);
break;
case magicSubGroups:
// add subgroups here
break;
case magicEoF:
eof_found = true;
break;
default:
//printf("Unknown chunk data type %08x of %d bytes while reading file %s\n", chunk.magic_id, chunk.num_bytes, filename.c_str());
break;
}
}
// Replace this with an efficient system without hardcoded sizes!
int vertex_size = header.bytes_per_vtx / sizeof(float);
for (unsigned int i = 0; i < temp_vtxs.size() - vertex_size; i = i + vertex_size) {
vertices.insert(vertices.end(), { temp_vtxs[i], temp_vtxs[i + 1], temp_vtxs[i + 2] });
normals.insert(normals.end(), { temp_vtxs[i + 3], temp_vtxs[i + 4], temp_vtxs[i + 5] });
uvs.insert(uvs.end(), { temp_vtxs[i + 6], temp_vtxs[i + 7] });
}
fclose(f);
return true;
}
// load uncompressed RGB targa file into an OpenGL texture
GLint Parsers::parseTexture(std::string filename) {
std::string str = filename;
std::string ext = str.substr(str.size() - 4, 4);
GLuint texture_id;
if (ext == ".tga" || ext == ".TGA")
{
TGAInfo* tgainfo = loadTGA(filename);
if (tgainfo == NULL) {
std::cerr << "ERROR: Could not load TGA file" << std::endl;
return false;
}
//generate new openGL texture and bind it (tell openGL we want to do stuff with it)
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id); //we are making a regular 2D texture
//screen pixels will almost certainly not be same as texture pixels, so we need to
//set some parameters regarding the filter we use to deal with these cases
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); //set the mag filter
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //set the min filter
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4); //use anisotropic filtering
//this is function that actually loads texture data into OpenGL
glTexImage2D(GL_TEXTURE_2D, //the target type, a 2D texture
0, //the base level-of-detail in the mipmap
(tgainfo->bpp == 24 ? GL_RGB : GL_RGBA), //specified the color channels for opengl
tgainfo->width, //the width of the texture
tgainfo->height, //the height of the texture
0, //border - must always be 0
(tgainfo->bpp == 24 ? GL_BGR : GL_BGRA), //the format of the incoming data
GL_UNSIGNED_BYTE, //the type of the incoming data
tgainfo->data); // a pointer to the incoming data
//we want to use mipmaps
glGenerateMipmap(GL_TEXTURE_2D);
//clean up memory
delete tgainfo->data;
delete tgainfo;
return texture_id;
}
else {
std::cerr << "ERROR: No extension or extension not supported" << std::endl;
return -1;
}
}
// this reader supports only uncompressed RGB targa files with no colour table
TGAInfo* Parsers::loadTGA(std::string filename)
{
//the TGA header is 18 bytes long. The first 12 bytes are for specifying the compression
//and various fields that are very infrequently used, and hence are usually 0.
//for this limited file parser, we start by reading the first 12 bytes and compare
//them against the pattern that identifies the file a simple, uncompressed RGB file.
//more info about the TGA format cane be found at http://www.paulbourke.net/dataformats/tga/
char TGA_uncompressed[12] = { 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
char TGA_compare[12];
char info_header[6];
GLuint bytes_per_pixel;
GLuint image_size;
//open file
std::ifstream file(filename, std::ios::binary);
//read first 12 bytes
file.read(&TGA_compare[0], 12);
std::streamsize read_header_12 = file.gcount();
//compare to check that file in uncompressed (or not corrupted)
int header_compare = memcmp(TGA_uncompressed, TGA_compare, sizeof(TGA_uncompressed));
if (read_header_12 != sizeof(TGA_compare) || header_compare != 0) {
std::cerr << "ERROR: TGA file is not in correct format or corrupted: " << filename << std::endl;
file.close();
return nullptr;
}
//read in next 6 bytes, which contain 'important' bit of header
file.read(&info_header[0], 6);
TGAInfo* tgainfo = new TGAInfo;
tgainfo->width = info_header[1] * 256 + info_header[0]; //width is stored in first two bytes of info_header
tgainfo->height = info_header[3] * 256 + info_header[2]; //height is stored in next two bytes of info_header
if (tgainfo->width <= 0 || tgainfo->height <= 0 || (info_header[4] != 24 && info_header[4] != 32)) {
file.close();
delete tgainfo;
std::cerr << "ERROR: TGA file is not 24 or 32 bits, or has no width or height: " << filename << std::endl;
return NULL;
}
//calculate bytes per pixel and then total image size in bytes
tgainfo->bpp = info_header[4];
bytes_per_pixel = tgainfo->bpp / 8;
image_size = tgainfo->width * tgainfo->height * bytes_per_pixel;
//reserve memory for the image data
tgainfo->data = (GLubyte*)malloc(image_size);
//read data into memory
file.read((char*)tgainfo->data, image_size);
std::streamsize image_read_size = file.gcount();
//check it has been read correctly
if (image_read_size != image_size) {
if (tgainfo->data != NULL)
free(tgainfo->data);
file.close();
std::cerr << "ERROR: Could not read tga data: " << filename << std::endl;
delete tgainfo;
return NULL;
}
file.close();
return tgainfo;
}
bool Parsers::parseJSONLevel(std::string filename,
GraphicsSystem& graphics_system) {
//read json file and stream it into a rapidjson document
//see http://rapidjson.org/md_doc_stream.html
std::ifstream json_file(filename);
rapidjson::IStreamWrapper json_stream(json_file);
rapidjson::Document json;
json.ParseStream(json_stream);
//check if its valid JSON
if (json.HasParseError()) std::cerr << "JSON format is not valid!" << std::endl;
//check if its a valid scene file
if (!json.HasMember("scene")) { std::cerr << "JSON file is incomplete! Needs entry: scene" << std::endl; return false; }
if (!json.HasMember("directory")) { std::cerr << "JSON file is incomplete! Needs entry: directory" << std::endl; return false; }
if (!json.HasMember("textures")) { std::cerr << "JSON file is incomplete! Needs entry: textures" << std::endl; return false; }
if (!json.HasMember("materials")) { std::cerr << "JSON file is incomplete! Needs entry: materials" << std::endl; return false; }
if (!json.HasMember("lights")) { std::cerr << "JSON file is incomplete! Needs entry: lights" << std::endl; return false; }
if (!json.HasMember("entities")) { std::cerr << "JSON file is incomplete! Needs entry: entities" << std::endl; return false; }
if (!json.HasMember("shaders")) { std::cerr << "JSON file is incomplete! Needs entry: shaders" << std::endl; return false; }
printf("Parsing Scene Name = %s\n", json["scene"].GetString());
std::string data_dir = json["directory"].GetString();
//dictionaries
std::unordered_map<std::string, int> geometries;
std::unordered_map<std::string, int> textures;
std::unordered_map<std::string, int> materials;
std::unordered_map<std::string, std::string> child_parent;
//geometries
for (rapidjson::SizeType i = 0; i < json["geometries"].Size(); i++) {
//get values from json
std::string name = json["geometries"][i]["name"].GetString();
std::string file = json["geometries"][i]["file"].GetString();
//load geometry
int geom_id = graphics_system.createGeometryFromFile(data_dir + file);
//add to dictionary
geometries[name] = geom_id;
}
//textures
for (rapidjson::SizeType i = 0; i < json["textures"].Size(); i++) {
//get values from json
std::string name = json["textures"][i]["name"].GetString();
std::string file = json["textures"][i]["file"].GetString();
//load texture
int tex_id = parseTexture(data_dir + file);
//add to dictionary
textures[name] = tex_id;
}
//shaders
for (rapidjson::SizeType i = 0; i < json["shaders"].Size(); i++) {
//get values from json
std::string name = json["shaders"][i]["name"].GetString();
std::string vertex = json["shaders"][i]["vertex"].GetString();
std::string fragment = json["shaders"][i]["fragment"].GetString();
//load shader
Shader* new_shader = graphics_system.loadShader(vertex, fragment);
new_shader->name = name;
shaders[name] = new_shader->program;
}
//materials
for (rapidjson::SizeType i = 0; i < json["materials"].Size(); i++) {
//get values from json
std::string name = json["materials"][i]["name"].GetString();
//create material
int mat_id = graphics_system.createMaterial();
//shader_id is mandatory
graphics_system.getMaterial(mat_id).shader_id = shaders[json["materials"][i]["shader"].GetString()];
//optional properties
//diffuse texture
if (json["materials"][i].HasMember("diffuse_texture")) {
std::string diffuse = json["materials"][i]["diffuse_texture"].GetString();
graphics_system.getMaterial(mat_id).diffuse_map = textures[diffuse]; //assign texture id from material
}
//specular
if (json["materials"][i].HasMember("specular")) {
auto& json_spec = json["materials"][i]["specular"];
graphics_system.getMaterial(mat_id).specular = lm::vec3(json_spec[0].GetFloat(), json_spec[1].GetFloat(), json_spec[2].GetFloat());
}
else
graphics_system.getMaterial(mat_id).specular = lm::vec3(0, 0, 0); //no specular
//ambient
if (json["materials"][i].HasMember("ambient")) {
auto& json_ambient = json["materials"][i]["ambient"];
graphics_system.getMaterial(mat_id).ambient = lm::vec3(json_ambient[0].GetFloat(), json_ambient[1].GetFloat(), json_ambient[2].GetFloat());
}
else
graphics_system.getMaterial(mat_id).ambient = lm::vec3(0.1f, 0.1f, 0.1f); //no specular
//add to dictionary
materials[name] = mat_id;
}
//lights
for (rapidjson::SizeType i = 0; i < json["lights"].Size(); i++) {
std::string light_name = json["lights"][i]["name"].GetString();
auto json_lp = json["lights"][i]["position"].GetArray();
auto json_lc = json["lights"][i]["color"].GetArray();
int ent_light = ECS.createEntity(light_name);
ECS.createComponentForEntity<Light>(ent_light);
ECS.getComponentFromEntity<Transform>(ent_light).translate(json_lp[0].GetFloat(), json_lp[1].GetFloat(), json_lp[2].GetFloat());
ECS.getComponentFromEntity<Light>(ent_light).color = lm::vec3(json_lc[0].GetFloat(), json_lc[1].GetFloat(), json_lc[2].GetFloat());
}
//entities
for (rapidjson::SizeType i = 0; i < json["entities"].Size(); i++) {
//json for entity
auto& json_ent = json["entities"][i];
//get name
std::string json_name = "";
if (json_ent.HasMember("name"))
json_name = json_ent["name"].GetString();
//get geometry and material ids - obligatory fields
std::string json_geometry = json_ent["geometry"].GetString();
std::string json_material = json_ent["material"].GetString();
//transform - obligatory field
auto jt = json_ent["transform"]["translate"].GetArray();
auto jr = json_ent["transform"]["rotate"].GetArray();
auto js = json_ent["transform"]["scale"].GetArray();
//create entity
int ent_id = ECS.createEntity(json_name);
Mesh& ent_mesh = ECS.createComponentForEntity<Mesh>(ent_id);
ent_mesh.geometry = geometries[json_geometry];
ent_mesh.material = materials[json_material];
//transform
auto& ent_transform = ECS.getComponentFromEntity<Transform>(ent_id);
//rotate
//get rotation euler angles
lm::vec3 rotate; rotate.x = jr[0].GetFloat(); rotate.y = jr[1].GetFloat(); rotate.z = jr[2].GetFloat();
//create quaternion from euler angles
lm::quat qR(rotate.x*DEG2RAD, rotate.y*DEG2RAD, rotate.z*DEG2RAD);
//create matrix which represents these rotations
lm::mat4 R; R.makeRotationMatrix(qR);
//multiply transform by this matrix
ent_transform.set(ent_transform * R);
//scale
ent_transform.scaleLocal(js[0].GetFloat(), js[1].GetFloat(), js[2].GetFloat());
//translate
ent_transform.translate(jt[0].GetFloat(), jt[1].GetFloat(), jt[2].GetFloat());
if (json_ent["transform"].HasMember("parent")) {
std::string json_parent = json_ent["transform"]["parent"].GetString();
if (json_name == "" || json_parent == "") std::cerr << "ERROR: Parser: Either parent or child has no name";
child_parent[json_name] = json_parent;
}
//optional fields below
if (json_ent.HasMember("collider")) {
std::string coll_type = json_ent["collider"]["type"].GetString();
if (coll_type == "Box") {
Collider& box_collider = ECS.createComponentForEntity<Collider>(ent_id);
box_collider.collider_type = ColliderTypeBox;
auto json_col_center = json_ent["collider"]["center"].GetArray();
box_collider.local_center.x = json_col_center[0].GetFloat();
box_collider.local_center.y = json_col_center[1].GetFloat();
box_collider.local_center.z = json_col_center[2].GetFloat();
auto json_col_halfwidth = json_ent["collider"]["halfwidth"].GetArray();
box_collider.local_halfwidth.x = json_col_halfwidth[0].GetFloat();
box_collider.local_halfwidth.y = json_col_halfwidth[1].GetFloat();
box_collider.local_halfwidth.z = json_col_halfwidth[2].GetFloat();
}
///TODO - Ray
}
}
//now link hierarchy need to get transform id from parent entity,
//and link to transform object from child entity
for (std::pair<std::string, std::string> relationship : child_parent)
{
//get parent entity
int parent_entity_id = ECS.getEntity(relationship.second);
Entity& parent = ECS.entities[parent_entity_id];
int parent_transform_id = parent.components[0]; //transform component is always in slot 0
//get child transform
Transform& transform_child = ECS.getComponentFromEntity<Transform>(relationship.first);
//link child transform with parent id
transform_child.parent = parent_transform_id;
}
return true;
}
// Method to parse the scene with new json structure
// No managers implemented, resources are loaded more than once!!
bool Parsers::parseScene(std::string filename, GraphicsSystem & graphics_system)
{
// Set the json stream to be read
std::ifstream json_file(filename);
rapidjson::IStreamWrapper json_stream(json_file);
rapidjson::Document json;
json.ParseStream(json_stream);
//check if its valid JSON
if (json.HasParseError()) std::cerr << "JSON format is not valid!" << std::endl;
if (!json.HasMember("scene")) { std::cerr << "JSON file is incomplete! Needs entry: scene" << std::endl; return false; }
if (!json.HasMember("entities")) { std::cerr << "JSON file is incomplete! Needs entry: entities" << std::endl; return false; }
printf("Parsing Scene Name = %s\n", json["scene"].GetString());
// Create a default shader by now
Shader* new_shader = graphics_system.loadShader("data/shaders/phong.vert", "data/shaders/phong.frag");
new_shader->name = "phong";
shaders["phong"] = new_shader->program;
std::unordered_map<std::string, std::string> child_parent;
for (rapidjson::SizeType i = 0; i < json["entities"].Size(); i++) {
//get values from json
rapidjson::Value & entity = json["entities"][i];
int entity_id = parseEntity(entity, graphics_system);
Entity ent = ECS.entities[entity_id];
// Stablish a parent/children relationship if needed
if (entity.HasMember("parent")) {
std::string json_parent = entity["parent"].GetString();
if (ent.name == "" || json_parent == "") std::cerr << "ERROR: Parser: Either parent or child has no name";
child_parent[ent.name] = json_parent;
}
}
//now link hierarchy need to get transform id from parent entity,
//and link to transform object from child entity
for (std::pair<std::string, std::string> relationship : child_parent)
{
//get parent entity
int parent_entity_id = ECS.getEntity(relationship.second);
Entity& parent = ECS.entities[parent_entity_id];
int parent_transform_id = parent.components[0];
Transform& transform_child = ECS.getComponentFromEntity<Transform>(relationship.first);
transform_child.parent = parent_transform_id;
}
return false;
}
int Parsers::parseEntity(rapidjson::Value & entity, GraphicsSystem & graphics_system)
{
std::string name = "";
if (entity.HasMember("name"))
name = entity["name"].GetString();
int ent_id = -1;
if (entity.HasMember("prefab")) {
/// In case of prefab entity, load the entity and then ignore it's default transform and name
std::ifstream json_file(entity["prefab"].GetString());
rapidjson::IStreamWrapper json_stream(json_file);
rapidjson::Document json;
json.ParseStream(json_stream);
// Add support for multiple entities in prefab
ent_id = parseEntity(json["entities"][0], graphics_system);
ECS.entities[ent_id].name = name;
}
else {
// Create the entity with the given name
ent_id = ECS.createEntity(name);
}
//load transform component, mandatory field
if (entity.HasMember("transform")) {
auto& ent_transform = ECS.getComponentFromEntity<Transform>(ent_id);
ent_transform.Load(entity, ent_id);
}
// Load render, geometry and materials
if (entity.HasMember("render")) {
int geo_id = Geometry::Load(graphics_system, entity, ent_id);
int mat_id = Material::Load(graphics_system, entity, ent_id);
Mesh& ent_mesh = ECS.createComponentForEntity<Mesh>(ent_id);
ent_mesh.geometry = geo_id;
ent_mesh.material = mat_id;
}
// Load collider parameters
if (entity.HasMember("collider")) {
Collider& collider = ECS.createComponentForEntity<Collider>(ent_id);
collider.Load(entity, ent_id);
}
// Add the light component
if (entity.HasMember("light")) {;
Light& light = ECS.createComponentForEntity<Light>(ent_id);
light.Load(entity, ent_id);
}
// Custom components here!
// Parse custom components here
if (entity.HasMember("rotator")) {
Rotator& rotator = ECS.createComponentForEntity<Rotator>(ent_id);
rotator.Load(entity, ent_id);
}
if (entity.HasMember("tags")) {
Tag& tag = ECS.createComponentForEntity<Tag>(ent_id);
tag.Load(entity, ent_id);
}
///TODO- Add any other component loading here!
return ent_id;
}
/*int Parsers::parseEntity(rapidjson::Value & entity, GraphicsSystem & graphics_system)
{
std::string name = "";
if (entity.HasMember("name"))
name = entity["name"].GetString();
// Create the entity with the given name
int ent_id = ECS.createEntity(name);
if (entity.HasMember("prefab")) {
/// In case of prefab entity, load the entity and then ignore it's default transform and name
std::ifstream json_file(entity["prefab"].GetString());
rapidjson::IStreamWrapper json_stream(json_file);
rapidjson::Document json;
json.ParseStream(json_stream);
// Add support for multiple entities in prefab
ent_id = parseEntity(json["entities"][0], graphics_system);
}
//load transform component, mandatory field
if (entity.HasMember("transform")) {
auto jt = entity["transform"]["translation"].GetArray();
auto jr = entity["transform"]["rotation"].GetArray();
auto js = entity["transform"]["scale"].GetArray();
//transform
auto& ent_transform = ECS.getComponentFromEntity<Transform>(ent_id);
lm::vec3 rotate; rotate.x = jr[0].GetFloat(); rotate.y = jr[1].GetFloat(); rotate.z = jr[2].GetFloat();
lm::quat qR(rotate.x*DEG2RAD, rotate.y*DEG2RAD, rotate.z*DEG2RAD);
lm::mat4 R;
R.rotateLocal(rotate.x*DEG2RAD, lm::vec3(1, 0, 0));
R.rotateLocal(rotate.y*DEG2RAD, lm::vec3(0, 1, 0));
R.rotateLocal(rotate.z*DEG2RAD, lm::vec3(0, 0, 1));
ent_transform.set(ent_transform * R);
ent_transform.scaleLocal(js[0].GetFloat(), js[1].GetFloat(), js[2].GetFloat());
ent_transform.translate(jt[0].GetFloat(), jt[1].GetFloat(), jt[2].GetFloat());
}
if (entity.HasMember("render")) {
// Parse mesh and materials
// By now, only one single material per mesh
auto jmesh = entity["render"]["mesh"].GetString();
auto jmat = entity["render"]["materials"].GetArray();
std::string mat_name = jmat[0].GetString();
std::ifstream json_file(jmat[0].GetString());
rapidjson::IStreamWrapper json_stream(json_file);
rapidjson::Document json_material;
json_material.ParseStream(json_stream);
int geo_id;
if (geometries.find(jmesh) == geometries.end()) {
geo_id = graphics_system.createGeometryFromFile(jmesh);
geometries[jmesh] = geo_id;
}
else {
geo_id = geometries[jmesh];
}
int mat_id = graphics_system.createMaterial();
// Load shader data from technique
// Hardcoded by now until technique source file is done.
graphics_system.getMaterial(mat_id).shader_id = shaders["phong"];
if (json_material.HasParseError()) std::cerr << "JSON format is not valid!" << std::endl;
if (json_material["textures"].HasMember("diffuse")) {
std::string tx_diff = json_material["textures"]["diffuse"].GetString();
int tex_id;
if (textures.find(tx_diff) == textures.end()) { tex_id = parseTexture(tx_diff); textures[tx_diff] = tex_id; }
else { tex_id = textures[tx_diff]; }
graphics_system.getMaterial(mat_id).diffuse_map = tex_id; //assign texture id from material
}
if (json_material["textures"].HasMember("specular")) {
std::string tx_spec = json_material["textures"]["specular"].GetString();
int tex_id = parseTexture(tx_spec);
//graphics_system.getMaterial(mat_id).specular = lm::vec3(json_spec[0].GetFloat(), json_spec[1].GetFloat(), json_spec[2].GetFloat());
}
else {
graphics_system.getMaterial(mat_id).specular = lm::vec3(0, 0, 0); //no specular
}
if (json_material["textures"].HasMember("ambient")) {
std::string tx_amb = json_material["textures"]["ambient"].GetString();
int tex_id = parseTexture(tx_amb);
//graphics_system.getMaterial(mat_id).ambient = lm::vec3(json_ambient[0].GetFloat(), json_ambient[1].GetFloat(), json_ambient[2].GetFloat());
}
else {
graphics_system.getMaterial(mat_id).ambient = lm::vec3(0.1f, 0.1f, 0.1f); //small ambient
}
Mesh& ent_mesh = ECS.createComponentForEntity<Mesh>(ent_id);
ent_mesh.geometry = geo_id;
ent_mesh.material = mat_id;
}
if (entity.HasMember("collider")) {
std::string coll_type = entity["collider"]["type"].GetString();
if (coll_type == "box") {
Collider& box_collider = ECS.createComponentForEntity<Collider>(ent_id);
box_collider.collider_type = ColliderTypeBox;
auto json_col_center = entity["collider"]["center"].GetArray();
box_collider.local_center.x = json_col_center[0].GetFloat();
box_collider.local_center.y = json_col_center[1].GetFloat();
box_collider.local_center.z = json_col_center[2].GetFloat();
auto json_col_halfwidth = entity["collider"]["halfwidth"].GetArray();
box_collider.local_halfwidth.x = json_col_halfwidth[0].GetFloat();
box_collider.local_halfwidth.y = json_col_halfwidth[1].GetFloat();
box_collider.local_halfwidth.z = json_col_halfwidth[2].GetFloat();
}
///TODO - Ray
}
// Add the light component
if (entity.HasMember("light")) {
auto json_lc = entity["light"]["color"].GetArray();
ECS.createComponentForEntity<Light>(ent_id);
ECS.getComponentFromEntity<Light>(ent_id).color = lm::vec3(json_lc[0].GetFloat(), json_lc[1].GetFloat(), json_lc[2].GetFloat());
}
// Parse custom components here
if (entity.HasMember("rotator")) {
auto json_sp = entity["rotator"]["speed"].GetFloat();
auto json_axis = entity["rotator"]["axis"].GetArray();
ECS.createComponentForEntity<Rotator>(ent_id);
ECS.getComponentFromEntity<Rotator>(ent_id).speed = json_sp;
ECS.getComponentFromEntity<Rotator>(ent_id).axis = lm::vec3(json_axis[0].GetFloat(), json_axis[1].GetFloat(), json_axis[2].GetFloat());
}
if (entity.HasMember("tags")) {
auto& json_tags = entity["tags"].GetArray();
std::vector<std::string> tags;
for (auto& p : json_tags)
tags.push_back(p.GetString());
ECS.createComponentForEntity<Tag>(ent_id);
ECS.getComponentFromEntity<Tag>(ent_id).tags = tags;
}
///TODO- Add any other component loading here!
return ent_id;
}
*/ | [
"[email protected]"
] | |
a018577b4c44747c97a94b48387b54036d67044c | dcd404807089f8c7f898d0fdbd4eac8eddfba70d | /modules/svg/include/SkSVGFeComposite.h | 9a6570acdc6f41faa9fac19adf0e3df7324cfd39 | [
"BSD-3-Clause"
] | permissive | mattleibow/skia | 3d52a7927fa733eedca9c3fd3235f9a905af7477 | 8e7a3aa31b76f3e16e561eead4c938a8fbbd520f | refs/heads/xamarin-mobile-bindings | 2023-03-16T18:06:35.333452 | 2022-05-31T18:20:40 | 2022-05-31T18:20:40 | 502,410,740 | 1 | 0 | BSD-3-Clause | 2022-06-11T17:14:30 | 2022-06-11T17:14:29 | null | UTF-8 | C++ | false | false | 1,356 | h | /*
* Copyright 2020 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkSVGFeComposite_DEFINED
#define SkSVGFeComposite_DEFINED
#include "include/core/SkBlendMode.h"
#include "modules/svg/include/SkSVGFe.h"
#include "modules/svg/include/SkSVGTypes.h"
class SkSVGFeComposite final : public SkSVGFe {
public:
~SkSVGFeComposite() override = default;
static sk_sp<SkSVGFeComposite> Make() {
return sk_sp<SkSVGFeComposite>(new SkSVGFeComposite());
}
SVG_ATTR(In2, SkSVGFeInputType, SkSVGFeInputType())
SVG_ATTR(K1, SkSVGNumberType, SkSVGNumberType(0))
SVG_ATTR(K2, SkSVGNumberType, SkSVGNumberType(0))
SVG_ATTR(K3, SkSVGNumberType, SkSVGNumberType(0))
SVG_ATTR(K4, SkSVGNumberType, SkSVGNumberType(0))
SVG_ATTR(Operator, SkSVGFeCompositeOperator, SkSVGFeCompositeOperator::kOver)
protected:
sk_sp<SkImageFilter> onMakeImageFilter(const SkSVGRenderContext&,
const SkSVGFilterContext&) const override;
bool parseAndSetAttribute(const char*, const char*) override;
private:
SkSVGFeComposite() : INHERITED(SkSVGTag::kFeComposite) {}
static SkBlendMode BlendModeForOperator(SkSVGFeCompositeOperator);
using INHERITED = SkSVGFe;
};
#endif // SkSVGFeComposite_DEFINED
| [
"[email protected]"
] | |
c6fb431ceec3c64fe4e4d8c28d12b09bd99f5002 | 10e90fa57373b61f54965ddc4ba51ab9ee69db33 | /source/color.cpp | e499805309cbaaf1aa1bb091d3e4b69e482f6664 | [
"MIT"
] | permissive | TheChosenHobbit/programmiersprachen-aufgabenblatt-2 | 62c419905a9c48e7f2cbadd92ebca9dd00757e6b | ac29bd561c633aede0cf34135b90e334a4b8437a | refs/heads/master | 2020-12-03T10:38:53.778756 | 2016-05-08T22:58:40 | 2016-05-08T22:58:40 | 57,893,836 | 0 | 0 | null | 2016-05-02T13:53:53 | 2016-05-02T13:53:53 | null | UTF-8 | C++ | false | false | 163 | cpp | #include "color.hpp"
Color::Color():
r{0},
g{0},
b{0} {}
Color::Color(float a):
r{a},
g{a},
b{a} {}
Color::Color(float d, float e, float f):
r{d},
g{e},
b{f} {} | [
"[email protected]"
] | |
0a835ad03547d117f52b6eedeaaa0b4fa66a79fc | 84b4e162de99f2c1fc470f03b94d01cadcfc9c05 | /Chp14/Questions/C14Q15.cpp | d43f3f7efa25478ae64c3239f98c9ff0b9d7cf62 | [] | no_license | kate-ly-zhao/Eckel_ThinkingInCPP | a12837deb5cc98b75c39e3302cd146b3dfc9521c | ccaf3d530a438f2f3581ad4264a585b4db920399 | refs/heads/master | 2020-03-19T06:33:54.222172 | 2018-07-13T01:12:43 | 2018-07-13T01:12:43 | 136,033,407 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 585 | cpp | // C14Q15.cpp
/* Create a class with two static member functions. Inherit from this class and redefine one of the member functions.
Show that the other is hidden in the derived class. */
#include <iostream>
#include <string>
using namespace std;
class music {
public:
static void rock() { cout << "rock n' roll" << endl; }
static void rock(int i) { cout << "how many guitars" << endl; }
};
class piano : public music {
public:
static void rock() { cout << "piano now" << endl; }
};
int main() {
piano steinway;
steinway.rock();
// steinway.rock(2);
}
| [
"[email protected]"
] | |
f06fde87e2b0c2c61116af82c98e9f95967ca4c0 | 0900694cdc952cc44faf65175bc156116ba82f14 | /algorithm/hannuota.cpp | b17967afa57d1393d9b071ec067517758671308a | [
"MIT"
] | permissive | chtld/Programming-and-Algorithm-Course | 588de8935ab2e35e72f43f406b73e57e3622faca | 669f266fc97db9050013ffbb388517667de33433 | refs/heads/master | 2021-07-22T20:32:04.246130 | 2020-05-10T00:06:40 | 2020-05-10T00:06:40 | 164,189,452 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | #include<iostream>
using namespace std;
void move(int n, char A, char B, char C){
if (n == 1) {
cout << A << "->" << C << endl;
return;
}
move(n-1, A, C, B);
cout << A << "->" << C << endl;
move(n-1, B, A, C);
}
int main(){
int n;
cin >> n;
move(n, 'A', 'B', 'C');
return 0;
} | [
"[email protected]"
] | |
76912f7c050cb42467549f061a5118bd4e233287 | 257a6ebe1c0bce0b6f81161fe059a50138860bf1 | /minesweeper test/Array2D.h | ae188f47eefcb074fa045c51b4c0f6620d428d95 | [] | no_license | shantahuja/minesweeper-test | ebfbce4f492d997fc3eb57d292bba0783ba661f2 | 95d1f6071c05655eaedda96967299fdaa3593c06 | refs/heads/master | 2020-04-01T12:39:11.004129 | 2018-10-16T03:35:26 | 2018-10-16T03:35:26 | 153,217,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,530 | h | #ifndef ARRAY2D_H
#define ARRAY2D_H
#include "Array.h"
#include "Row.h"
#include "Exception.h"
template <class T>
class Row;
template <class T>
class Array2D
{
private:
Array<T> m_array;
int m_row;
int m_col;
public:
Array2D();
Array2D(int row, int col);
Array2D(const Array2D & copy);
~Array2D();
Array2D & operator =(const Array2D & rhs);
Row<T> operator [](int index);
Row<T> operator [](int index) const;
int getRow();
int getRow() const;
void setRow(int rows);
int getColumn();
int getColumn() const;
void setColumn(int columns);
T & Select(int row, int column);
T & Select(int row, int column) const;
};
template <class T>
//make sure that default constructor has row, column, and length of zero
inline Array2D<T>::Array2D() : m_row(0), m_col(0)
{
m_array.setLength(0);
}
template<class T>
//make sure row, col, and length equal to what you set it
inline Array2D<T>::Array2D(int row, int col)
{
try
{
if (row < 0)
{
throw Exception();
}
if (col < 0)
{
throw Exception();
}
m_array.setLength((row)*(col));
m_row = row;
m_col = col;
}
catch (std::bad_alloc ba)
{
throw ba;
}
}
template<class T>
//copy constructor equal test
inline Array2D<T>::Array2D(const Array2D & copy)
{
m_array.setLength((copy.getRow()) * (copy.getColumn()));
m_row = copy.getRow();
m_col = copy.getColumn();
m_array = copy.m_array;
}
template<class T>
//no test?
inline Array2D<T>::~Array2D()
{
}
template<class T>
//use assignment operator to make two 2d arrays equal each other
inline Array2D<T> & Array2D<T>::operator=(const Array2D & rhs)
{
m_array.setLength((rhs.getRow()) * (rhs.getColumn()));
m_row = rhs.getRow();
m_col = rhs.getColumn();
m_array = rhs.m_array;
return *this;
}
template<class T>
inline Row<T> Array2D<T>::operator[](int index)
{
return Row<T>(*this, index);
}
template<class T>
inline Row<T> Array2D<T>::operator[](int index) const
{
return Row<T>(*this, index);
}
template<class T>
inline int Array2D<T>::getRow()
{
return m_row;
}
template<class T>
inline int Array2D<T>::getRow() const
{
return m_row;
}
template<class T>
//set new amount of rows and verify data inside
inline void Array2D<T>::setRow(int rows)
{
m_array.setLength(rows*m_col);
m_row = rows;
}
template<class T>
inline int Array2D<T>::getColumn()
{
return m_col;
}
template<class T>
inline int Array2D<T>::getColumn() const
{
return m_col;
}
template<class T>
inline void Array2D<T>::setColumn(int columns)
{
Array<T> temp(m_row*columns);
int index = 0;
int actual_column = (m_col < columns) ? m_col : columns;
for (int i = 0; i < m_row; i++)
{
for (int j = 0; j < actual_column; j++)
{
T value = m_array[(i*m_col) + j];
temp[index++] = value;
}
}
m_col = columns;
m_array = temp;
}
template<class T>
inline T & Array2D<T>::Select(int row, int column)
{
int upper_bound = m_row * m_col;
int lower_bound = 0;
try
{
int size = row * column;
if (size <= upper_bound && size >= lower_bound && row >= 0 && column >= 0)
{
return m_array[((m_col*row) + column)];
}
else
throw Exception();
}
catch (std::bad_alloc & ba)
{
throw ba;
}
}
template<class T>
inline T & Array2D<T>::Select(int row, int column) const
{
int upper_bound = m_row * m_col;
int lower_bound = 0;
try
{
int size = row * column;
if (size <= upper_bound && size >= lower_bound && row >= 0 && column >= 0)
{
return m_array[((m_col*row) + column)];
}
else
throw Exception();
}
catch (std::bad_alloc & ba)
{
throw ba;
}
}
#endif // !ARRAY2D_H
| [
"[email protected]"
] | |
8c62c62986648d4564d30b91a3ce486b2c618eb1 | f8df0470893e10f25f4362b84feecb9011293f43 | /build/iOS/Preview/include/Fuse.Animations.Change-1.h | 1491b6cb083521286b27213364628da8a9f98c46 | [] | no_license | cekrem/PlateNumber | 0593a84a5ff56ebd9663382905dc39ae4e939b08 | 3a4e40f710bb0db109a36d65000dca50e79a22eb | refs/heads/master | 2021-08-23T02:06:58.388256 | 2017-12-02T11:01:03 | 2017-12-02T11:01:03 | 112,779,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,466 | h | // This file was generated based on /usr/local/share/uno/Packages/Fuse.Animations/1.4.0/Change.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.TrackAnimator.h>
namespace g{namespace Fuse{namespace Animations{struct AnimatorState;}}}
namespace g{namespace Fuse{namespace Animations{struct Change;}}}
namespace g{namespace Fuse{namespace Animations{struct Converter;}}}
namespace g{namespace Fuse{namespace Animations{struct CreateStateParams;}}}
namespace g{namespace Uno{namespace UX{struct Property1;}}}
namespace g{namespace Uno{struct Float2;}}
namespace g{
namespace Fuse{
namespace Animations{
// public sealed class Change<T> :35
// {
::g::Fuse::Animations::Animator_type* Change_typeof();
void Change__ctor_3_fn(Change* __this, ::g::Uno::UX::Property1* target);
void Change__CreateState_fn(Change* __this, ::g::Fuse::Animations::CreateStateParams* p, ::g::Fuse::Animations::AnimatorState** __retval);
void Change__get_DegreesX_fn(Change* __this, float* __retval);
void Change__set_DegreesX_fn(Change* __this, float* value);
void Change__get_DegreesXY_fn(Change* __this, ::g::Uno::Float2* __retval);
void Change__set_DegreesXY_fn(Change* __this, ::g::Uno::Float2* value);
void Change__get_DegreesY_fn(Change* __this, float* __retval);
void Change__set_DegreesY_fn(Change* __this, float* value);
void Change__get_DegreesZ_fn(Change* __this, float* __retval);
void Change__set_DegreesZ_fn(Change* __this, float* value);
void Change__get_IsContinuous_fn(Change* __this, bool* __retval);
void Change__New2_fn(uType* __type, ::g::Uno::UX::Property1* target, Change** __retval);
void Change__get_Target_fn(Change* __this, ::g::Uno::UX::Property1** __retval);
void Change__set_Target_fn(Change* __this, ::g::Uno::UX::Property1* value);
void Change__get_Value_fn(Change* __this, uTRef __retval);
void Change__set_Value_fn(Change* __this, void* value);
void Change__get_X_fn(Change* __this, float* __retval);
void Change__set_X_fn(Change* __this, float* value);
void Change__get_XY_fn(Change* __this, ::g::Uno::Float2* __retval);
void Change__set_XY_fn(Change* __this, ::g::Uno::Float2* value);
void Change__get_Y_fn(Change* __this, float* __retval);
void Change__set_Y_fn(Change* __this, float* value);
void Change__get_Z_fn(Change* __this, float* __retval);
void Change__set_Z_fn(Change* __this, float* value);
struct Change : ::g::Fuse::Animations::TrackAnimator
{
uStrong< ::g::Fuse::Animations::Converter*> ContinuousConverter;
uStrong< ::g::Uno::UX::Property1*> _Target;
void ctor_3(::g::Uno::UX::Property1* target);
float DegreesX();
void DegreesX(float value);
::g::Uno::Float2 DegreesXY();
void DegreesXY(::g::Uno::Float2 value);
float DegreesY();
void DegreesY(float value);
float DegreesZ();
void DegreesZ(float value);
bool IsContinuous();
::g::Uno::UX::Property1* Target();
void Target(::g::Uno::UX::Property1* value);
template<class T>
T Value() { T __retval; return Change__get_Value_fn(this, &__retval), __retval; }
template<class T>
void Value(T value) { Change__set_Value_fn(this, uConstrain(__type->T(0), value)); }
float X();
void X(float value);
::g::Uno::Float2 XY();
void XY(::g::Uno::Float2 value);
float Y();
void Y(float value);
float Z();
void Z(float value);
static Change* New2(uType* __type, ::g::Uno::UX::Property1* target);
};
// }
}}} // ::g::Fuse::Animations
| [
"[email protected]"
] | |
5606bdfa8dd242ffddbd7ba0eea5362e8ae856e2 | 1c444bdf16632d78a3801a7fe6b35c054c4cddde | /include/bds/unmapped/IPackTelemetry.h | 79718d64d421469b2e7af997ca32d435624c1fb0 | [] | no_license | maksym-pasichnyk/symbols | 962a082bf6a692563402c87eb25e268e7e712c25 | 7673aa52391ce93540f0e65081f16cd11c2aa606 | refs/heads/master | 2022-04-11T03:17:18.078103 | 2020-03-15T11:30:36 | 2020-03-15T11:30:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | h | #pragma once
class IPackTelemetry {
public:
~IPackTelemetry(); // _ZN14IPackTelemetryD2Ev
IPackTelemetry(); // _ZN14IPackTelemetryC2Ev
};
| [
"[email protected]"
] | |
844bdfa74e135b8ad6814f0a5cee475eb21e4ed5 | ffa8bfb9a99563a4295af6ddd76a1be697aba97a | /photon/src/photon.ino | 39a8b81afa73e944b491cce52da230cb0274b6f3 | [
"MIT"
] | permissive | FirstBuild/AutoBourbonDispenser | 5204d5fcfa2fb5e6f33d7c8aea5f6fc04c3eb3e5 | ff216c8d412b2de3f92773df6f42129eab70ed28 | refs/heads/master | 2021-07-05T05:38:11.871895 | 2017-09-21T20:35:39 | 2017-09-21T20:35:39 | 103,546,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,459 | ino | /*
* Project photon
* Description:
* Author:
* Date:
*/
#include "HX711ADC/HX711ADC.h"
#include "FastLED/FastLED.h"
#include "RBD_Timer/RBD_Timer.h"
#include "RBD_Button/RBD_Button.h"
FASTLED_USING_NAMESPACE;
#define LED_PIN A5
#define COLOR_ORDER GRB
#define CHIPSET WS2811
#define NUM_LEDS 113
#define BRIGHTNESS 100
#define FRAMES_PER_SECOND 60
CRGB leds[NUM_LEDS];
// Pins
#define pumpControlPin D1
#define HX711_DOUT_PIN D7
#define HX711_CLK_PIN D6
#define dispenseBtnPin A2
#define manualDispenseSwitchPin D3
#define autoDispenseSwitchPin D2
// Output device parameters
#define dispenseTimeForOneShot 800
#define weightSamplingRate 20
#define dispenseDebounceTimeout 15
#define weightHighThreshold 7.0
#define weightLowThreshold 2.0
#define autoDispenseDelay 2000
SYSTEM_THREAD(ENABLED);
SYSTEM_MODE(SEMI_AUTOMATIC);
HX711ADC *scale = NULL;
int calibration_factor = 14000;
RBD::Button dispensePushButton(dispenseBtnPin);
RBD::Button manualDispenseSwitch(manualDispenseSwitchPin);
RBD::Button autoDispenseSwitch(autoDispenseSwitchPin);
static int dispenseMode = 0;
void setup() {
// Sanity delay.
handleWiFiConnection();
// Put initialization like pinMode and begin function here.
Serial.begin(9600);
pinMode(pumpControlPin, OUTPUT);
FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( CRGB::Seashell );
FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setTemperature( CRGB::Seashell );
FastLED.setBrightness( BRIGHTNESS );
setupWeightSensing();
}
void loop() {
handleDoubleThrowToggle();
handleBullsEyeWindowLights();
switch (dispenseMode) {
case 0:
break;
case 1:
handleDispenseButton();
break;
case 2:
handleWeightSensing();
break;
default:
break;
}
}
void handleWiFiConnection() {
WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);
waitFor(WiFi.ready, 5000);
if (!(WiFi.ready())) {
WiFi.off();
}
Particle.connect();
waitFor(Particle.connected, 5000);
if (!(Particle.connected())) {
Particle.disconnect();
}
}
void handleBullsEyeWindowLights() {
allWhite();
FastLED.show(); // display this frame
FastLED.delay(1000 / FRAMES_PER_SECOND);
}
void handleDoubleThrowToggle() {
if (manualDispenseSwitch.onPressed()) {
dispenseMode = 1;
Serial.println("Manual Dispense Mode: Enabled");
} else if (manualDispenseSwitch.onReleased()) {
dispenseMode = 0;
Serial.println("Manual Dispense Mode: Disabled");
}
if (autoDispenseSwitch.onPressed()) {
tareScale();
dispenseMode = 2;
Serial.println("Automatic Dispense Mode: Enabled");
} else if (autoDispenseSwitch.onReleased()) {
dispenseMode = 0;
Serial.println("Automatic Dispense Mode: Disabled");
}
}
void handleDispenseButton() {
if (dispensePushButton.onPressed()) {
Serial.println("Dispensing liquid.");
dispenseLiquid();
}
}
void setupWeightSensing() {
scale = new HX711ADC(HX711_DOUT_PIN, HX711_CLK_PIN);
scale->set_scale(calibration_factor);
tareScale();
}
void tareScale() {
scale->tare(); //Reset the scale to 0
}
void handleWeightSensing() {
static float weightInLbs = 0;
static bool hasDispensedLiquid = false;
static unsigned long rateTracker = millis();
if ((millis() - rateTracker) > weightSamplingRate) {
weightInLbs = scale->get_units();
Serial.println(scale->get_units(), 1);
rateTracker = millis();
}
static unsigned long dispenseTimeTracker = millis();
if ((millis() - dispenseTimeTracker) > dispenseDebounceTimeout) {
if (!hasDispensedLiquid && weightInLbs > weightHighThreshold) {
hasDispensedLiquid = true;
Serial.println("Weight placed.");
delay(autoDispenseDelay);
dispenseLiquid();
} else if (hasDispensedLiquid && weightInLbs <= weightLowThreshold) {
hasDispensedLiquid = false;
Serial.println("Weight removed.");
}
dispenseTimeTracker = millis();
}
}
void allWhite() {
for (int i = 0; i < NUM_LEDS; i++) {
leds[i] = CRGB::Seashell;
}
}
void dispenseLiquid() {
// Given that the mosfet range is [0, 5.0], D1 is rated only up to
// 3.3v. Therefore, we are able to achieve 50% duty cycle by
// writing 194.
// Calculations: 194 / 255 = 76%
// .76 * 3.3 = 2.5
// 50% duty cycle is achieved with a 2.5v mosfet signal output.
analogWrite(pumpControlPin, 194);
delay(800);
analogWrite(pumpControlPin, 0);
}
| [
"[email protected]"
] | |
67de5db196140f2d21e36b5212a4168a0857946b | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /net/log/trace_net_log_observer.cc | 4349c3c714ac507747b2cca50d6c886d85cf297e | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 4,044 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/log/trace_net_log_observer.h"
#include <stdio.h>
#include <memory>
#include <string>
#include <utility>
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/trace_event/trace_event.h"
#include "base/values.h"
#include "net/log/net_log_entry.h"
#include "net/log/net_log_event_type.h"
namespace net {
namespace {
// TraceLog category for NetLog events.
const char kNetLogTracingCategory[] = "netlog";
class TracedValue : public base::trace_event::ConvertableToTraceFormat {
public:
explicit TracedValue(std::unique_ptr<base::Value> value)
: value_(std::move(value)) {}
private:
~TracedValue() override {}
void AppendAsTraceFormat(std::string* out) const override {
if (value_) {
std::string tmp;
base::JSONWriter::Write(*value_, &tmp);
*out += tmp;
} else {
*out += "\"\"";
}
}
private:
std::unique_ptr<base::Value> value_;
};
} // namespace
TraceNetLogObserver::TraceNetLogObserver()
: net_log_to_watch_(nullptr), weak_factory_(this) {}
TraceNetLogObserver::~TraceNetLogObserver() {
DCHECK(!net_log_to_watch_);
DCHECK(!net_log());
}
void TraceNetLogObserver::OnAddEntry(const NetLogEntry& entry) {
std::unique_ptr<base::Value> params(entry.ParametersToValue());
switch (entry.phase()) {
case NetLogEventPhase::BEGIN:
TRACE_EVENT_NESTABLE_ASYNC_BEGIN2(
kNetLogTracingCategory, NetLog::EventTypeToString(entry.type()),
entry.source().id, "source_type",
NetLog::SourceTypeToString(entry.source().type), "params",
std::unique_ptr<base::trace_event::ConvertableToTraceFormat>(
new TracedValue(std::move(params))));
break;
case NetLogEventPhase::END:
TRACE_EVENT_NESTABLE_ASYNC_END2(
kNetLogTracingCategory, NetLog::EventTypeToString(entry.type()),
entry.source().id, "source_type",
NetLog::SourceTypeToString(entry.source().type), "params",
std::unique_ptr<base::trace_event::ConvertableToTraceFormat>(
new TracedValue(std::move(params))));
break;
case NetLogEventPhase::NONE:
TRACE_EVENT_NESTABLE_ASYNC_INSTANT2(
kNetLogTracingCategory, NetLog::EventTypeToString(entry.type()),
entry.source().id, "source_type",
NetLog::SourceTypeToString(entry.source().type), "params",
std::unique_ptr<base::trace_event::ConvertableToTraceFormat>(
new TracedValue(std::move(params))));
break;
}
}
void TraceNetLogObserver::WatchForTraceStart(NetLog* netlog) {
DCHECK(!net_log_to_watch_);
DCHECK(!net_log());
net_log_to_watch_ = netlog;
// Tracing can start before the observer is even created, for instance for
// startup tracing.
if (base::trace_event::TraceLog::GetInstance()->IsEnabled())
OnTraceLogEnabled();
base::trace_event::TraceLog::GetInstance()->AddAsyncEnabledStateObserver(
weak_factory_.GetWeakPtr());
}
void TraceNetLogObserver::StopWatchForTraceStart() {
// Should only stop if is currently watching.
DCHECK(net_log_to_watch_);
base::trace_event::TraceLog::GetInstance()->RemoveAsyncEnabledStateObserver(
this);
// net_log() != nullptr iff NetLog::AddObserver() has been called.
// This implies that if the netlog category wasn't enabled, then
// NetLog::RemoveObserver() will not get called, and there won't be
// a crash in NetLog::RemoveObserver().
if (net_log())
net_log()->RemoveObserver(this);
net_log_to_watch_ = nullptr;
}
void TraceNetLogObserver::OnTraceLogEnabled() {
bool enabled;
TRACE_EVENT_CATEGORY_GROUP_ENABLED(kNetLogTracingCategory, &enabled);
if (!enabled)
return;
net_log_to_watch_->AddObserver(this, NetLogCaptureMode::Default());
}
void TraceNetLogObserver::OnTraceLogDisabled() {
if (net_log())
net_log()->RemoveObserver(this);
}
} // namespace net
| [
"[email protected]"
] | |
dc24cfb9cfac2ab3d1f3fdd43b7dfc2e1f7a0e42 | c32ee8ade268240a8064e9b8efdbebfbaa46ddfa | /Libraries/m2sdk/ue/sys/render/C_CompressedBuffer.h | c61eb368db0acf951a1f8a98595ab8deaac943e5 | [] | 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 | 425 | h | // auto-generated file (rttidump-exporter by h0pk1nz)
#pragma once
#include <ue/C_RefPtrCounter.h>
namespace ue
{
namespace sys
{
namespace render
{
/** ue::sys::render::C_CompressedBuffer (VTable=0x01E90350) */
class C_CompressedBuffer : public ue::C_RefPtrCounter
{
public:
virtual void vfn_0001_2967E2C5() = 0;
virtual void vfn_0002_2967E2C5() = 0;
};
} // namespace render
} // namespace sys
} // namespace ue
| [
"[email protected]"
] | |
9cf1a8cbfff07db7494c6ed8754bee80b6fbd12a | 2fcc9ad89cf0c85d12fa549f969973b6f4c68fdc | /LibMathematics/CurvesSurfacesVolumes/Wm5BSplineVolume.cpp | 7a11fb87be32ac2c333e2384a733172ad2f59aed | [
"BSL-1.0"
] | permissive | nmnghjss/WildMagic | 9e111de0a23d736dc5b2eef944f143ca84e58bc0 | b1a7cc2140dde23d8d9a4ece52a07bd5ff938239 | refs/heads/master | 2022-04-22T09:01:12.909379 | 2013-05-13T21:28:18 | 2013-05-13T21:28:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,409 | cpp | // Geometric Tools, LLC
// Copyright (c) 1998-2012
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.1 (2010/10/01)
#include "Wm5MathematicsPCH.h"
#include "Wm5BSplineVolume.h"
#include "Wm5Memory.h"
namespace Wm5
{
//----------------------------------------------------------------------------
template <typename Real>
BSplineVolume<Real>::BSplineVolume (int numUCtrlPoints, int numVCtrlPoints,
int numWCtrlPoints, int uDegree, int vDegree, int wDegree)
{
assertion(numUCtrlPoints >= 2, "Invalid input\n");
assertion(1 <= uDegree && uDegree <= numUCtrlPoints - 1,
"Invalid input\n");
assertion(numVCtrlPoints >= 2, "Invalid input\n");
assertion(1 <= vDegree && vDegree <= numVCtrlPoints - 1,
"Invalid input\n");
assertion(numWCtrlPoints >= 2, "Invalid input\n");
assertion(1 <= wDegree && wDegree <= numWCtrlPoints - 1,
"Invalid input\n");
mCtrlPoint = new3<Vector3<Real> >(numUCtrlPoints, numVCtrlPoints,
numWCtrlPoints);
memset(mCtrlPoint[0][0], 0, numUCtrlPoints*numVCtrlPoints*numWCtrlPoints*
sizeof(Vector3<Real>));
mBasis[0].Create(numUCtrlPoints, uDegree, true);
mBasis[1].Create(numVCtrlPoints, vDegree, true);
mBasis[2].Create(numWCtrlPoints, wDegree, true);
}
//----------------------------------------------------------------------------
template <typename Real>
BSplineVolume<Real>::~BSplineVolume ()
{
delete3(mCtrlPoint);
}
//----------------------------------------------------------------------------
template <typename Real>
int BSplineVolume<Real>::GetNumCtrlPoints (int dim) const
{
return mBasis[dim].GetNumCtrlPoints();
}
//----------------------------------------------------------------------------
template <typename Real>
int BSplineVolume<Real>::GetDegree (int dim) const
{
return mBasis[dim].GetDegree();
}
//----------------------------------------------------------------------------
template <typename Real>
void BSplineVolume<Real>::SetControlPoint (int uIndex, int vIndex,
int wIndex, const Vector3<Real>& ctrlPoint)
{
if (0 <= uIndex && uIndex < mBasis[0].GetNumCtrlPoints()
&& 0 <= vIndex && vIndex < mBasis[1].GetNumCtrlPoints()
&& 0 <= wIndex && wIndex < mBasis[2].GetNumCtrlPoints())
{
mCtrlPoint[uIndex][vIndex][wIndex] = ctrlPoint;
}
}
//----------------------------------------------------------------------------
template <typename Real>
Vector3<Real> BSplineVolume<Real>::GetControlPoint (int uIndex, int vIndex,
int wIndex) const
{
if (0 <= uIndex && uIndex < mBasis[0].GetNumCtrlPoints()
&& 0 <= vIndex && vIndex < mBasis[1].GetNumCtrlPoints()
&& 0 <= wIndex && wIndex < mBasis[2].GetNumCtrlPoints())
{
return mCtrlPoint[uIndex][vIndex][wIndex];
}
return Vector3<Real>(Math<Real>::MAX_REAL, Math<Real>::MAX_REAL,
Math<Real>::MAX_REAL);
}
//----------------------------------------------------------------------------
template <typename Real>
Vector3<Real> BSplineVolume<Real>::GetPosition (Real u, Real v, Real w) const
{
int iumin, iumax, ivmin, ivmax, iwmin, iwmax;
mBasis[0].Compute(u, 0, iumin, iumax);
mBasis[1].Compute(v, 0, ivmin, ivmax);
mBasis[2].Compute(w, 0, iwmin, iwmax);
Vector3<Real> pos = Vector3<Real>::ZERO;
for (int iu = iumin; iu <= iumax; ++iu)
{
Real tmp0 = mBasis[0].GetD0(iu);
for (int iv = ivmin; iv <= ivmax; ++iv)
{
Real tmp1 = mBasis[1].GetD0(iv);
for (int iw = iwmin; iw <= iwmax; ++iw)
{
Real tmp2 = mBasis[2].GetD0(iw);
Real prod = tmp0*tmp1*tmp2;
pos += prod*mCtrlPoint[iu][iv][iw];
}
}
}
return pos;
}
//----------------------------------------------------------------------------
template <typename Real>
Vector3<Real> BSplineVolume<Real>::GetDerivativeU (Real u, Real v, Real w)
const
{
int iumin, iumax, ivmin, ivmax, iwmin, iwmax;
mBasis[0].Compute(u, 1, iumin, iumax);
mBasis[1].Compute(v, 0, ivmin, ivmax);
mBasis[2].Compute(w, 0, iwmin, iwmax);
Vector3<Real> derU = Vector3<Real>::ZERO;
for (int iu = iumin; iu <= iumax; ++iu)
{
Real tmp0 = mBasis[0].GetD1(iu);
for (int iv = ivmin; iv <= ivmax; ++iv)
{
Real tmp1 = mBasis[1].GetD0(iv);
for (int iw = iwmin; iw <= iwmax; ++iw)
{
Real tmp2 = mBasis[2].GetD0(iw);
Real prod = tmp0*tmp1*tmp2;
derU += prod*mCtrlPoint[iu][iv][iw];
}
}
}
return derU;
}
//----------------------------------------------------------------------------
template <typename Real>
Vector3<Real> BSplineVolume<Real>::GetDerivativeV (Real u, Real v, Real w)
const
{
int iumin, iumax, ivmin, ivmax, iwmin, iwmax;
mBasis[0].Compute(u, 0, iumin, iumax);
mBasis[1].Compute(v, 1, ivmin, ivmax);
mBasis[2].Compute(w, 0, iwmin, iwmax);
Vector3<Real> derV = Vector3<Real>::ZERO;
for (int iu = iumin; iu <= iumax; ++iu)
{
Real tmp0 = mBasis[0].GetD0(iu);
for (int iv = ivmin; iv <= ivmax; ++iv)
{
Real tmp1 = mBasis[1].GetD1(iv);
for (int iw = iwmin; iw <= iwmax; ++iw)
{
Real tmp2 = mBasis[2].GetD0(iw);
Real prod = tmp0*tmp1*tmp2;
derV += prod*mCtrlPoint[iu][iv][iw];
}
}
}
return derV;
}
//----------------------------------------------------------------------------
template <typename Real>
Vector3<Real> BSplineVolume<Real>::GetDerivativeW (Real u, Real v, Real w)
const
{
int iumin, iumax, ivmin, ivmax, iwmin, iwmax;
mBasis[0].Compute(u, 0, iumin, iumax);
mBasis[1].Compute(v, 0, ivmin, ivmax);
mBasis[2].Compute(w, 1, iwmin, iwmax);
Vector3<Real> derW = Vector3<Real>::ZERO;
for (int iu = iumin; iu <= iumax; ++iu)
{
Real tmp0 = mBasis[0].GetD0(iu);
for (int iv = ivmin; iv <= ivmax; ++iv)
{
Real tmp1 = mBasis[1].GetD0(iv);
for (int iw = iwmin; iw <= iwmax; ++iw)
{
Real tmp2 = mBasis[2].GetD1(iw);
Real prod = tmp0*tmp1*tmp2;
derW += prod*mCtrlPoint[iu][iv][iw];
}
}
}
return derW;
}
//----------------------------------------------------------------------------
template <typename Real>
Vector3<Real> BSplineVolume<Real>::GetPosition (Real pos[3]) const
{
return GetPosition(pos[0], pos[1], pos[2]);
}
//----------------------------------------------------------------------------
template <typename Real>
Vector3<Real> BSplineVolume<Real>::GetDerivative (int i, Real pos[3]) const
{
switch (i)
{
case 0:
return GetDerivativeU(pos[0], pos[1], pos[2]);
case 1:
return GetDerivativeV(pos[0], pos[1], pos[2]);
case 2:
return GetDerivativeW(pos[0], pos[1], pos[2]);
}
assertion(false, "Derivatives larger than order 3 not supported\n");
return Vector3<Real>::ZERO;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Explicit instantiation.
//----------------------------------------------------------------------------
template WM5_MATHEMATICS_ITEM
class BSplineVolume<float>;
template WM5_MATHEMATICS_ITEM
class BSplineVolume<double>;
//----------------------------------------------------------------------------
}
| [
"bazhenovc@bazhenovc-laptop"
] | bazhenovc@bazhenovc-laptop |
b66d4a48c2af76b0f5a37598233f2370280134be | a8b24dd7e1a897f31e76bd8230b003e8417ba01c | /在线Oj01/oj_server.cpp | e2b83b6aa3f1bc508a11a50d04e82e1da35a175e | [] | no_license | pengkunfan/project | ee707f23109e00f5da9fa3797eee5c8e7cbf3e0a | 677b5b7c6bb984bf8235f705c3b249399acc9406 | refs/heads/master | 2022-11-10T23:33:14.424551 | 2020-07-05T06:58:33 | 2020-07-05T06:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,065 | cpp | #include <string.h>
#include <string>
#include "httplib.h"
#include "oj_model.hpp"
//#include "oj_log.hpp"
int main()
{
using namespace httplib;//只在当前模块生效
Server svr;
OjModel ojmodel;
//【var】 :值传递,lambda内部操作不会影响外边
//【this】: 值传递this指针
//层次匹配 + 回调函数
//获取试题信息
svr.Get("/all_questions", [&ojmodel](const Request& req, Response& resp){
//获取题目列表
std::vector<Questions> ques;
ojmodel.GetAllQuestions(&ques);
if(ques.size() != 0)
printf("hahaha\n");
//获取题干信息
char buf[10240] ={'\0'};
snprintf(buf, sizeof(buf)-1, "<html>%s.%s %s</html>",ques[0].id_.c_str(),
ques[0].name_.c_str(), ques[0].star_.c_str());
std::string html;
html.assign(buf,strlen(buf));
//用模板技术填充HTML页面
resp.set_content(html, "text/html; charset=UTF-8");
});
svr.listen("0.0.0.0", 19999);//监听所有ip
return 0;
}
| [
"[email protected]"
] | |
e39182378b3cbfb70a50a232ec013820ee8e15d5 | c4266e711eaeefc6c19f93e12a7189d61eba3861 | /sy3.cpp | 3406e769ad9b225523bffc7f0d066c04afd09d2d | [] | no_license | jjAugust/C_project | f84a22ecac37d22efd3bf9fda51e35dead737e17 | 2534a1961199582f080df9e99767ef3c114986b9 | refs/heads/master | 2021-01-11T03:26:02.818369 | 2016-10-16T05:27:19 | 2016-10-16T05:27:19 | 71,031,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,936 | cpp | #ifndef _BTREE_H
#define _BTREE_H
#define MIN_T 3
#define MAX_T (MIN_T * 2)
typedef struct BTreeNodedata BTreeNodedata;
typedef struct BTreeNodedata *BTreeNode;
typedef struct BTreedata BTreedata;
typedef struct BTreedata *BTree;
/*
Create(BTree *Bt):初始化操作。构造一个空的B-Tree树。
Search(p,k):查找操作。在p为根的B-Tree树中查找关键字值为k的元素;如果操作成功,则返回指向该元素的指针;否则,返回NULL。
Insert(e):插入操作。将指定的不重复的元素e插入到B-Tree树中;插入成功后返回OK,否则返回ERROR。
Delete(k,e):删除操作。删除关键字的值为k的元素并将其返回到e中,且满足定义7.4;删除成功后返回OK,否则返回ERROR。
Traverse():输出操作。按照某种次序输出B-Tree树中的所有元素;如果操作成功,则返回OK;否则,返回ERROR。
*/
/*
* B树结点结构体
*/
struct BTreeNodedata
{
int n; //关键字个数
int leaf; //是否是叶子结点,1为叶子结点,0反之
int key[MAX_T - 1]; //关键字,这里的关键字为了简便编程设为int
BTreeNode child[MAX_T]; //子结点
};
/*
* B树的结构体
*/
struct BTreedata
{
BTreeNode root; //B树的根结点
};
#define BTREE_NODE_SIZE sizeof(BTreeNodedata)
#define BTREE_SIZE sizeof(BTreedata)
/*
BTreeNode allocate_node(); //为结点分配空间
void btree_create(BTree tree); //初始化树
void btree_search(BTreeNode node, int key); //寻找关键字位置
void btree_split_child(BTreeNode node, int location); //分裂子结点
void btree_insert_nonfull(BTreeNode node, int key); //向未满结点插入关键字
void btree_insert(BTree tree, int key); //向树插入关键字
void display_node(BTreeNode *node_first, int n); //显示以结点node_first为父结点的树
void display_btree(BTree tree); //显示整棵树
BTreeNode btree_minimum(BTreeNode node); //以node为根结点,寻找最小关键字
BTreeNode btree_maximum(BTreeNode node); //以node为根结点,寻找最大关键字
void btree_min(BTree tree); //在整棵树中寻找最小关键字
void btree_max(BTree tree); //在整棵树中寻找最大关键字
void btree_left(BTreeNode parent, BTreeNode node, BTreeNode othernode, int location); //将父结点、右兄弟、该结点的关键字调整
void btree_right(BTreeNode parent, BTreeNode node, BTreeNode othernode, int location); //将父结点、左兄弟、该结点的关键字调整
int btree_merge_child(BTreeNode parent, int location); //合并子结点,并返回下降子结点的位置
void btree_delete_leaf(BTreeNode node, int location); //删除叶子结点关键字
int btree_delete_node_in(BTreeNode r_node, int i); //删除内结点关键字,并返回下降子结点的位置
void btree_delete_node(BTreeNode r_node, int key); //删除以r_node为根结点的树中关键字
void btree_delete(BTree tree, int key); //删除树中的关键字
*/
#endif
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <assert.h>
/*
* 为新结点分配空间
*/
BTreeNode
allocate_node()
{
BTreeNode node = (BTreeNode) malloc (BTREE_NODE_SIZE);
return node;
}
/*
* 生成一棵空树
* 关键字个数为0,且为叶子结点
*/
void btree_create(BTree tree)
{
BTreeNode r_node = allocate_node();
(r_node)->n = 0;
(r_node)->leaf = 1;
(tree)->root = r_node;
}
/*
* 在以node为根结点的树中,寻找关键字位置
* 返回关键字所在结点,并将关键字位置保存在location
*/
void btree_search(BTreeNode node, int key)
{
int j = 0;
/*
* 遍历当前结点,寻找恰当的关键字,如果找到相等的关键字,返回结点并将关键字位置保存在location
* 如果没找到相等结点,且该结点为叶子结点,则报错
* 否则递归寻找
*/
while(j < node->n && key > node->key[j])
j++;
if(j < node->n && key == node->key[j])
{
printf("the %d key's location is %d in the node %p\n", key, j, node);
}
else if(node->leaf)
{
printf("error:there is no a key\n");
}
else btree_search(node->child[j], key);
}
/*
* 分裂父结点node中位置为location的子结点的满结点
*/
void btree_split_child(BTreeNode node, int location)
{
/* 建立新的空结点 */
BTreeNode newnode = allocate_node();
BTreeNode childnode = node->child[location];
int i = 0;
/* 初始化空结点newnode,将子结点childnode的信息复制到新结点node中 */
newnode->leaf = childnode->leaf;
newnode->n = MIN_T - 1;
/* 将子结点childnode后T-1个关键字复制到新结点中,并改变子结点的n值 */
for(i = 0;i <= MIN_T - 2;i++)
newnode->key[i] = childnode->key[i + MIN_T];
childnode->n = MIN_T - 1;
/* 如果子结点非叶子结点,则相应的将子结点的结点点复制到新结点中 */
if(!childnode->leaf)
for(i = 0;i <= MIN_T - 1;i++)
newnode->child[i] = childnode->child[i + MIN_T];
/* 将父结点对应的关键字以及子结点位置向后移动一位 */
for(i = node->n;i > location;i--)
{
node->key[i] = node->key[i - 1];
node->child[i+1] = node->child[i];
}
/* 为父结点增加新的关键字和子结点,并修改n值 */
node->child[location + 1] = newnode;
node->key[location] = childnode->key[MIN_T - 1];
node->n = node->n + 1;
}
/*
* 对非满结点进行插入关键字
*/
void btree_insert_nonfull(BTreeNode node, int key)
{
int i = node->n - 1;
if(node->leaf)
{
/* 该结点为叶子结点时,找到对应位置,将关键字插入,并对结点node做出修改 */
while(i >=0 && key < node->key[i])
{
node->key[i+1] = node->key[i];
i--;
}
node->key[i+1] = key;
node->n = node->n + 1;
}
else
{
/* 非叶子结点时,查找对应子结点,判断其是否为满结点,是,则分裂,否递归插入 */
while(i >=0 && key < node->key[i])
i--;
i++;
if(node->child[i]->n == MAX_T - 1)
{
btree_split_child(node, i);
if(key > node->key[i])
i++;
}
btree_insert_nonfull(node->child[i], key);
}
}
/*
* 对整棵树进行插入关键字
* 当树为有且只有一个关键字,且已满时,需要建立新的结点作为树的根结点,
* 而当原树的根结点作为新结点的子结点,进行分裂操作
* 否则,直接进行非满结点插入操作
*/
void btree_insert(BTree tree, int key)
{
BTreeNode r_node = tree->root;
if(r_node->n == MAX_T - 1)
{
BTreeNode r_node_new = allocate_node();
r_node_new->leaf = 0;
r_node_new->n = 0;
r_node_new->child[0] = r_node;
tree->root = r_node_new;
btree_split_child(r_node_new, 0);
btree_insert_nonfull(r_node_new, key);
}
else btree_insert_nonfull(r_node, key);
}
/*
* 为了验证插入以及删除结果正确,添加输出函数
* 输出以parent为父结点的子树的所有关键字
* 这里将所有的同一层的结点放入到一个数组中,方便输出
* 第一个参数node_first作为每一层结点数组的起始地址
* n为该层结点数
*/
void display_node(BTreeNode *node_first, int n)
{
int i = 0, j = 0, k = 0,all = 0;
BTreeNode *node = node_first;
/* 将该层的结点所有的关键字输出,不同结点以“ ”为分隔,每层以“$$”为分隔 */
for(i = 0; i < n; i++)
{
for(j = 0; j < (*(node + i))->n; j++)
{
printf("%d ", (*(node + i))->key[j]);
}
all = all + (*(node + i))->n + 1;
//printf(" %p ", *(node + i));
printf(" ");
}
printf("$$\n");
if(!(*node)->leaf)
{
BTreeNode nodes[all];
i = 0;
for(j = 0; j < n; j++)
{
for(k = 0; k <= (*(node + j))->n; k++)
{
nodes[i] = (*(node + j))->child[k];
i++;
}
}
display_node(nodes, all);
}
}
/*
* 为了验证插入和删除操作的正确性,添加输出函数
* 将整棵树输出
*/
void display_btree(BTree tree)
{
BTreeNode r_node = tree->root;
display_node(&r_node, 1);
}
/*
* 返回以node为根结点树的最小关键字的结点,关键字的位置肯定为0
*/
BTreeNode btree_minimum(BTreeNode node)
{
BTreeNode newnode = node;
if(newnode->n < 1)
{
printf("this is null tree\n");
return NULL;
}
if(node->leaf)
return newnode;
else
newnode = btree_minimum(node->child[0]);
return newnode;
}
/*
* 返回以node为根结点树的最大关键字的结点,关键字的位置肯定为该结点的n-1值
*/
BTreeNode btree_maximum(BTreeNode node)
{
BTreeNode newnode = node;
if(newnode->n < 1)
{
printf("this is null tree\n");
return NULL;
}
if(node->leaf)
return newnode;
else
newnode = btree_maximum(node->child[node->n]);
return newnode;
}
/*
* 输出整棵树的最小关键字
*/
void btree_min(BTree tree)
{
BTreeNode r_node = tree->root;
BTreeNode n_node = btree_minimum(r_node);
printf("the min is %d\n", n_node->key[0]);
}
/*
* 输出整棵树的最大关键字
*/
void btree_max(BTree tree)
{
BTreeNode r_node = tree->root;
BTreeNode n_node = btree_maximum(r_node);
printf("the max is %d\n", n_node->key[n_node->n - 1]);
}
/*
* 当下降的结点node的关键字个数为T-1时,
* 为了满足下降过程中,遇到的结点的关键字个数大于等于T,
* 对结点parent、node、othernode三个结点的关键字做调整。
* 当node在other左侧时,即node的右结点时(父结点的右子结点), * 在T+1位置,增加一个关键字,其值为父结点对应的关键字值,
* 将父结点对应关键字值赋值为右子结点中的第一个关键字。
* 将右子结点的关键字和子结点(如果有的话)向前移动一位
* 修改右子结点以及该结点的n值
*/
void btree_left(BTreeNode parent, BTreeNode node, BTreeNode othernode, int location)
{
int i = 0;
node->key[node->n] = parent->key[location];
parent->key[location] = othernode->key[0];
for(i = 0; i <= othernode->n - 2; i++)
othernode->key[i] = othernode->key[i + 1];
if(!othernode->leaf)
{
node->child[node->n + 1] = othernode->child[0];
for(i = 0; i <= othernode->n - 1; i++)
othernode->child[i] = othernode->child[i + 1];
}
node->n = node->n + 1;
othernode->n = othernode->n - 1;
}
/*
* 当下降的结点node的关键字个数为T-1时,
* 为了满足下降过程中,遇到的结点的关键字个数大于等于T,
* 对结点parent、node、othernode三个结点的关键字做调整。
* 当node在other右侧时,即node的左结点时(父结点的左子结点),
* node结点的关键字和子结点(如果有的话)向后移动一位,
* 在第一个位置增加一个关键字,其值为父结点对应的关键字值,
* 将父结点对应关键字值赋值为左子结点中的最后一个关键字。
* 修改左子结点和该结点的n值
*/
void btree_right(BTreeNode parent, BTreeNode node, BTreeNode othernode, int location)
{
int i = 0;
for(i = node->n - 1; i >= 0; i--)
othernode->key[i+1] = othernode->key[i];
node->key[0] = parent->key[location];
parent->key[location] = othernode->key[othernode->n];
if(!node->leaf)
{
node->child[0] = othernode->child[othernode->n + 1];
for(i = othernode->n; i >= 0; i--)
othernode->child[i + 1] = othernode->child[i];
}
node->n = node->n + 1;
othernode->n = othernode->n - 1;
}
/*
* 合并两个关键字个数为T-1父结点为parent位置为location的子结点
* 以父结点对应的关键字为中间值连接两个子结点
* 并返回需要下降的子结点位置
*/
int btree_merge_child(BTreeNode parent, int location)
{
int i;
BTreeNode lnode = NULL;
BTreeNode rnode = NULL;
if(location == parent->n)
location--;
lnode = parent->child[location];
rnode = parent->child[location + 1];
/* 将父结点对应的关键字以及右兄弟所有的关键字复制该结点,同时修改左子的n值 */
lnode->key[lnode->n] = parent->key[location];
for(i = 0; i < rnode->n; i++)
{
lnode->key[MIN_T + i] = rnode->key[i];
lnode->n++;
}
/* 如果有子结点同样复制到该结点 */
if(!rnode->leaf)
for(i = 0; i <= rnode->n; i++)
lnode->child[MIN_T + i] = rnode->child[i];
rnode->n= 0;
lnode->n = MAX_T - 1;
/* 对父结点相应的关键字和子结点位置发生变化 */
for(i = location; i < parent->n - 1; i++)
{
parent->key[i] = parent->key[i + 1];
parent->child[i + 1] = parent->child[i + 2];
}
/* 调整父结点的n值 */
parent->n = parent->n - 1;
rnode = NULL;
return location;
}
/*
* 对叶子结点node位置为location的关键字删除
* 直接将位置location后的关键字向前移动一位
*/
void btree_delete_leaf(BTreeNode node, int location)
{
int i = 0;
for(i = location; i < node->n - 1; i++)
node->key[i] = node->key[i + 1];
node->n = node->n - 1;
}
/*
* 删除该层数组坐标为i的关键字
*/
int btree_delete_node_in(BTreeNode r_node, int i)
{
BTreeNode lnode = r_node->child[i];
BTreeNode rnode = r_node->child[i + 1];
int temp = 0;
/*
* 当前于该位置的关键字的左子结点关键字个数大于等于T时,
* 寻找该位置的关键的前驱(左子结点的最大关键字)
*/
if(lnode->n >= MIN_T)
{
BTreeNode newnode = btree_maximum(lnode);
temp = r_node->key[i];
r_node->key[i] = newnode->key[newnode->n - 1];
newnode->key[newnode->n - 1] = temp;
}
/*
* 相反的,若右子结点符合条件,则找寻后继(即右子结点的最小关键字)
*/
else if(rnode->n >= MIN_T)
{
BTreeNode newnode = btree_minimum(rnode);
temp = r_node->key[i];
r_node->key[i] = newnode->key[0];
newnode->key[0] = temp;
i++;
}
/*
* 当左右子结点都不符合条件,则合并两个子结点
*/
else i = btree_merge_child(r_node, i);
return i;
}
/*
* 删除以r_node为根结点的树的关键字key
*/
void btree_delete_node(BTreeNode r_node, int key)
{
int i = 0;
/* 寻找关键字位置,或者下降的子结点位置 */
while(i < r_node->n && key > r_node->key[i])
i++;
/* 若再该层且为叶子结点删除结点,否则下降寻找结点删除 */
if(i < r_node->n && key == r_node->key[i])
if(r_node->leaf)
btree_delete_leaf(r_node, i);
else
{
i = btree_delete_node_in(r_node, i);
btree_delete_node(r_node->child[i], key);
}
else
{
if(r_node->leaf)
printf("there is no the key %d!!\n", key);
else
{
if(r_node->child[i]->n >= MIN_T){
btree_delete_node(r_node->child[i], key);}
else
{
if(i > 0 && r_node->child[i - 1]->n >= MIN_T)
{
btree_right(r_node, r_node->child[i], r_node->child[i - 1], i);}
else if(i < r_node->n && r_node->child[i + 1]->n >= MIN_T)
btree_left(r_node, r_node->child[i], r_node->child[i + 1], i);
else
i = btree_merge_child(r_node, i);
btree_delete_node(r_node->child[i], key);
}
}
}
}
/*
* 删除树内的关键字key,如果根结点为空,则替换根结点
*/
void btree_delete(BTree tree, int key)
{
BTreeNode r_node = tree->root;
btree_delete_node(r_node, key);
if(tree->root->n == 0 && tree->root->leaf == 0)
tree->root = tree->root->child[0];
}
int main()
{
BTree tree = (BTree) malloc (BTREE_SIZE);
tree->root = (BTreeNode) malloc (BTREE_NODE_SIZE);
int keys[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,24,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,
82,81,83,84,85,86,87,88,89,90,91,92,99,94,93,95,96,97,98,100};
int i = 0;
btree_create(tree);
for(i = 0; i <= 99; i++){
btree_insert(tree, keys[i]);
//display_btree(&tree);
}
btree_max(tree);
display_btree(tree);
btree_max(tree);
btree_min(tree);
btree_search(tree->root,5);
btree_search(tree->root,33);
btree_delete(tree, 100);
display_btree(tree);
btree_delete(tree, 94);
display_btree(tree);
btree_delete(tree, 81);
display_btree(tree);
btree_delete(tree, 36);
display_btree(tree);
btree_delete(tree, 42);
display_btree(tree);
btree_max(tree);
btree_min(tree);
free(tree);
return 0;
}
| [
"[email protected]"
] | |
b8e0933a042794dd7950dd4e1b772ab45c453638 | 75a1ce195fa1556e79c0b12e6ec600a0942e91a7 | /test/idl/filebuf.hpp | 6b153fe79e3509420897e558e97956ca1928b6c5 | [
"Apache-2.0"
] | permissive | lineCode/jmsg | 44ad1d3405d00a8b9f9a20c255edcb4dbc394407 | d3d3462d76dfdbf8f01f64ba4354f63b56805ceb | refs/heads/master | 2021-01-01T06:09:37.659428 | 2016-11-16T13:57:16 | 2016-11-16T13:57:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,632 | hpp | #pragma once
#include <fstream>
static const char * const s_prefix[] = {
"",
"\t",
"\t\t",
"\t\t\t",
"\t\t\t\t",
"\t\t\t\t\t",
"\t\t\t\t\t\t",
"\t\t\t\t\t\t\t",
"\t\t\t\t\t\t\t\t",
"\t\t\t\t\t\t\t\t\t",
"\t\t\t\t\t\t\t\t\t\t",
"\t\t\t\t\t\t\t\t\t\t\t",
"\t\t\t\t\t\t\t\t\t\t\t\t",
"\t\t\t\t\t\t\t\t\t\t\t\t\t",
};
class filebuf {
public:
filebuf(std::size_t N, const char * file_name, const char * header = nullptr)
: m_cur(new char[N])
, m_remain(N)
, m_bp(m_cur)
, m_N(m_remain)
, m_file(file_name)
, m_header(header)
{
m_cur[0] = '\0';
}
~filebuf()
{
delete [] m_bp;
}
public:
template<typename ... Types>
void pf(std::size_t lvl, const char * format, Types ... rest)
{
__pf_prefix(lvl);
int ret = std::snprintf(m_cur, m_remain, format, rest...);
if (ret < 0) {
throw "no enough space";
}
m_cur += ret;
m_remain -= ret;
}
void pf_type_tail()
{
pf(0, ";\n\n");
}
void output()
{
std::ofstream ofs(m_file);
if (m_header) ofs << m_header;
ofs << m_bp;
//std::printf("%s\n", m_bp);
}
private:
void __pf_prefix(std::size_t lvl)
{
if (sizeof(s_prefix) / sizeof(s_prefix[0]) <= lvl) {
throw "too deep indent!!!!";
}
int ret = std::snprintf(m_cur, m_remain, "%s", s_prefix[lvl]);
if (ret < 0) {
throw "no enough space";
}
m_cur += ret;
m_remain -= ret;
}
private:
char * m_cur;
std::size_t m_remain;
char * const m_bp;
std::size_t const m_N;
const char * m_file;
const char * m_header;
};
extern filebuf s_outf_types;
extern filebuf s_outf_id;
extern filebuf s_outf_converter;
extern filebuf s_outf_sender;
extern filebuf s_outf_rcver;
| [
"[email protected]"
] | |
ef53133c613df781b4d9180d1a7ce56b8420056e | 856e293846602600fa840654d38ad9762c6c5498 | /solucaoAula1.cpp | 785a8628d7fbbfbb3fad08fc614a866057c4d66c | [] | no_license | ThiagoSTeixeira/Desafios | 14d746a59410a7820144415b96cf99df559dd9e7 | cd5de5850b7394c940573046f58ca179b1081e31 | refs/heads/master | 2021-01-09T03:59:37.388796 | 2020-05-18T21:42:09 | 2020-05-18T21:42:09 | 242,238,747 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | /*NOTAS:
Para encontrar o teto: int(ceil(x/n)) ou (x+n-1)/n !!!!
*/
#include<bits/stdc++.h>
using namespace std;
/*Programa D
Bastava contar a quantidade de zeros antes do primeiro 1 e depois do ultimo 1, e depois subtrair da quantidade total de zeros
*/
//Programa E
int main(){
int n, pos, l, r;
cin >> n >> pos >> l >> r;
int op1 = abs(r - pos);
int op2 = abs(l- pos);
if (l != 1 && r !=n){
cout<<min(op1, op2) + r -l + 2 << endl;
//incompleto
}
} | [
"[email protected]"
] | |
3a86b7b670cc52504cb8ba9714259dd99fdd0fc6 | 09ea1901af1caa0cd7a6977209c384e08278a371 | /test/network/JPTest/src/JPTest/jptmainwindow.h | 02716b98c0b2909917e8bcaa5f3e830e0dc87a41 | [] | no_license | sid1980/JAGUAR | e038e048a0542d7f3b67c480d27881f91ef42e4e | 2dc262fdc10a600335f71878e092265bc9da77c2 | refs/heads/master | 2021-12-03T05:19:44.367320 | 2014-05-01T23:21:27 | 2014-05-01T23:21:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,251 | h | #ifndef JPTMAINWINDOW_H
#define JPTMAINWINDOW_H
#include <QMainWindow>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMessageBox>
#include "jptestcontroller.h"
const QString JAG_COLOR = "blue";
const QString MAV_COLOR = "green";
const QString PAYLOAD_COLOR = "black";
namespace Ui {
class JPTMainWindow;
}
class JPTMainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit JPTMainWindow(QWidget *parent = 0);
~JPTMainWindow();
public slots:
void RefreshPortList();
void BrowseWkDirSlot();
void RefreshTestList();
void StartTest();
void StopTest();
void StepTest();
void LoadTest();
void RemoveNotification(int tabIndex);
void UpdateJaguarIDS(QString JAGID);
void UpdateTestScript(QStringList newScript);
void UpdateP2Script(QStringList newP2Script);
void UpdateP3Script(QStringList newP3Script);
void UpdatePortSelection(const QString &UnusedPortVar);
void HandleTestListSelectionChanged();
void AppendToOutbox(QByteArray data, bool newPacketStart, int packetLength);
void CacheTestOptions();
void ProcessDiffResults(JPacketDiffResults);
void HandleFinishedSending();
void HandleTestStarted();
void HandleTestEnded();
void HandleUnableToStartTest();
private:
Ui::JPTMainWindow *ui;
QHBoxLayout* mainLayout;
QVBoxLayout* outboxTabPacketListLayout;
QVBoxLayout* outboxTabOutboxLayout;
QHBoxLayout* outboxTabLayout;
QVBoxLayout* leftLayout;
QVBoxLayout* rightLayout;
protected:
JPTestController* jptestManager;
QDir* workingDirectory;
QColor notificationColor;
JPTestOptions testOptions;
QAction* startAction;
QAction* stopAction;
QAction* stepAction;
QAction* loadAction;
int outgoingPacketIndex;
int packetBytesSent;
int p2InboxPassFailIndex;
int p3InboxPassFailIndex;
bool running;
bool doneSending;
// Setup Methods
void RegisterMetaTypes();
void SetupLayouts();
void SetInitialStates();
void ConnectSignalsAndSlots();
// Utility Methods
QDir GetInitialWorkingDir(); // CLS - needed to account for OS X .app files
QString GetJptestFilename(bool IncludeWorkingDir = true);
QString GetJPacketPath();
QString GetPortName();
QString GetHtmlString(const QString& text, const QString& color);
QString FormatByteToHexString(const unsigned char &byte);
void SetRunning(const bool& SetRunning = true);
// UI Methods
void ShowStatusBarMessage(const QString& msg);
void ShowMessageBoxMessage(const QString& msg);
void LogToMessageArea(const QString& msg);
void UpdateJAGIDStrings(const QString& myName, const QString& p2Name, const QString& p3Name);
void PostNotification(const int& tabIndex);
void ClearMailboxes();
// Inboxes/outboxes methods
void AppendToStagingArea(char);
void AppendToP2Inbox(const char& byte, const bool& pass);
void AppendToP3Inbox(const char& byte, const bool& pass);
void AppendToGarbageArea(const char& garbageByte);
void StartNewP2Packet(QByteArray packetStart, QList<bool> passList);
void StartNewP3Packet(QByteArray packetStart, QList<bool> passList);
};
#endif // JPTMAINWINDOW_H
| [
"[email protected]"
] | |
87a9a00189a720cbd681e6dd12b5d9871303e9a4 | 61bd7cbe6c7886e0c4629a2d0bd1aef6f1f9d2e1 | /morse.cpp | 44226a3e4e00565ccb155702dee27cc31e641089 | [] | no_license | iamrasheeq/MorseCode-Encryption | 78b54b9a681397b6b649a2f3c776ed3a52572b20 | e995399926403eae18219b5ae25d1a5a9afc4103 | refs/heads/master | 2021-07-15T06:35:16.536693 | 2020-11-23T19:58:57 | 2020-11-23T19:58:57 | 227,539,388 | 1 | 0 | null | 2019-12-16T12:07:01 | 2019-12-12T06:48:26 | C++ | UTF-8 | C++ | false | false | 1,962 | cpp | #include <iostream>
#include <string>
#include <string.h>
using namespace std;
string getString(char x)
{
string s(1, x);
return s;
}
bool com(string s1,string s2){
if (s1.length() != s2.length())
{
return false;
}
for(int i = 0;i<s1.length(); i++){
if (s1[i] != s2[i])
{
return false;
}
}
return true;
}
int main(){
char c;
int n=0,n1 = 1;
bool f1 = false;
string s1,s2;
string morseC[] = {".____","..___","...__","...._",".....","_....","__...","___..","____.","_____","._","_...","_._.","_..",".",".._.","__.","....","..",".___","_._","._..","__","_.","___",".__.","__._","._.","...","_",".._","..._",".__","_.._","_.__","__.."};
cout<<"'.' = dot ; '_' = dash"<<endl;
cout<<"Enter Morse Code: ";
getline(cin,s1);
cout<<"Encrypted Message: ";
s1 = s1 + " ";
for (int i = 0; i < s1.length(); i++)
{
if (s1[i] == ' ')
{
for (int j = 0; j < 36; j++)
{
//cout<<morseC[j]<<"|_|"<<s2<<endl;
if ((com(morseC[j],s2)) && j>=10)
{
c = (char)(j+55);
cout<<c;
n1 = 0;
}
else if (com(morseC[j],s2))
{
cout<<j+1;
n1 = 0;
}
}
if (n1 != 0)
{
cout<<" ";
}
n1 = 1;
n=0;
}
if (n == 0)
{
s2 = getString(s1[i]);
n++;
}else
{
s2 = s2 + s1[i];
}
if (s2[0] == ' ')
{
s2.erase(s2.begin() + 0);
}
}
cout<<endl;
}
| [
"[email protected]"
] | |
6c7b32e5db3d1027ded4a1cf124de3484742dbd2 | 2a01d8d0b5715216cb77d08b973676fe8295bb6a | /cpp/cpp_libs/src/eigen_quaternion.cpp | 526bf4801afc89599dbba574b9694be81f11d18a | [
"BSD-3-Clause"
] | permissive | maximilianharr/code_snippets | 78cb72de2f5765f8578ee46b381bb8abf25918bc | 8b271e6fa9174e24200e88be59e417abd5f2f59a | refs/heads/master | 2022-12-12T23:13:12.184496 | 2020-09-04T16:54:47 | 2020-09-04T16:54:47 | 261,803,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,745 | cpp | /**
* @file eigen_quaternion.cpp
* @author Maximilian Harr <[email protected]>
* @date 17.06.2017
*
* @brief Eigen quaternion computations
*
*
*
* Coding Standard:
* wiki.ros.org/CppStyleGuide
* https://google.github.io/styleguide/cppguide.html
*
*
* @bug
*
*
* @todo
*
*
*/
// PRAGMA
// SYSTEM INCLUDES
#include <iostream> /* Header that defines the standard input/output stream objects */
#include <cstdlib> /* Header that defines several general purpose functions */
#include <string>
#include <Eigen/Dense> /* template library for linear algebra http://eigen.tuxfamily.org */
#include <math.h> /* Defines M_PI for pi value */
#include <Eigen/Eigenvalues>
#include <Eigen/Geometry>
// PROJECT INCLUDES
// LOCAL INCLUDES
// FORWARD REFERENCES
// FUNCTION PROTOTYPES
/** @brief Standard command line parameter processing.
* @param Pass command line parameters
* @return 0 if -h flag is set
*/
int cmd_check(int, char*[]);
// GLOBAL VARIABLES
using namespace Eigen;
using namespace std;
void outputAsMatrix(const Eigen::Quaterniond& q)
{
std::cout << "R=" << std::endl << q.normalized().toRotationMatrix() << std::endl;
}
//// MAIN //////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
/* Check command line options. Stop execution if -h is set. */
if(!cmd_check(argc,argv)) return 0;
/* Specify roation axis and angle */
Eigen::Vector3d rotation_axis{0, 0, 1};
Eigen::Vector3d pose{0, 0, 1};
double angle = 0;
if(argc == 2){
angle = atof(argv[1]);}
else{
angle = M_PI/8.0;
}
/* Compute Quaternion by hand */
auto sinA = std::sin(angle / 2);
auto cosA = std::cos(angle / 2);
Eigen::Quaterniond q;
q.x() = rotation_axis(0) * sinA;
q.y() = rotation_axis(1) * sinA;
q.z() = rotation_axis(2) * sinA;
q.w() = cosA;
/* Let Eigen compute Quaternion (use Vector3d::UnitZ() instead of rotation_axis) */
Eigen::Quaterniond q2 = Eigen::Quaterniond{ Eigen::AngleAxisd{ angle, rotation_axis } };
/* Compare rotation matrices */
outputAsMatrix( q );
outputAsMatrix( q2 );
/* Get rotation matrix from quaternion */
Matrix3d m;
m = Eigen::Quaterniond(q2);
std::cout << "Quaternion q2: " << std::endl << q2.x() << std::endl
<< q2.y() << std::endl << q2.z() << std::endl << q2.w() << std::endl;
std::cout << "Rotation matrix m of Quaternion q2: " << std::endl << m << std::endl;
/* Multiplication of quaternions */
Matrix3d m2;
m2 = Eigen::Quaterniond(q2*q2);
std::cout << "m*m: " << std::endl << m*m << std::endl;
std::cout << "Rotation matrix of q2*q2: " << std::endl << m2 << std::endl;
/* Dividing Quaternions */
Matrix3d m3;
m3 = Eigen::Quaterniond(q2.inverse());
std::cout << "m.inverse(): " << std::endl << m.inverse() << std::endl;
std::cout << "Rotation matrix of q2.inverse(): " << std::endl << m3 << std::endl;
/* Rotate Vector */
Eigen::Vector3d x_axis = Eigen::Vector3d::UnitX();
std::cout << "q2*x_axis: " << std::endl << q2*x_axis << std::endl;
/* Get rotation axis of Quaternion */
Eigen::AngleAxisd rot_axis_m(m);
Eigen::AngleAxisd rot_axis_q2(q2);
rot_axis_m.axis().cross(rot_axis_q2.axis());
std::cout << "Rotation axis of m: " << std::endl << rot_axis_m.axis() << std::endl;
std::cout << "Rotation axis of q2: " << std::endl << rot_axis_q2.axis() << std::endl;
/* Get Euler Angles from Quaternion */
Eigen::Vector3d euler = q2.toRotationMatrix().eulerAngles(0,1,2);
std::cout << "Euler angles yf q2: " << std::endl << euler << std::endl;
/* Get Quaternion from euler angles */
Eigen::Quaterniond q3;
q3 = AngleAxisd(euler[0], Eigen::Vector3d::UnitX())*
AngleAxisd(euler[1], Eigen::Vector3d::UnitY())*
AngleAxisd(euler[2], Eigen::Vector3d::UnitZ());
std::cout << "q3 from euler angles: " << std::endl << q3.x() << std::endl
<< q3.y() << std::endl << q3.z() << std::endl << q3.w() << std::endl;
/* Rotate covariance matrix */
Eigen::MatrixXd covariance_q = Eigen::MatrixXd::Zero(3,3);
Eigen::Quaterniond q4 = Eigen::Quaterniond{ Eigen::AngleAxisd{ angle, Eigen::Vector3d::UnitZ() } };
Eigen::MatrixXd covariance_r = Eigen::MatrixXd::Zero(3,3);
Matrix3d rotation;
rotation = Eigen::AngleAxisd{ Eigen::AngleAxisd( angle, Eigen::Vector3d::UnitZ()) };
covariance_q(0,0) = 1;
covariance_q(1,1) = 2;
covariance_q(2,2) = 3;
covariance_r(0,0) = 1;
covariance_r(1,1) = 2;
covariance_r(2,2) = 3;
covariance_q = q * covariance_q; // Rotate covariance matrix in lane coordinates
covariance_q = covariance_q*covariance_q.transpose();
covariance_r = rotation*covariance_r*covariance_r.transpose()*rotation.transpose();
std::cout << "covariance_q:\n " << covariance_q << std::endl;
std::cout << "covariance_r:\n " << covariance_r << std::endl;
}
//// FUNCTION DEFINITIONS //////////////////////////////////////////////////////////////////////////
int cmd_check(int argc, char* argv[])
{
int option;
/* third argument of getopt specifies valid options and whether they need input(:) */
while((option = getopt(argc,argv,"hp:"))>=0)
{
switch (option)
{
case 'h': std::cout
<< "Usage: <filename> [options] \n\n"
<< "<desription> \n\n"
<< "Options: \n"
<< " -h show this help message and exit \n"
<< " -p <PARAMETER> <description> \n"
<< " \n";
return 0; /* do not execute main with this option */
case 'p': std::cout << "-p = " << optarg << "\n"; /* optarg is option argument */
break;
}
}
return 1;
}
| [
"[email protected]"
] | |
b96d283d1bb9684d6cc3e90d05ca23ccde5dc499 | aec880e28a57fee7d219ea52d32c98f581304ffc | /VFASSensor.cpp | 88c6720d8212e58dacee8c342e6d1ecddbc691f3 | [] | no_license | michaelkoetter/mavlink2sport | 33e27b38b938c9f9fecb0b662fe1a5daf58e5f1c | 311422b392417635366def0751cf293c36398c31 | refs/heads/master | 2020-12-24T14:10:44.351210 | 2015-03-15T18:45:41 | 2015-03-15T18:45:41 | 32,017,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 645 | cpp | #include "VFASSensor.h"
VFASSensor::VFASSensor()
: pollSeq(0), voltage(0), current(0) {
}
VFASSensor::~VFASSensor() {
}
float VFASSensor::getCurrent() const {
return current;
}
void VFASSensor::setCurrent(float current) {
this->current = current;
}
float VFASSensor::getVoltage() const {
return voltage;
}
void VFASSensor::setVoltage(float voltage) {
this->voltage = voltage;
}
bool VFASSensor::Poll(SPortData_t* data) {
switch (pollSeq++ % 2) {
case 0:
data->dataTypeId = VFAS_FIRST_ID;
data->data = voltage * 100;
break;
case 1:
data->dataTypeId = CURR_FIRST_ID;
data->data = current * 10;
break;
}
return true;
}
| [
"[email protected]"
] | |
6e54c2f35dd97cc29c1aa5c5dc003885483a54ce | d9142bdff80cad8a1bf5a138f55c442a04e2674d | /2449.cpp | 4baab83d5584c8d6902fa2261e8d05c783604226 | [] | no_license | epicurean21/Algorithm | 280a84d5f73db7787eb2589a3a37901983496691 | d5fa2f0318d45bdd17c5ccda9e72468b4711100c | refs/heads/master | 2023-07-22T05:30:47.982546 | 2023-07-09T06:22:09 | 2023-07-09T06:22:09 | 199,615,976 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | cpp | #include <iostream>
using namespace std;
#define MAX 201
int N, K, color[21], cnt[MAX], bulb[MAX]; // index, color
int countBulb(int clr) { // clr가 연속으로 몇개 켜져있는지.
int tmp = 0;
int ret = 0;
for (int i = 1; i <= N; i++) {
if (clr == bulb[i]) {
tmp++;
ret = max(ret, tmp);
} else
tmp = 0;
}
return ret;
}
int countClr() { // 현재 켜져있는 색상이 몇종류인지
bool chk[MAX] = {false,};
int tmp = 0;
for (int i = 1; i <= N; i++) {
if (chk[bulb[i]] != 1) {
chk[bulb[i]] = 1;
tmp++;
}
}
return tmp;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
} | [
"[email protected]"
] | |
3369f044ace4960e8c36c4fb81ce547b174cd11a | cc278421ec379fd4b7c9393f4c1edd31a627b984 | /src/ExifToolPipe.cpp | ef34e53120940541f302ea4be877140faa800ab6 | [] | no_license | UAV-Concordia/MetaWriter | 5871b3b34acfe9c8889ee64624c7ebdd7843896d | d0866c4900af19bf29514b92629cc6045da94ff5 | refs/heads/master | 2021-01-21T04:33:12.154321 | 2015-03-14T06:05:14 | 2015-03-14T06:05:14 | 32,197,807 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,005 | cpp | //------------------------------------------------------------------------------
// File: ExifToolPipe.cpp
//
// Description: Piped output from exiftool application
//
// License: Copyright 2013, Phil Harvey (phil at owl.phy.queensu.ca)
//
// This is software, in whole or part, is free for use in
// non-commercial applications, provided that this copyright notice
// is retained. A licensing fee may be required for use in a
// commercial application.
//
// History: 2013-11-23 - Phil Harvey Created
//------------------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
#include "ExifToolPipe.h"
//------------------------------------------------------------------------------
// ExifToolPipe constructor
ExifToolPipe::ExifToolPipe()
: mFile(-1), mBuff(NULL), mSize(0), mLen(0), mPos(0), mSearchPos(0),
mBlockSize(0), mString(NULL), mPid(-1)
{
}
//------------------------------------------------------------------------------
// Destructor -- close the input file and delete the buffer
ExifToolPipe::~ExifToolPipe()
{
if (mFile >= 0) close(mFile);
Free();
}
//------------------------------------------------------------------------------
// Initialize the ExifTool pipe object
// - sets input file to non-blocking
void ExifToolPipe::Init(int fd, int pid, int initialSize)
{
mFile = fd;
mPid = pid;
mBlockSize = initialSize;
// set read pipe to non-blocking
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
//------------------------------------------------------------------------------
// Read exiftool response for specified command number
// returns: command number on success, 0 if no response available, <0 on error
// - this routine returns immediately
int ExifToolPipe::Read()
{
const int kMinRemaining = 1024; // enlarge buffer if less than this free
Flush(); // remove previous response from buffer
// keep reading until we get a complete response or there is no more to read
for (;;) {
// read to fill remaining response buffer, but leave room for null terminator
int remaining = mSize - mLen - 1;
// enlarge buffer if necessary
// (could test for "remaining < 1", but what is the point in reading just 1 byte?)
if (remaining < kMinRemaining) {
int newSize = mSize + mLen + mBlockSize;
char *pt = new char[newSize];
if (!pt) return -1; // out of memory!
if (mSize) memcpy(pt, mBuff, mSize);
delete [] mBuff;
mBuff = pt;
mSize = newSize;
remaining = newSize - mLen - 1;
}
// read output from exiftool process
int bytesRead = read(mFile, mBuff + mLen, remaining);
if (bytesRead < 0) {
if (errno != EAGAIN) return -2; // read error!
bytesRead = 0;
}
mLen += bytesRead;
if (mLen < 13) {
if (!bytesRead) {
// no response, so check to be sure our exiftool process is still running
int status;
if (mPid == -1) return -3;
if (waitpid(mPid, &status, WNOHANG)) {
mPid = -1;
return -3;
}
}
return 0;
}
// must null terminate response string for searching
mBuff[mLen] = '\0';
// 0123456789012
// response should end with "{ready12345}\n" or "{ready12345}\r\n"
// - continue searching from where we left off
char *pt = mBuff + mSearchPos;
char *end = mBuff + mLen;
for (;;) {
pt = strstr(pt, "{ready");
if (!pt) {
mSearchPos = mLen - 5; // continue next search where we left off
break;
}
if ((pt==mBuff || pt[-1]=='\n') && end-pt>=13 && pt[11]=='}' &&
// must end with newline, or CR+LF in Windows
(pt[12]=='\n' || (pt[12]=='\r' && end-pt>=14 && pt[13]=='\n')))
{
// validate and extract command number
int cmdNum = 0;
for (int i=0; i<5; ++i) {
unsigned d = pt[i+6] -'0';
if (d > 9) {
cmdNum = 0;
break;
}
cmdNum = cmdNum * 10 + d;
}
if (cmdNum) {
*pt = '\0'; // NULL terminate original response
// skip LF if this was a Windows CR+LF combo
if (pt[12] == '\r') ++pt;
pt += 13; // step to start of next response
// update current position in response buffer
mPos = pt - mBuff;
mString = mBuff; // set return string
return cmdNum; // success!
}
}
pt += 6; // step to next possible search position
}
if (bytesRead != remaining) break; // stop if we read everything
}
return 0; // no complete response available
}
//------------------------------------------------------------------------------
// Free buffer memory
void ExifToolPipe::Free()
{
delete [] mBuff;
mBuff = mString = NULL;
mLen = mSize = mPos = mSearchPos = 0;
}
//------------------------------------------------------------------------------
// Remove previous response from buffer
void ExifToolPipe::Flush()
{
if (mPos) {
if (mLen > mPos) {
memmove(mBuff, mBuff+mPos, mLen-mPos);
mLen -= mPos;
} else {
mLen = 0;
}
mPos = mSearchPos = 0;
}
mString = NULL;
}
// end
| [
"[email protected]"
] | |
e94745819ecd535c04fe4a99defe76ecc350730f | c65fbfcfce3ed9bf9efabb0b8136ceaa432f6d09 | /include/imgproc/xf_remap.hpp | 459e7e124a44c79cbf4dd023cebacf218bfc9dcd | [
"BSD-3-Clause"
] | permissive | Andromem/xfopencv | 1a4daf202b447e8fb8bba1360420fe7d9b553ff0 | c396bc6d2d6b71a9d3e83b530afad46df4486fb3 | refs/heads/master | 2020-03-19T03:03:26.317246 | 2018-05-21T07:12:34 | 2018-05-21T07:12:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,279 | hpp | /***************************************************************************
Copyright (c) 2016, Xilinx, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#ifndef _XF_REMAP_HPP_
#define _XF_REMAP_HPP_
#ifndef __cplusplus
#error C++ is needed to include this header.
#endif
#include "hls_stream.h"
#include "common/xf_common.h"
#include "common/xf_utility.h"
#define HLS_INTER_TAB_SIZE 32
#define HLS_INTER_BITS 5
namespace xf{
template <int WIN_ROW, int ROWS, int COLS, typename SRC_T, typename DST_T, typename MAP_T>
void xFRemapNNI(
hls::stream< SRC_T > &src,
hls::stream< DST_T > &dst,
hls::stream< MAP_T > &mapx,
hls::stream< MAP_T > &mapy,
uint16_t rows, uint16_t cols
)
{
DST_T buf[WIN_ROW][COLS];
#pragma HLS ARRAY_PARTITION variable=buf complete dim=1
SRC_T s;
DST_T d;
MAP_T mx_fl;
MAP_T my_fl;
assert(rows <= ROWS);
assert(cols <= COLS);
int ishift=WIN_ROW/2;
int r[WIN_ROW] = {};
int row_tripcount = ROWS+WIN_ROW;
loop_height: for( int i=0; i< rows+ishift; i++)
{
#pragma HLS LOOP_FLATTEN OFF
#pragma HLS LOOP_TRIPCOUNT min=1 max=row_tripcount
loop_width: for( int j=0; j< cols; j++)
{
#pragma HLS PIPELINE II=1
#pragma HLS dependence array inter false
#pragma HLS LOOP_TRIPCOUNT min=1 max=COLS
if(i<rows&& j<cols)
{
src >> s;
}
buf[i % WIN_ROW][j] = s;
r[i % WIN_ROW] = i;
if(i>=ishift)
{
mapx >> mx_fl;
mapy >> my_fl;
int x = (int)mx_fl;
int y = (int)my_fl;
bool in_range = (y>=0 && y<rows && r[y%WIN_ROW] == y && x>=0 && x<cols);
if(in_range)
d = buf[y%WIN_ROW][x];
else
d = 0;
dst << d;
}
}
}
}
#define TWO_POW_16 65536
template <int WIN_ROW, int ROWS, int COLS, typename SRC_T, typename DST_T, typename MAP_T>
void xFRemapLI(
hls::stream< SRC_T > &src,
hls::stream< DST_T > &dst,
hls::stream< MAP_T > &mapx,
hls::stream< MAP_T > &mapy,
uint16_t rows, uint16_t cols
)
{
// Add one to always get zero for boundary interpolation. Maybe need initialization here?
DST_T buf[WIN_ROW/2+1][2][COLS/2+1][2];
#pragma HLS array_partition complete variable=buf dim=2
#pragma HLS array_partition complete variable=buf dim=4
SRC_T s;
MAP_T mx;
MAP_T my;
assert(rows <= ROWS);
assert(cols <= COLS);
int ishift=WIN_ROW/2;
int r1[WIN_ROW] = {};
int r2[WIN_ROW] = {};
int row_tripcount = ROWS+WIN_ROW;
loop_height: for( int i=0; i< rows+ishift; i++)
{
#pragma HLS LOOP_FLATTEN OFF
#pragma HLS LOOP_TRIPCOUNT min=1 max=row_tripcount
loop_width: for( int j=0; j< cols; j++)
{
#pragma HLS PIPELINE II=1
#pragma HLS dependence array inter false
#pragma HLS LOOP_TRIPCOUNT min=1 max=COLS
if(i<rows&& j<cols)
{
src >> s;
}
if((i % WIN_ROW) % 2) {
buf[(i % WIN_ROW)/2][(i % WIN_ROW) % 2][j/2][j%2] = s;
} else {
buf[(i % WIN_ROW)/2][(i % WIN_ROW) % 2][j/2][j%2] = s;
}
r1[i % WIN_ROW] = i;
r2[i % WIN_ROW] = i;
if(i>=ishift)
{
mapx >> mx;
mapy >> my;
float x_fl = mx;
float y_fl = my;
int x_fix = (int) ((float)x_fl * (float)HLS_INTER_TAB_SIZE); // mapx data in A16.HLS_INTER_TAB_SIZE format
int y_fix = (int) ((float)y_fl * (float)HLS_INTER_TAB_SIZE); // mapy data in A16.HLS_INTER_TAB_SIZE format
int x = x_fix >> HLS_INTER_BITS;
int y = y_fix >> HLS_INTER_BITS;
int x_frac = x_fix & (HLS_INTER_TAB_SIZE-1);
int y_frac = y_fix & (HLS_INTER_TAB_SIZE-1);
int ynext = y+1;
ap_ufixed<HLS_INTER_BITS, 0> iu, iv;
iu(HLS_INTER_BITS-1, 0) = x_frac;
iv(HLS_INTER_BITS-1, 0) = y_frac;
// Note that the range here is larger than expected by 1 horizontal and 1 vertical pixel, to allow
// Interpolating at the edge of the image
bool in_range = (y>=0 && y<rows && r1[y%WIN_ROW] == y && r2[ynext%WIN_ROW] == ynext && x>=0 && x<cols);
int xa0, xa1, ya0, ya1;
// The buffer is essentially cyclic partitioned, but we have
// to do this manually because HLS can't figure it out.
// The code below is wierd, but it is this code expanded.
// if ((y % WIN_ROW) % 2) {
// // Case 1, where y hits in bank 1 and ynext in bank 0
// ya0 = (ynext%WIN_ROW)/2;
// ya1 = (y%WIN_ROW)/2;
// } else {
// // The simpler case, where y hits in bank 0 and ynext hits in bank 1
// ya0 = (y%WIN_ROW)/2;
// ya1 = (ynext%WIN_ROW)/2;
// }
// Both cases reduce to this, if WIN_ROW is a multiple of two.
assert(((WIN_ROW & 1) == 0) && "WIN_ROW must be a multiple of two");
xa0 = x/2 + x%2;
xa1 = x/2;
ya0 = (y/2 + y%2)%(WIN_ROW/2);
ya1 = (y/2)%(WIN_ROW/2);
DST_T d00, d01, d10, d11;
d00=buf[ya0][0][xa0][0];
d01=buf[ya0][0][xa1][1];
d10=buf[ya1][1][xa0][0];
d11=buf[ya1][1][xa1][1];
if(x%2) {
std::swap(d00,d01);
std::swap(d10,d11);
}
if(y%2) {
std::swap(d00,d10);
std::swap(d01,d11);
}
ap_ufixed<2*HLS_INTER_BITS + 1, 1> k01 = (1-iv)*( iu); // iu-iu*iv
ap_ufixed<2*HLS_INTER_BITS + 1, 1> k10 = ( iv)*(1-iu); // iv-iu*iv
ap_ufixed<2*HLS_INTER_BITS + 1, 1> k11 = ( iv)*( iu); // iu*iv
ap_ufixed<2*HLS_INTER_BITS + 1, 1> k00 = 1-iv-k01; //(1-iv)*(1-iu) = 1-iu-iv+iu*iv = 1-iv-k01
assert( k00 + k01 + k10 + k11 == 1);
DST_T d;
if(in_range)
d = d00 * k00 + d01 * k01 + d10 * k10 + d11 * k11;
else
d = 0;
dst<< d;
}
}
}
}
template <int WIN_ROW, int INTERPOLATION_TYPE, int ROWS, int COLS, typename SRC_T, typename DST_T, typename MAP_T>
void xFRemapKernel(
hls::stream< SRC_T > &src,
hls::stream< DST_T > &dst,
hls::stream< MAP_T > &mapx,
hls::stream< MAP_T > &mapy,
uint16_t rows, uint16_t cols
)
{
if(INTERPOLATION_TYPE == XF_INTERPOLATION_NN) {
xFRemapNNI<WIN_ROW,ROWS,COLS>(src, dst, mapx, mapy,rows,cols);
} else if(INTERPOLATION_TYPE == XF_INTERPOLATION_BILINEAR) {
xFRemapLI<WIN_ROW,ROWS,COLS>(src, dst, mapx, mapy,rows,cols);
}
else {
assert (((INTERPOLATION_TYPE == XF_INTERPOLATION_NN)||(INTERPOLATION_TYPE == XF_INTERPOLATION_BILINEAR)) && "The INTERPOLATION_TYPE must be either XF_INTERPOLATION_NN or XF_INTERPOLATION_BILINEAR");
}
}
//#pragma SDS data data_mover("_src_mat.data":AXIDMA_SIMPLE,"_remapped_mat.data":AXIDMA_SIMPLE,"_mapx_mat.data":AXIDMA_SIMPLE,"_mapy_mat.data":AXIDMA_SIMPLE)
//#pragma SDS data mem_attribute("_src_mat.data":NON_CACHEABLE|PHYSICAL_CONTIGUOUS,"_remapped_mat.data":NON_CACHEABLE|PHYSICAL_CONTIGUOUS,"_mapx_mat.data":NON_CACHEABLE|PHYSICAL_CONTIGUOUS,"_mapy_mat.data":NON_CACHEABLE|PHYSICAL_CONTIGUOUS)
#pragma SDS data access_pattern("_src_mat.data":SEQUENTIAL,"_remapped_mat.data":SEQUENTIAL,"_mapx_mat.data":SEQUENTIAL,"_mapy_mat.data":SEQUENTIAL)
#pragma SDS data copy("_src_mat.data"[0:"_src_mat.rows*_src_mat.cols"], "_remapped_mat.data"[0:"_remapped_mat.size"],"_mapx_mat.data"[0:"_mapx_mat.size"],"_mapy_mat.data"[0:"_mapy_mat.size"])
template<int WIN_ROWS, int INTERPOLATION_TYPE, int SRC_T, int MAP_T, int DST_T, int ROWS, int COLS, int NPC = XF_NPPC1>
void remap (xf::Mat<SRC_T, ROWS, COLS, NPC> &_src_mat, xf::Mat<DST_T, ROWS, COLS, NPC> &_remapped_mat, xf::Mat<MAP_T, ROWS, COLS, NPC> &_mapx_mat,
xf::Mat<MAP_T, ROWS, COLS, NPC> &_mapy_mat)
{
#pragma HLS inline off
#pragma HLS dataflow
assert ((MAP_T == XF_32FC1) && "The MAP_T must be XF_32FC1");
// assert ((SRC_T == XF_8UC1) && "The SRC_T must be XF_8UC1");
// assert ((DST_T == XF_8UC1) && "The DST_T must be XF_8UC1");
assert ((NPC == XF_NPPC1) && "The NPC must be XF_NPPC1");
hls::stream< XF_TNAME(SRC_T,NPC)> _src;
hls::stream< XF_TNAME(MAP_T,NPC)> _mapx;
hls::stream< XF_TNAME(MAP_T,NPC)> _mapy;
hls::stream< XF_TNAME(DST_T,NPC)> _remapped;
int depth_est = WIN_ROWS*_src_mat.cols;
uint16_t rows = _src_mat.rows;
uint16_t cols = _src_mat.cols;
int loop_count = (rows*cols);
int TC=(ROWS*COLS);
int ishift = WIN_ROWS/2;
int row_tripcount = ROWS+WIN_ROWS;
xfremap_rows_loop:
for (int i = 0; i < rows+ishift; i++)
{
#pragma HLS LOOP_FLATTEN OFF
#pragma HLS LOOP_TRIPCOUNT min=1 max=row_tripcount
xfremap_cols_loop:
for (int j = 0; j < cols; j++)
{
#pragma HLS pipeline ii=1
#pragma HLS LOOP_TRIPCOUNT min=1 max=COLS
if (i < rows) {
_src.write(*(_src_mat.data + i*cols + j));
}
if (i >= ishift) {
_mapx.write(*(_mapx_mat.data + (i-ishift)*cols + j));
_mapy.write(*(_mapy_mat.data + (i-ishift)*cols + j));
}
}
}
xFRemapKernel <WIN_ROWS,INTERPOLATION_TYPE,ROWS,COLS> (_src, _remapped, _mapx, _mapy, rows, cols);
xfremap_output_loop:
for (int i = 0; i < loop_count; i++)
{
#pragma HLS pipeline ii=1
#pragma HLS LOOP_TRIPCOUNT min=1 max=TC
_remapped_mat.data[i] = _remapped.read();
}
}
}
#endif//_XF_REMAP_HPP_
| [
"[email protected]"
] | |
3f794c4f201b2d9101bedb98b984e44359f9ff32 | 431048c473d1dccb8e4c810c7844229b49f4e830 | /translator.h | 341ad3323b816205a5a054434d2bfeee2d991f56 | [] | no_license | n1c0sh/TechnicHubController | 8fc030ca10cec75640e93e20c519b37dfca7f608 | 66baf8350ad9e9c3a9258639435f5911c04e09ab | refs/heads/master | 2022-03-04T16:43:07.486685 | 2019-11-06T07:46:42 | 2019-11-06T07:46:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | h | #ifndef TRANSLATOR_H
#define TRANSLATOR_H
#include <QObject>
#include <QTranslator>
#include <QQmlApplicationEngine>
#include <QGuiApplication>
class Translator: public QObject{
Q_OBJECT
public:
Translator() {}
~Translator(){engine = nullptr;}
private:
QTranslator translator;
QQmlApplicationEngine *engine;
public slots:
void setEngine(QQmlApplicationEngine *_engine){
engine = _engine;
}
void selectLanguage(QString language) {
if(language == "ru_RU"){
if (!translator.isEmpty()) qApp->removeTranslator(&translator);
translator.load(":/lang/lang_ru_RU");
qApp->installTranslator(&translator);
}
if(language == "en_US"){
if (!translator.isEmpty())qApp->removeTranslator(&translator);
}
engine->retranslate();
}
};
#endif // TRANSLATOR_H
| [
"[email protected]"
] | |
b0a01ce4387ebd0b98d74b8559a15834c71e7b0b | c49870c4a74b36d77633258ef209dcb96a012480 | /src/widgets/text.hpp | 4ff40bcc7bc3ac20a768dda3b8280451c027420c | [
"BSD-3-Clause"
] | permissive | jdstmporter/VCV-Plugins | dc0b15db8d7f275e460779634f30ae06d4d69506 | cea4eb8073a44f7359791d5a19550131d3231229 | refs/heads/master | 2022-11-28T04:09:23.844054 | 2020-08-14T22:51:19 | 2020-08-14T22:51:19 | 277,945,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,347 | hpp | /*
* text.hpp
*
* Created on: 12 Aug 2020
* Author: julianporter
*/
#ifndef SRC_WIDGETS_TEXT_HPP_
#define SRC_WIDGETS_TEXT_HPP_
#include <rack.hpp>
#include <nanovg.h>
#include <color.hpp>
#include <blendish.h>
namespace rack { namespace componentlibrary {
struct TextDisplayField : public LedDisplayTextField {
NVGcolor background;
NVGcolor highlight;
float fontSize = NAN;
bool centre = false;
TextDisplayField() : LedDisplayTextField() {
background = nvgRGBAf(0,0,0,0);
color = nvgRGBAf(0,0,0,1);
highlight = nvgRGBAf(0,0,0,0.5);
};
virtual ~TextDisplayField() = default;
void setFG(const NVGcolor &c) {
color=c;
highlight=nvgTransRGBAf(c,0.5f);
}
void setFG(const float r,const float g,const float b,const float a=1.f) { setFG(nvgRGBAf(r,g,b,a)); }
void setBG(const NVGcolor &c) { background=c; }
void setBG(const float r,const float g,const float b,const float a=1.f) { setBG(nvgRGBAf(r,g,b,a)); }
void loadFont(const std::string &f) { font=APP->window->loadFont(f); }
void setFontSize(const float s) { fontSize=s; }
virtual void draw(const Widget::DrawArgs &args) override {
NVGcontext *ctx=args.vg;
nvgScissor(ctx, RECT_ARGS(args.clipBox));
// Background
nvgBeginPath(ctx);
nvgRoundedRect(ctx, 0, 0, box.size.x, box.size.y, 5.0);
nvgFillColor(ctx, background);
nvgFill(ctx);
// Text
nvgScale(ctx,0.75,0.75);
if (font->handle >= 0) {
bndSetFont(font->handle);
if(std::isfinite(fontSize)) nvgFontSize(ctx,fontSize);
int begin = std::min(cursor, selection);
int end = (this == APP->event->selectedWidget) ? std::max(cursor, selection) : -1;
auto boxWidth = box.size.x - 2 * textOffset.x;
float bounds[4] = {0,0,0,0};
nvgTextBounds(ctx,textOffset.x, textOffset.y,text.c_str(),NULL,bounds);
auto textWidth=bounds[2]-bounds[0];
auto offset=(centre) ? 0.5f*(boxWidth-textWidth) : 0.0;
//INFO("%f,%f,%f,%f %f",bounds[0],bounds[1],bounds[2],bounds[3],offset);
bndIconLabelCaret(ctx, textOffset.x + offset, textOffset.y,
boxWidth, box.size.y - 2 * textOffset.y,
-1, (NVGcolor)color, 12, text.c_str(), highlight, begin, end);
bndSetFont(APP->window->uiFont->handle);
}
nvgResetTransform(ctx);
nvgResetScissor(ctx);
}
};
}}
#endif /* SRC_WIDGETS_TEXT_HPP_ */
| [
"[email protected]"
] | |
7fa75cb9fe930ef6fed4731eaf239cf294b38245 | adc91d74d99f03bf1c054fd4d7598db48d8275d8 | /Arduino/OSC_Bundle_senden/OSC_Bundle_senden.ino | 75981a7f46b3bbfc41b8c3bfb9235c9d9e2f470a | [] | no_license | HerrPaule/OSCuino | a373594ccb6f4d1f870953f5612fb71eb588c141 | 59008b0f80dc05e6c4f4afbd1b7ab427dcbd6a1e | refs/heads/master | 2020-04-29T12:04:05.917563 | 2014-03-05T12:19:13 | 2014-03-05T12:19:13 | 17,400,349 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,266 | ino | #include <OSCBundle.h>
/*
OSC Bundle Nachrichten
basierend auf CNMAT Beispielsketch der OSCuino Bibliothek
*/
//Teensy und Leonardo nutzen einen anderen speziellen USB serial.
#if defined(CORE_TEENSY)|| defined(__AVR_ATmega32U4__)
#include <SLIPEncodedUSBSerial.h>
SLIPEncodedUSBSerial SLIPSerial(Serial);
#else
// Wenn kein Teensy oder Leonardo angeschlossen ist
#include <SLIPEncodedSerial.h>
SLIPEncodedSerial SLIPSerial(Serial);
#endif
int poti = A0;
int potiRoh = 0;
int potiMidi = 0;
void setup() {
//SLIPserial wird wie der normale Serial befehl initiert.
Serial.begin(9600);
while(!Serial); // speziell für Leonardo
}
void loop(){
potiRoh = analogRead(poti);
//Analog Rohwerte zu MIDI konformen Werte (0-127) skalieren
potiMidi = map(potiRoh, 0, 1024, 0, 127);
// bei mehreren OSC Nachrichten gleichzeitig muss man diese als OSC Bundle senden
OSCBundle bndl;
bndl.add("/analog/0").add(potiRoh);
bndl.add("/analog/midi/0").add(potiMidi);
SLIPSerial.beginPacket();
bndl.send(SLIPSerial); // sendet das vorherige OSC Bundle über den SLIP Stream
SLIPSerial.endPacket(); // danach wird das Ende der Nachricht ausgegeben.
bndl.empty(); // und der Speicher wird nach der Übertragung der Daten geleert
delay(20);
}
| [
"[email protected]"
] | |
0ccb1219942be50273d65e0e15eed85906d0d499 | b7021a6a00c8204a9b904b9dc719762a23185eda | /aprinter/meta/TypeMap.h | cb35afa0d736fe14cd6d96257088bc132cba2709 | [] | no_license | imsplitbit/aprinter | 178f859a8169f49f2179d9d85618c49bb08f4326 | 2d7549394198794081611d1f7c316764eee5bb1d | refs/heads/master | 2021-01-22T14:29:02.089006 | 2015-01-11T01:03:06 | 2015-01-11T01:03:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,226 | h | /*
* Copyright (c) 2013 Ambroz Bizjak
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef AMBROLIB_TYPE_MAP_H
#define AMBROLIB_TYPE_MAP_H
#include <aprinter/meta/MakeTypeList.h>
#include <aprinter/meta/TypeListFind.h>
#include <aprinter/meta/GetMemberTypeFunc.h>
#include <aprinter/meta/IsEqualFunc.h>
#include <aprinter/meta/ComposeFunctions.h>
#include <aprinter/BeginNamespace.h>
template <typename TKey, typename TVal>
struct TypeMapEntry {
using Key = TKey;
using Val = TVal;
};
template <typename TEntriesList>
struct TypeMap {
using EntriesList = TEntriesList;
};
template <typename... Entries>
using MakeTypeMap = TypeMap<MakeTypeList<Entries...>>;
AMBRO_DECLARE_GET_MEMBER_TYPE_FUNC(TypeMap__GetMemberType_Key, Key)
template <typename Map, typename Key>
using TypeMapGet = typename TypeListFind<typename Map::EntriesList, ComposeFunctions<IsEqualFunc<Key>, TypeMap__GetMemberType_Key>>::Val;
#include <aprinter/EndNamespace.h>
#endif
| [
"[email protected]"
] | |
d405b7c53028cdaa23aeff586c2acabecb0e8ec6 | 792e697ba0f9c11ef10b7de81edb1161a5580cfb | /lib/Transforms/Scalar/LoopDistribute.cpp | 0f4c767c1e4cf3d6505295199d7524051a376e0b | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | opencor/llvmclang | 9eb76cb6529b6a3aab2e6cd266ef9751b644f753 | 63b45a7928f2a8ff823db51648102ea4822b74a6 | refs/heads/master | 2023-08-26T04:52:56.472505 | 2022-11-02T04:35:46 | 2022-11-03T03:55:06 | 115,094,625 | 0 | 1 | Apache-2.0 | 2021-08-12T22:29:21 | 2017-12-22T08:29:14 | LLVM | UTF-8 | C++ | false | false | 41,226 | cpp | //===- LoopDistribute.cpp - Loop Distribution Pass ------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the Loop Distribution Pass. Its main focus is to
// distribute loops that cannot be vectorized due to dependence cycles. It
// tries to isolate the offending dependences into a new loop allowing
// vectorization of the remaining parts.
//
// For dependence analysis, the pass uses the LoopVectorizer's
// LoopAccessAnalysis. Because this analysis presumes no change in the order of
// memory operations, special care is taken to preserve the lexical order of
// these operations.
//
// Similarly to the Vectorizer, the pass also supports loop versioning to
// run-time disambiguate potentially overlapping arrays.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar/LoopDistribute.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/EquivalenceClasses.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/LoopAccessAnalysis.h"
#include "llvm/Analysis/LoopAnalysisManager.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#include "llvm/Transforms/Utils/LoopVersioning.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <cassert>
#include <functional>
#include <list>
#include <tuple>
#include <utility>
using namespace llvm;
#define LDIST_NAME "loop-distribute"
#define DEBUG_TYPE LDIST_NAME
/// @{
/// Metadata attribute names
static const char *const LLVMLoopDistributeFollowupAll =
"llvm.loop.distribute.followup_all";
static const char *const LLVMLoopDistributeFollowupCoincident =
"llvm.loop.distribute.followup_coincident";
static const char *const LLVMLoopDistributeFollowupSequential =
"llvm.loop.distribute.followup_sequential";
static const char *const LLVMLoopDistributeFollowupFallback =
"llvm.loop.distribute.followup_fallback";
/// @}
static cl::opt<bool>
LDistVerify("loop-distribute-verify", cl::Hidden,
cl::desc("Turn on DominatorTree and LoopInfo verification "
"after Loop Distribution"),
cl::init(false));
static cl::opt<bool> DistributeNonIfConvertible(
"loop-distribute-non-if-convertible", cl::Hidden,
cl::desc("Whether to distribute into a loop that may not be "
"if-convertible by the loop vectorizer"),
cl::init(false));
static cl::opt<unsigned> DistributeSCEVCheckThreshold(
"loop-distribute-scev-check-threshold", cl::init(8), cl::Hidden,
cl::desc("The maximum number of SCEV checks allowed for Loop "
"Distribution"));
static cl::opt<unsigned> PragmaDistributeSCEVCheckThreshold(
"loop-distribute-scev-check-threshold-with-pragma", cl::init(128),
cl::Hidden,
cl::desc(
"The maximum number of SCEV checks allowed for Loop "
"Distribution for loop marked with #pragma loop distribute(enable)"));
static cl::opt<bool> EnableLoopDistribute(
"enable-loop-distribute", cl::Hidden,
cl::desc("Enable the new, experimental LoopDistribution Pass"),
cl::init(false));
STATISTIC(NumLoopsDistributed, "Number of loops distributed");
namespace {
/// Maintains the set of instructions of the loop for a partition before
/// cloning. After cloning, it hosts the new loop.
class InstPartition {
using InstructionSet = SmallPtrSet<Instruction *, 8>;
public:
InstPartition(Instruction *I, Loop *L, bool DepCycle = false)
: DepCycle(DepCycle), OrigLoop(L) {
Set.insert(I);
}
/// Returns whether this partition contains a dependence cycle.
bool hasDepCycle() const { return DepCycle; }
/// Adds an instruction to this partition.
void add(Instruction *I) { Set.insert(I); }
/// Collection accessors.
InstructionSet::iterator begin() { return Set.begin(); }
InstructionSet::iterator end() { return Set.end(); }
InstructionSet::const_iterator begin() const { return Set.begin(); }
InstructionSet::const_iterator end() const { return Set.end(); }
bool empty() const { return Set.empty(); }
/// Moves this partition into \p Other. This partition becomes empty
/// after this.
void moveTo(InstPartition &Other) {
Other.Set.insert(Set.begin(), Set.end());
Set.clear();
Other.DepCycle |= DepCycle;
}
/// Populates the partition with a transitive closure of all the
/// instructions that the seeded instructions dependent on.
void populateUsedSet() {
// FIXME: We currently don't use control-dependence but simply include all
// blocks (possibly empty at the end) and let simplifycfg mostly clean this
// up.
for (auto *B : OrigLoop->getBlocks())
Set.insert(B->getTerminator());
// Follow the use-def chains to form a transitive closure of all the
// instructions that the originally seeded instructions depend on.
SmallVector<Instruction *, 8> Worklist(Set.begin(), Set.end());
while (!Worklist.empty()) {
Instruction *I = Worklist.pop_back_val();
// Insert instructions from the loop that we depend on.
for (Value *V : I->operand_values()) {
auto *I = dyn_cast<Instruction>(V);
if (I && OrigLoop->contains(I->getParent()) && Set.insert(I).second)
Worklist.push_back(I);
}
}
}
/// Clones the original loop.
///
/// Updates LoopInfo and DominatorTree using the information that block \p
/// LoopDomBB dominates the loop.
Loop *cloneLoopWithPreheader(BasicBlock *InsertBefore, BasicBlock *LoopDomBB,
unsigned Index, LoopInfo *LI,
DominatorTree *DT) {
ClonedLoop = ::cloneLoopWithPreheader(InsertBefore, LoopDomBB, OrigLoop,
VMap, Twine(".ldist") + Twine(Index),
LI, DT, ClonedLoopBlocks);
return ClonedLoop;
}
/// The cloned loop. If this partition is mapped to the original loop,
/// this is null.
const Loop *getClonedLoop() const { return ClonedLoop; }
/// Returns the loop where this partition ends up after distribution.
/// If this partition is mapped to the original loop then use the block from
/// the loop.
Loop *getDistributedLoop() const {
return ClonedLoop ? ClonedLoop : OrigLoop;
}
/// The VMap that is populated by cloning and then used in
/// remapinstruction to remap the cloned instructions.
ValueToValueMapTy &getVMap() { return VMap; }
/// Remaps the cloned instructions using VMap.
void remapInstructions() {
remapInstructionsInBlocks(ClonedLoopBlocks, VMap);
}
/// Based on the set of instructions selected for this partition,
/// removes the unnecessary ones.
void removeUnusedInsts() {
SmallVector<Instruction *, 8> Unused;
for (auto *Block : OrigLoop->getBlocks())
for (auto &Inst : *Block)
if (!Set.count(&Inst)) {
Instruction *NewInst = &Inst;
if (!VMap.empty())
NewInst = cast<Instruction>(VMap[NewInst]);
assert(!isa<BranchInst>(NewInst) &&
"Branches are marked used early on");
Unused.push_back(NewInst);
}
// Delete the instructions backwards, as it has a reduced likelihood of
// having to update as many def-use and use-def chains.
for (auto *Inst : reverse(Unused)) {
if (!Inst->use_empty())
Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
Inst->eraseFromParent();
}
}
void print() const {
if (DepCycle)
dbgs() << " (cycle)\n";
for (auto *I : Set)
// Prefix with the block name.
dbgs() << " " << I->getParent()->getName() << ":" << *I << "\n";
}
void printBlocks() const {
for (auto *BB : getDistributedLoop()->getBlocks())
dbgs() << *BB;
}
private:
/// Instructions from OrigLoop selected for this partition.
InstructionSet Set;
/// Whether this partition contains a dependence cycle.
bool DepCycle;
/// The original loop.
Loop *OrigLoop;
/// The cloned loop. If this partition is mapped to the original loop,
/// this is null.
Loop *ClonedLoop = nullptr;
/// The blocks of ClonedLoop including the preheader. If this
/// partition is mapped to the original loop, this is empty.
SmallVector<BasicBlock *, 8> ClonedLoopBlocks;
/// These gets populated once the set of instructions have been
/// finalized. If this partition is mapped to the original loop, these are not
/// set.
ValueToValueMapTy VMap;
};
/// Holds the set of Partitions. It populates them, merges them and then
/// clones the loops.
class InstPartitionContainer {
using InstToPartitionIdT = DenseMap<Instruction *, int>;
public:
InstPartitionContainer(Loop *L, LoopInfo *LI, DominatorTree *DT)
: L(L), LI(LI), DT(DT) {}
/// Returns the number of partitions.
unsigned getSize() const { return PartitionContainer.size(); }
/// Adds \p Inst into the current partition if that is marked to
/// contain cycles. Otherwise start a new partition for it.
void addToCyclicPartition(Instruction *Inst) {
// If the current partition is non-cyclic. Start a new one.
if (PartitionContainer.empty() || !PartitionContainer.back().hasDepCycle())
PartitionContainer.emplace_back(Inst, L, /*DepCycle=*/true);
else
PartitionContainer.back().add(Inst);
}
/// Adds \p Inst into a partition that is not marked to contain
/// dependence cycles.
///
// Initially we isolate memory instructions into as many partitions as
// possible, then later we may merge them back together.
void addToNewNonCyclicPartition(Instruction *Inst) {
PartitionContainer.emplace_back(Inst, L);
}
/// Merges adjacent non-cyclic partitions.
///
/// The idea is that we currently only want to isolate the non-vectorizable
/// partition. We could later allow more distribution among these partition
/// too.
void mergeAdjacentNonCyclic() {
mergeAdjacentPartitionsIf(
[](const InstPartition *P) { return !P->hasDepCycle(); });
}
/// If a partition contains only conditional stores, we won't vectorize
/// it. Try to merge it with a previous cyclic partition.
void mergeNonIfConvertible() {
mergeAdjacentPartitionsIf([&](const InstPartition *Partition) {
if (Partition->hasDepCycle())
return true;
// Now, check if all stores are conditional in this partition.
bool seenStore = false;
for (auto *Inst : *Partition)
if (isa<StoreInst>(Inst)) {
seenStore = true;
if (!LoopAccessInfo::blockNeedsPredication(Inst->getParent(), L, DT))
return false;
}
return seenStore;
});
}
/// Merges the partitions according to various heuristics.
void mergeBeforePopulating() {
mergeAdjacentNonCyclic();
if (!DistributeNonIfConvertible)
mergeNonIfConvertible();
}
/// Merges partitions in order to ensure that no loads are duplicated.
///
/// We can't duplicate loads because that could potentially reorder them.
/// LoopAccessAnalysis provides dependency information with the context that
/// the order of memory operation is preserved.
///
/// Return if any partitions were merged.
bool mergeToAvoidDuplicatedLoads() {
using LoadToPartitionT = DenseMap<Instruction *, InstPartition *>;
using ToBeMergedT = EquivalenceClasses<InstPartition *>;
LoadToPartitionT LoadToPartition;
ToBeMergedT ToBeMerged;
// Step through the partitions and create equivalence between partitions
// that contain the same load. Also put partitions in between them in the
// same equivalence class to avoid reordering of memory operations.
for (PartitionContainerT::iterator I = PartitionContainer.begin(),
E = PartitionContainer.end();
I != E; ++I) {
auto *PartI = &*I;
// If a load occurs in two partitions PartI and PartJ, merge all
// partitions (PartI, PartJ] into PartI.
for (Instruction *Inst : *PartI)
if (isa<LoadInst>(Inst)) {
bool NewElt;
LoadToPartitionT::iterator LoadToPart;
std::tie(LoadToPart, NewElt) =
LoadToPartition.insert(std::make_pair(Inst, PartI));
if (!NewElt) {
LLVM_DEBUG(dbgs()
<< "Merging partitions due to this load in multiple "
<< "partitions: " << PartI << ", " << LoadToPart->second
<< "\n"
<< *Inst << "\n");
auto PartJ = I;
do {
--PartJ;
ToBeMerged.unionSets(PartI, &*PartJ);
} while (&*PartJ != LoadToPart->second);
}
}
}
if (ToBeMerged.empty())
return false;
// Merge the member of an equivalence class into its class leader. This
// makes the members empty.
for (ToBeMergedT::iterator I = ToBeMerged.begin(), E = ToBeMerged.end();
I != E; ++I) {
if (!I->isLeader())
continue;
auto PartI = I->getData();
for (auto PartJ : make_range(std::next(ToBeMerged.member_begin(I)),
ToBeMerged.member_end())) {
PartJ->moveTo(*PartI);
}
}
// Remove the empty partitions.
PartitionContainer.remove_if(
[](const InstPartition &P) { return P.empty(); });
return true;
}
/// Sets up the mapping between instructions to partitions. If the
/// instruction is duplicated across multiple partitions, set the entry to -1.
void setupPartitionIdOnInstructions() {
int PartitionID = 0;
for (const auto &Partition : PartitionContainer) {
for (Instruction *Inst : Partition) {
bool NewElt;
InstToPartitionIdT::iterator Iter;
std::tie(Iter, NewElt) =
InstToPartitionId.insert(std::make_pair(Inst, PartitionID));
if (!NewElt)
Iter->second = -1;
}
++PartitionID;
}
}
/// Populates the partition with everything that the seeding
/// instructions require.
void populateUsedSet() {
for (auto &P : PartitionContainer)
P.populateUsedSet();
}
/// This performs the main chunk of the work of cloning the loops for
/// the partitions.
void cloneLoops() {
BasicBlock *OrigPH = L->getLoopPreheader();
// At this point the predecessor of the preheader is either the memcheck
// block or the top part of the original preheader.
BasicBlock *Pred = OrigPH->getSinglePredecessor();
assert(Pred && "Preheader does not have a single predecessor");
BasicBlock *ExitBlock = L->getExitBlock();
assert(ExitBlock && "No single exit block");
Loop *NewLoop;
assert(!PartitionContainer.empty() && "at least two partitions expected");
// We're cloning the preheader along with the loop so we already made sure
// it was empty.
assert(&*OrigPH->begin() == OrigPH->getTerminator() &&
"preheader not empty");
// Preserve the original loop ID for use after the transformation.
MDNode *OrigLoopID = L->getLoopID();
// Create a loop for each partition except the last. Clone the original
// loop before PH along with adding a preheader for the cloned loop. Then
// update PH to point to the newly added preheader.
BasicBlock *TopPH = OrigPH;
unsigned Index = getSize() - 1;
for (auto I = std::next(PartitionContainer.rbegin()),
E = PartitionContainer.rend();
I != E; ++I, --Index, TopPH = NewLoop->getLoopPreheader()) {
auto *Part = &*I;
NewLoop = Part->cloneLoopWithPreheader(TopPH, Pred, Index, LI, DT);
Part->getVMap()[ExitBlock] = TopPH;
Part->remapInstructions();
setNewLoopID(OrigLoopID, Part);
}
Pred->getTerminator()->replaceUsesOfWith(OrigPH, TopPH);
// Also set a new loop ID for the last loop.
setNewLoopID(OrigLoopID, &PartitionContainer.back());
// Now go in forward order and update the immediate dominator for the
// preheaders with the exiting block of the previous loop. Dominance
// within the loop is updated in cloneLoopWithPreheader.
for (auto Curr = PartitionContainer.cbegin(),
Next = std::next(PartitionContainer.cbegin()),
E = PartitionContainer.cend();
Next != E; ++Curr, ++Next)
DT->changeImmediateDominator(
Next->getDistributedLoop()->getLoopPreheader(),
Curr->getDistributedLoop()->getExitingBlock());
}
/// Removes the dead instructions from the cloned loops.
void removeUnusedInsts() {
for (auto &Partition : PartitionContainer)
Partition.removeUnusedInsts();
}
/// For each memory pointer, it computes the partitionId the pointer is
/// used in.
///
/// This returns an array of int where the I-th entry corresponds to I-th
/// entry in LAI.getRuntimePointerCheck(). If the pointer is used in multiple
/// partitions its entry is set to -1.
SmallVector<int, 8>
computePartitionSetForPointers(const LoopAccessInfo &LAI) {
const RuntimePointerChecking *RtPtrCheck = LAI.getRuntimePointerChecking();
unsigned N = RtPtrCheck->Pointers.size();
SmallVector<int, 8> PtrToPartitions(N);
for (unsigned I = 0; I < N; ++I) {
Value *Ptr = RtPtrCheck->Pointers[I].PointerValue;
auto Instructions =
LAI.getInstructionsForAccess(Ptr, RtPtrCheck->Pointers[I].IsWritePtr);
int &Partition = PtrToPartitions[I];
// First set it to uninitialized.
Partition = -2;
for (Instruction *Inst : Instructions) {
// Note that this could be -1 if Inst is duplicated across multiple
// partitions.
int ThisPartition = this->InstToPartitionId[Inst];
if (Partition == -2)
Partition = ThisPartition;
// -1 means belonging to multiple partitions.
else if (Partition == -1)
break;
else if (Partition != (int)ThisPartition)
Partition = -1;
}
assert(Partition != -2 && "Pointer not belonging to any partition");
}
return PtrToPartitions;
}
void print(raw_ostream &OS) const {
unsigned Index = 0;
for (const auto &P : PartitionContainer) {
OS << "Partition " << Index++ << " (" << &P << "):\n";
P.print();
}
}
void dump() const { print(dbgs()); }
#ifndef NDEBUG
friend raw_ostream &operator<<(raw_ostream &OS,
const InstPartitionContainer &Partitions) {
Partitions.print(OS);
return OS;
}
#endif
void printBlocks() const {
unsigned Index = 0;
for (const auto &P : PartitionContainer) {
dbgs() << "\nPartition " << Index++ << " (" << &P << "):\n";
P.printBlocks();
}
}
private:
using PartitionContainerT = std::list<InstPartition>;
/// List of partitions.
PartitionContainerT PartitionContainer;
/// Mapping from Instruction to partition Id. If the instruction
/// belongs to multiple partitions the entry contains -1.
InstToPartitionIdT InstToPartitionId;
Loop *L;
LoopInfo *LI;
DominatorTree *DT;
/// The control structure to merge adjacent partitions if both satisfy
/// the \p Predicate.
template <class UnaryPredicate>
void mergeAdjacentPartitionsIf(UnaryPredicate Predicate) {
InstPartition *PrevMatch = nullptr;
for (auto I = PartitionContainer.begin(); I != PartitionContainer.end();) {
auto DoesMatch = Predicate(&*I);
if (PrevMatch == nullptr && DoesMatch) {
PrevMatch = &*I;
++I;
} else if (PrevMatch != nullptr && DoesMatch) {
I->moveTo(*PrevMatch);
I = PartitionContainer.erase(I);
} else {
PrevMatch = nullptr;
++I;
}
}
}
/// Assign new LoopIDs for the partition's cloned loop.
void setNewLoopID(MDNode *OrigLoopID, InstPartition *Part) {
Optional<MDNode *> PartitionID = makeFollowupLoopID(
OrigLoopID,
{LLVMLoopDistributeFollowupAll,
Part->hasDepCycle() ? LLVMLoopDistributeFollowupSequential
: LLVMLoopDistributeFollowupCoincident});
if (PartitionID.hasValue()) {
Loop *NewLoop = Part->getDistributedLoop();
NewLoop->setLoopID(PartitionID.getValue());
}
}
};
/// For each memory instruction, this class maintains difference of the
/// number of unsafe dependences that start out from this instruction minus
/// those that end here.
///
/// By traversing the memory instructions in program order and accumulating this
/// number, we know whether any unsafe dependence crosses over a program point.
class MemoryInstructionDependences {
using Dependence = MemoryDepChecker::Dependence;
public:
struct Entry {
Instruction *Inst;
unsigned NumUnsafeDependencesStartOrEnd = 0;
Entry(Instruction *Inst) : Inst(Inst) {}
};
using AccessesType = SmallVector<Entry, 8>;
AccessesType::const_iterator begin() const { return Accesses.begin(); }
AccessesType::const_iterator end() const { return Accesses.end(); }
MemoryInstructionDependences(
const SmallVectorImpl<Instruction *> &Instructions,
const SmallVectorImpl<Dependence> &Dependences) {
Accesses.append(Instructions.begin(), Instructions.end());
LLVM_DEBUG(dbgs() << "Backward dependences:\n");
for (auto &Dep : Dependences)
if (Dep.isPossiblyBackward()) {
// Note that the designations source and destination follow the program
// order, i.e. source is always first. (The direction is given by the
// DepType.)
++Accesses[Dep.Source].NumUnsafeDependencesStartOrEnd;
--Accesses[Dep.Destination].NumUnsafeDependencesStartOrEnd;
LLVM_DEBUG(Dep.print(dbgs(), 2, Instructions));
}
}
private:
AccessesType Accesses;
};
/// The actual class performing the per-loop work.
class LoopDistributeForLoop {
public:
LoopDistributeForLoop(Loop *L, Function *F, LoopInfo *LI, DominatorTree *DT,
ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
: L(L), F(F), LI(LI), DT(DT), SE(SE), ORE(ORE) {
setForced();
}
/// Try to distribute an inner-most loop.
bool processLoop(std::function<const LoopAccessInfo &(Loop &)> &GetLAA) {
assert(L->isInnermost() && "Only process inner loops.");
LLVM_DEBUG(dbgs() << "\nLDist: In \""
<< L->getHeader()->getParent()->getName()
<< "\" checking " << *L << "\n");
// Having a single exit block implies there's also one exiting block.
if (!L->getExitBlock())
return fail("MultipleExitBlocks", "multiple exit blocks");
if (!L->isLoopSimplifyForm())
return fail("NotLoopSimplifyForm",
"loop is not in loop-simplify form");
if (!L->isRotatedForm())
return fail("NotBottomTested", "loop is not bottom tested");
BasicBlock *PH = L->getLoopPreheader();
LAI = &GetLAA(*L);
// Currently, we only distribute to isolate the part of the loop with
// dependence cycles to enable partial vectorization.
if (LAI->canVectorizeMemory())
return fail("MemOpsCanBeVectorized",
"memory operations are safe for vectorization");
auto *Dependences = LAI->getDepChecker().getDependences();
if (!Dependences || Dependences->empty())
return fail("NoUnsafeDeps", "no unsafe dependences to isolate");
InstPartitionContainer Partitions(L, LI, DT);
// First, go through each memory operation and assign them to consecutive
// partitions (the order of partitions follows program order). Put those
// with unsafe dependences into "cyclic" partition otherwise put each store
// in its own "non-cyclic" partition (we'll merge these later).
//
// Note that a memory operation (e.g. Load2 below) at a program point that
// has an unsafe dependence (Store3->Load1) spanning over it must be
// included in the same cyclic partition as the dependent operations. This
// is to preserve the original program order after distribution. E.g.:
//
// NumUnsafeDependencesStartOrEnd NumUnsafeDependencesActive
// Load1 -. 1 0->1
// Load2 | /Unsafe/ 0 1
// Store3 -' -1 1->0
// Load4 0 0
//
// NumUnsafeDependencesActive > 0 indicates this situation and in this case
// we just keep assigning to the same cyclic partition until
// NumUnsafeDependencesActive reaches 0.
const MemoryDepChecker &DepChecker = LAI->getDepChecker();
MemoryInstructionDependences MID(DepChecker.getMemoryInstructions(),
*Dependences);
int NumUnsafeDependencesActive = 0;
for (auto &InstDep : MID) {
Instruction *I = InstDep.Inst;
// We update NumUnsafeDependencesActive post-instruction, catch the
// start of a dependence directly via NumUnsafeDependencesStartOrEnd.
if (NumUnsafeDependencesActive ||
InstDep.NumUnsafeDependencesStartOrEnd > 0)
Partitions.addToCyclicPartition(I);
else
Partitions.addToNewNonCyclicPartition(I);
NumUnsafeDependencesActive += InstDep.NumUnsafeDependencesStartOrEnd;
assert(NumUnsafeDependencesActive >= 0 &&
"Negative number of dependences active");
}
// Add partitions for values used outside. These partitions can be out of
// order from the original program order. This is OK because if the
// partition uses a load we will merge this partition with the original
// partition of the load that we set up in the previous loop (see
// mergeToAvoidDuplicatedLoads).
auto DefsUsedOutside = findDefsUsedOutsideOfLoop(L);
for (auto *Inst : DefsUsedOutside)
Partitions.addToNewNonCyclicPartition(Inst);
LLVM_DEBUG(dbgs() << "Seeded partitions:\n" << Partitions);
if (Partitions.getSize() < 2)
return fail("CantIsolateUnsafeDeps",
"cannot isolate unsafe dependencies");
// Run the merge heuristics: Merge non-cyclic adjacent partitions since we
// should be able to vectorize these together.
Partitions.mergeBeforePopulating();
LLVM_DEBUG(dbgs() << "\nMerged partitions:\n" << Partitions);
if (Partitions.getSize() < 2)
return fail("CantIsolateUnsafeDeps",
"cannot isolate unsafe dependencies");
// Now, populate the partitions with non-memory operations.
Partitions.populateUsedSet();
LLVM_DEBUG(dbgs() << "\nPopulated partitions:\n" << Partitions);
// In order to preserve original lexical order for loads, keep them in the
// partition that we set up in the MemoryInstructionDependences loop.
if (Partitions.mergeToAvoidDuplicatedLoads()) {
LLVM_DEBUG(dbgs() << "\nPartitions merged to ensure unique loads:\n"
<< Partitions);
if (Partitions.getSize() < 2)
return fail("CantIsolateUnsafeDeps",
"cannot isolate unsafe dependencies");
}
// Don't distribute the loop if we need too many SCEV run-time checks, or
// any if it's illegal.
const SCEVUnionPredicate &Pred = LAI->getPSE().getUnionPredicate();
if (LAI->hasConvergentOp() && !Pred.isAlwaysTrue()) {
return fail("RuntimeCheckWithConvergent",
"may not insert runtime check with convergent operation");
}
if (Pred.getComplexity() > (IsForced.getValueOr(false)
? PragmaDistributeSCEVCheckThreshold
: DistributeSCEVCheckThreshold))
return fail("TooManySCEVRuntimeChecks",
"too many SCEV run-time checks needed.\n");
if (!IsForced.getValueOr(false) && hasDisableAllTransformsHint(L))
return fail("HeuristicDisabled", "distribution heuristic disabled");
LLVM_DEBUG(dbgs() << "\nDistributing loop: " << *L << "\n");
// We're done forming the partitions set up the reverse mapping from
// instructions to partitions.
Partitions.setupPartitionIdOnInstructions();
// If we need run-time checks, version the loop now.
auto PtrToPartition = Partitions.computePartitionSetForPointers(*LAI);
const auto *RtPtrChecking = LAI->getRuntimePointerChecking();
const auto &AllChecks = RtPtrChecking->getChecks();
auto Checks = includeOnlyCrossPartitionChecks(AllChecks, PtrToPartition,
RtPtrChecking);
if (LAI->hasConvergentOp() && !Checks.empty()) {
return fail("RuntimeCheckWithConvergent",
"may not insert runtime check with convergent operation");
}
// To keep things simple have an empty preheader before we version or clone
// the loop. (Also split if this has no predecessor, i.e. entry, because we
// rely on PH having a predecessor.)
if (!PH->getSinglePredecessor() || &*PH->begin() != PH->getTerminator())
SplitBlock(PH, PH->getTerminator(), DT, LI);
if (!Pred.isAlwaysTrue() || !Checks.empty()) {
assert(!LAI->hasConvergentOp() && "inserting illegal loop versioning");
MDNode *OrigLoopID = L->getLoopID();
LLVM_DEBUG(dbgs() << "\nPointers:\n");
LLVM_DEBUG(LAI->getRuntimePointerChecking()->printChecks(dbgs(), Checks));
LoopVersioning LVer(*LAI, Checks, L, LI, DT, SE);
LVer.versionLoop(DefsUsedOutside);
LVer.annotateLoopWithNoAlias();
// The unversioned loop will not be changed, so we inherit all attributes
// from the original loop, but remove the loop distribution metadata to
// avoid to distribute it again.
MDNode *UnversionedLoopID =
makeFollowupLoopID(OrigLoopID,
{LLVMLoopDistributeFollowupAll,
LLVMLoopDistributeFollowupFallback},
"llvm.loop.distribute.", true)
.getValue();
LVer.getNonVersionedLoop()->setLoopID(UnversionedLoopID);
}
// Create identical copies of the original loop for each partition and hook
// them up sequentially.
Partitions.cloneLoops();
// Now, we remove the instruction from each loop that don't belong to that
// partition.
Partitions.removeUnusedInsts();
LLVM_DEBUG(dbgs() << "\nAfter removing unused Instrs:\n");
LLVM_DEBUG(Partitions.printBlocks());
if (LDistVerify) {
LI->verify(*DT);
assert(DT->verify(DominatorTree::VerificationLevel::Fast));
}
++NumLoopsDistributed;
// Report the success.
ORE->emit([&]() {
return OptimizationRemark(LDIST_NAME, "Distribute", L->getStartLoc(),
L->getHeader())
<< "distributed loop";
});
return true;
}
/// Provide diagnostics then \return with false.
bool fail(StringRef RemarkName, StringRef Message) {
LLVMContext &Ctx = F->getContext();
bool Forced = isForced().getValueOr(false);
LLVM_DEBUG(dbgs() << "Skipping; " << Message << "\n");
// With Rpass-missed report that distribution failed.
ORE->emit([&]() {
return OptimizationRemarkMissed(LDIST_NAME, "NotDistributed",
L->getStartLoc(), L->getHeader())
<< "loop not distributed: use -Rpass-analysis=loop-distribute for "
"more "
"info";
});
// With Rpass-analysis report why. This is on by default if distribution
// was requested explicitly.
ORE->emit(OptimizationRemarkAnalysis(
Forced ? OptimizationRemarkAnalysis::AlwaysPrint : LDIST_NAME,
RemarkName, L->getStartLoc(), L->getHeader())
<< "loop not distributed: " << Message);
// Also issue a warning if distribution was requested explicitly but it
// failed.
if (Forced)
Ctx.diagnose(DiagnosticInfoOptimizationFailure(
*F, L->getStartLoc(), "loop not distributed: failed "
"explicitly specified loop distribution"));
return false;
}
/// Return if distribution forced to be enabled/disabled for the loop.
///
/// If the optional has a value, it indicates whether distribution was forced
/// to be enabled (true) or disabled (false). If the optional has no value
/// distribution was not forced either way.
const Optional<bool> &isForced() const { return IsForced; }
private:
/// Filter out checks between pointers from the same partition.
///
/// \p PtrToPartition contains the partition number for pointers. Partition
/// number -1 means that the pointer is used in multiple partitions. In this
/// case we can't safely omit the check.
SmallVector<RuntimePointerCheck, 4> includeOnlyCrossPartitionChecks(
const SmallVectorImpl<RuntimePointerCheck> &AllChecks,
const SmallVectorImpl<int> &PtrToPartition,
const RuntimePointerChecking *RtPtrChecking) {
SmallVector<RuntimePointerCheck, 4> Checks;
copy_if(AllChecks, std::back_inserter(Checks),
[&](const RuntimePointerCheck &Check) {
for (unsigned PtrIdx1 : Check.first->Members)
for (unsigned PtrIdx2 : Check.second->Members)
// Only include this check if there is a pair of pointers
// that require checking and the pointers fall into
// separate partitions.
//
// (Note that we already know at this point that the two
// pointer groups need checking but it doesn't follow
// that each pair of pointers within the two groups need
// checking as well.
//
// In other words we don't want to include a check just
// because there is a pair of pointers between the two
// pointer groups that require checks and a different
// pair whose pointers fall into different partitions.)
if (RtPtrChecking->needsChecking(PtrIdx1, PtrIdx2) &&
!RuntimePointerChecking::arePointersInSamePartition(
PtrToPartition, PtrIdx1, PtrIdx2))
return true;
return false;
});
return Checks;
}
/// Check whether the loop metadata is forcing distribution to be
/// enabled/disabled.
void setForced() {
Optional<const MDOperand *> Value =
findStringMetadataForLoop(L, "llvm.loop.distribute.enable");
if (!Value)
return;
const MDOperand *Op = *Value;
assert(Op && mdconst::hasa<ConstantInt>(*Op) && "invalid metadata");
IsForced = mdconst::extract<ConstantInt>(*Op)->getZExtValue();
}
Loop *L;
Function *F;
// Analyses used.
LoopInfo *LI;
const LoopAccessInfo *LAI = nullptr;
DominatorTree *DT;
ScalarEvolution *SE;
OptimizationRemarkEmitter *ORE;
/// Indicates whether distribution is forced to be enabled/disabled for
/// the loop.
///
/// If the optional has a value, it indicates whether distribution was forced
/// to be enabled (true) or disabled (false). If the optional has no value
/// distribution was not forced either way.
Optional<bool> IsForced;
};
} // end anonymous namespace
/// Shared implementation between new and old PMs.
static bool runImpl(Function &F, LoopInfo *LI, DominatorTree *DT,
ScalarEvolution *SE, OptimizationRemarkEmitter *ORE,
std::function<const LoopAccessInfo &(Loop &)> &GetLAA) {
// Build up a worklist of inner-loops to vectorize. This is necessary as the
// act of distributing a loop creates new loops and can invalidate iterators
// across the loops.
SmallVector<Loop *, 8> Worklist;
for (Loop *TopLevelLoop : *LI)
for (Loop *L : depth_first(TopLevelLoop))
// We only handle inner-most loops.
if (L->isInnermost())
Worklist.push_back(L);
// Now walk the identified inner loops.
bool Changed = false;
for (Loop *L : Worklist) {
LoopDistributeForLoop LDL(L, &F, LI, DT, SE, ORE);
// If distribution was forced for the specific loop to be
// enabled/disabled, follow that. Otherwise use the global flag.
if (LDL.isForced().getValueOr(EnableLoopDistribute))
Changed |= LDL.processLoop(GetLAA);
}
// Process each loop nest in the function.
return Changed;
}
namespace {
/// The pass class.
class LoopDistributeLegacy : public FunctionPass {
public:
static char ID;
LoopDistributeLegacy() : FunctionPass(ID) {
// The default is set by the caller.
initializeLoopDistributeLegacyPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
std::function<const LoopAccessInfo &(Loop &)> GetLAA =
[&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
return runImpl(F, LI, DT, SE, ORE, GetLAA);
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<ScalarEvolutionWrapperPass>();
AU.addRequired<LoopInfoWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
AU.addRequired<LoopAccessLegacyAnalysis>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
}
};
} // end anonymous namespace
PreservedAnalyses LoopDistributePass::run(Function &F,
FunctionAnalysisManager &AM) {
auto &LI = AM.getResult<LoopAnalysis>(F);
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
// We don't directly need these analyses but they're required for loop
// analyses so provide them below.
auto &AA = AM.getResult<AAManager>(F);
auto &AC = AM.getResult<AssumptionAnalysis>(F);
auto &TTI = AM.getResult<TargetIRAnalysis>(F);
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
std::function<const LoopAccessInfo &(Loop &)> GetLAA =
[&](Loop &L) -> const LoopAccessInfo & {
LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE,
TLI, TTI, nullptr, nullptr, nullptr};
return LAM.getResult<LoopAccessAnalysis>(L, AR);
};
bool Changed = runImpl(F, &LI, &DT, &SE, &ORE, GetLAA);
if (!Changed)
return PreservedAnalyses::all();
PreservedAnalyses PA;
PA.preserve<LoopAnalysis>();
PA.preserve<DominatorTreeAnalysis>();
return PA;
}
char LoopDistributeLegacy::ID;
static const char ldist_name[] = "Loop Distribution";
INITIALIZE_PASS_BEGIN(LoopDistributeLegacy, LDIST_NAME, ldist_name, false,
false)
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
INITIALIZE_PASS_END(LoopDistributeLegacy, LDIST_NAME, ldist_name, false, false)
FunctionPass *llvm::createLoopDistributePass() { return new LoopDistributeLegacy(); }
| [
"[email protected]"
] | |
b0e0f7810af40f0f191f5fc29e0363fc2a48e4fb | 10d37c2326bdd70cd2aec8ba3d30272bfd3e5add | /BattleTank/Source/BattleTank/Private/TankPlayerController.cpp | c6ca609e7330f4222be8b1bd87b4455530be4614 | [] | no_license | talhek/BattleTank | 09db57de451fa4fa10a7ab45e6d46ff35e42d3ae | cbc10e0a08eec1b95dee59e8de4458ae9cabe4fd | refs/heads/master | 2021-05-16T17:43:53.787587 | 2017-09-24T09:34:29 | 2017-09-24T09:34:29 | 103,035,568 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,367 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Public/TankPlayerController.h"
#include "Tank.h"
void ATankPlayerController::BeginPlay() {
Super::BeginPlay();
//Logger();
}
ATank* ATankPlayerController::GetControlledTank() const
{
return Cast<ATank>(GetPawn());
}
void ATankPlayerController::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
AimTowardsCrosshair();
}
void ATankPlayerController::AimTowardsCrosshair()
{
if (!GetControlledTank()) {
return;
}
FVector OutHitLocation;
if (GetSightRayHitLocation(OutHitLocation)) {
GetControlledTank()->AimAt(OutHitLocation);
}
}
bool ATankPlayerController::GetSightRayHitLocation(FVector & OutHitLocation) const
{
int32 ViewportSizeX, ViewportSizeY;
FVector LookDirection;
//Find the crosshair position
GetViewportSize(ViewportSizeX, ViewportSizeY);
FVector2D ScreenLocation = FVector2D(ViewportSizeX* CrossHairXLocation, ViewportSizeY* CrossHairYLocation);
//De-project the screen position of the crosshair to a world direction
if (GetLookDirection(ScreenLocation, LookDirection)) {
//Line-trace along that look direction, and see what we hit(up to max range)
if (GetLookPlayerHitLocation(LookDirection, OutHitLocation)){}
}
return true;
}
bool ATankPlayerController::GetLookPlayerHitLocation(FVector LookDirection, FVector& OutHitLocation) const{
FHitResult HitResult = FHitResult();
auto StartLocation = PlayerCameraManager->GetCameraLocation();
auto EndLocation = StartLocation + (LookDirection * LineTraceRange);
if (GetWorld()->LineTraceSingleByChannel(HitResult,
StartLocation,
EndLocation,
ECollisionChannel::ECC_Visibility)) {
OutHitLocation = HitResult.Location;
return true;
}
else {
OutHitLocation = FVector(0.f);
return false;
}
}
bool ATankPlayerController::GetLookDirection(FVector2D ScreenLocation, FVector& LookDirection) const {
FVector CameraLookDirection; //to be discarded
return DeprojectScreenPositionToWorld(ScreenLocation.X, ScreenLocation.Y, CameraLookDirection, LookDirection);
}
void ATankPlayerController::Logger() {
ATank *LogTank = GetControlledTank();
UE_LOG(LogTemp, Warning, TEXT("TankPlayerController initiated"));
if (LogTank) {
UE_LOG(LogTemp, Warning, TEXT("The Tank is: %s"), *(LogTank->GetName()));
}
else {
UE_LOG(LogTemp, Warning, TEXT("No Tank is available"));
}
} | [
"[email protected]"
] | |
2f9b8d1f8f0f0ba26e27ec6892d6a78c33d95cae | 600fd105e3c19a993ddee81a8a7cb2e2f4e5cfe8 | /api/python/src/pyErr.hpp | c95ea23ce1230f470513c4ccad3b5466aa532bc6 | [
"Apache-2.0"
] | permissive | geekonion/LIEF | f4c750129f33ac93ba11f1e29d74ad73d50e76be | 7057b9d359ab63703cbb41310fb1110eeca8e649 | refs/heads/master | 2023-07-15T00:40:37.274434 | 2023-07-01T06:38:56 | 2023-07-01T06:38:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,440 | hpp | /* Copyright 2017 - 2023 R. Thomas
* Copyright 2017 - 2023 Quarkslab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PY_LIEF_ERR_H_
#define PY_LIEF_ERR_H_
#include <pybind11/pybind11.h>
#include "LIEF/errors.hpp"
namespace py = pybind11;
template <class Func, typename... Ts,
std::enable_if_t<!std::is_member_pointer<std::decay_t<Func>>{}, int> = 0>
py::object error_or(Func f, Ts&&... args) {
auto&& ret = f(std::forward<Ts>(args)...);
if (!ret) {
return py::cast(LIEF::as_lief_err(ret));
}
return py::cast(ret.value());
}
template <class Func, typename... Ts,
std::enable_if_t<std::is_member_pointer<std::decay_t<Func>>{}, int> = 0>
py::object error_or(Func f, Ts&&... args) {
auto&& ret = std::mem_fn(f)(std::forward<Ts>(args)...);
if (!ret) {
return py::cast(LIEF::as_lief_err(ret));
}
return py::cast(ret.value());
}
void init_LIEF_errors(py::module&);
#endif
| [
"[email protected]"
] | |
8b0f38d6d58e7890940e1bcd6c29a5723c5bd309 | dcc2bc687bfd0def79352398296ff1c401629189 | /bind10-1.1.0/src/lib/util/memory_segment_mapped.h | 7685e30c728211e98fef47537a8d98ebe24730fb | [
"LicenseRef-scancode-unknown-license-reference",
"ISC",
"BSL-1.0"
] | permissive | frozensunq/DHCPv4oDHCPv6 | 97aa51f554fcf1183b972634a9dfd1f707f143ed | 0a9cf99e5c6906453463e9f8cf6ebc87b98d8d71 | refs/heads/master | 2021-01-22T06:58:20.174910 | 2014-03-01T14:05:00 | 2014-03-01T14:05:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,293 | h | // Copyright (C) 2013 Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#ifndef MEMORY_SEGMENT_MAPPED_H
#define MEMORY_SEGMENT_MAPPED_H
#include <util/memory_segment.h>
#include <boost/noncopyable.hpp>
#include <string>
namespace isc {
namespace util {
/// \brief Mapped-file based Memory Segment class.
///
/// This implementation of \c MemorySegment uses a concrete file to be mapped
/// into memory. Multiple processes can share the same mapped memory image.
///
/// This class provides two operation modes: read-only and read-write.
/// A \c MemorySegmentMapped object in the read-only mode cannot modify the
/// mapped memory image or other internal maintenance data of the object;
/// In the read-write mode the object can allocate or deallocate memory
/// from the mapped image, and the owner process can change the content.
///
/// Multiple processes can open multiple segments for the same file in
/// read-only mode at the same time. But there shouldn't be more than
/// one process that opens segments for the same file in read-write mode
/// at the same time. Likewise, if one process opens a segment for a
/// file in read-write mode, there shouldn't be any other process that
/// opens a segment for the file in read-only mode. If one or more
/// processes open segments for a file in read-only mode, there
/// shouldn't be any other process that opens a segment for the file in
/// read-write mode. This class tries to detect any violation of this
/// restriction, but this does not intend to provide 100% safety. It's
/// generally the user's responsibility to ensure this condition.
///
/// The same restriction applies within the single process, whether
/// multi-threaded or not: a process shouldn't open read-only and read-write
/// (or multiple read-write) segments for the same file. The violation
/// detection mentioned above may or may not work in such cases due to
/// limitation of the underlying API. It's completely user's responsibility
/// to prevent this from happening. A single process may open multiple
/// segments in read-only mode for the same file, but that shouldn't be
/// necessary in practice; since it's read-only there wouldn't be a reason
/// to have a redundant copy.
class MemorySegmentMapped : boost::noncopyable, public MemorySegment {
public:
/// \brief The default value of the mapped file size when newly created.
///
/// Its value, 32KB, is an arbitrary choice, but considered to be
/// sufficiently but not too large.
static const size_t INITIAL_SIZE = 32768;
/// \brief Open modes of \c MemorySegmentMapped.
///
/// These modes matter only for \c MemorySegmentMapped to be opened
/// in read-write mode, and specify further details of open operation.
enum OpenMode {
OPEN_FOR_WRITE = 0, ///< Open only. File must exist.
OPEN_OR_CREATE, ///< If file doesn't exist it's created.
CREATE_ONLY ///< New file is created; existing one will be removed.
};
/// \brief Constructor in the read-only mode.
///
/// This constructor will map the content of the given file into memory
/// in read-only mode; the resulting memory segment object cannot
/// be used with methods that would require the mapped memory (see method
/// descriptions). Also, if the application tries to modify memory in
/// the segment, it will make the application crash.
///
/// The file must have been created by the other version of the
/// constructor beforehand and must be readable for the process
/// constructing this object. Otherwise \c MemorySegmentOpenError
/// exception will be thrown.
///
/// \throw MemorySegmentOpenError The given file does not exist, is not
/// readable, or not valid mappable segment. Or there is another process
/// that has already opened a segment for the file.
/// \throw std::bad_alloc (rare case) internal resource allocation
/// failure.
///
/// \param filename The file name to be mapped to memory.
MemorySegmentMapped(const std::string& filename);
/// \brief Constructor in the read-write mode.
///
/// This is similar to the read-only version of the constructor, but
/// does not have the restrictions that the read-only version has.
///
/// The \c mode parameter specifies further details of how the segment
/// should be opened.
/// - OPEN_FOR_WRITE: this is open-only mode. The file must exist,
/// and it will be opened without any initial modification.
/// - OPEN_OR_CREATE: similar to OPEN_FOR_WRITE, but if the file does not
/// exist, a new one will be created. An existing file will be used
/// any initial modification.
/// - CREATE_ONLY: a new file (of the given file name) will be created;
/// any existing file of the same name will be removed.
///
/// If OPEN_FOR_WRITE is specified, the specified file must exist
/// and be writable, and have been previously initialized by this
/// version of constructor either with OPEN_OR_CREATE or CREATE_ONLY.
/// If the mode is OPEN_OR_CREATE or CREATE_ONLY, and the file needs
/// to be created, then this method tries to create a new file of the
/// name and build internal data on it so that the file will be mappable
/// by this class object. If any of these conditions is not met, or
/// create or initialization fails, \c MemorySegmentOpenError exception
/// will be thrown.
///
/// This constructor also throws \c MemorySegmentOpenError when it
/// detects violation of the restriction on the mixed open of read-only
/// and read-write mode (see the class description).
///
/// When initial_size is specified but is too small (including a value of
/// 0), the underlying Boost library will reject it, and this constructor
/// throws \c MemorySegmentOpenError exception. The Boost documentation
/// does not specify how large it should be, but the default
/// \c INITIAL_SIZE should be sufficiently large in practice.
///
/// \throw MemorySegmentOpenError see the description.
///
/// \param filename The file name to be mapped to memory.
/// \param mode Open mode (see the description).
/// \param initial_size Specifies the size of the newly created file;
/// ignored if \c mode is OPEN_FOR_WRITE.
MemorySegmentMapped(const std::string& filename, OpenMode mode,
size_t initial_size = INITIAL_SIZE);
/// \brief Destructor.
///
/// If the object was constructed in the read-write mode and the underlying
/// memory segment wasn't broken due to an exceptional event, the
/// destructor ensures the content of the mapped memory is written back to
/// the corresponding file.
virtual ~MemorySegmentMapped();
/// \brief Allocate/acquire a segment of memory.
///
/// This version can throw \c MemorySegmentGrown.
///
/// This method cannot be called if the segment object is created in the
/// read-only mode; in that case MemorySegmentError will be thrown.
virtual void* allocate(size_t size);
/// \brief Deallocate/release a segment of memory.
///
/// This implementation does not check the validity of \c size, because
/// if this segment object was constructed for an existing file to map,
/// the underlying segment may already contain allocated regions, so
/// this object cannot reliably detect whether it's safe to deallocate
/// the given size of memory from the underlying segment.
///
/// Parameter \c ptr must point to an address that was returned by a
/// prior call to \c allocate() of this segment object, and there should
/// not be a \c MemorySegmentGrown exception thrown from \c allocate()
/// since then; if it was thrown the corresponding address must have been
/// adjusted some way; e.g., by re-fetching the latest mapped address
/// via \c getNamedAddress().
///
/// This method cannot be called if the segment object is created in the
/// read-only mode; in that case MemorySegmentError will be thrown.
virtual void deallocate(void* ptr, size_t size);
virtual bool allMemoryDeallocated() const;
/// \brief Mapped segment version of setNamedAddress.
///
/// This implementation detects if \c addr is invalid (see the base class
/// description) and throws \c MemorySegmentError in that case.
///
/// This version of method should normally return false. However,
/// it internally allocates memory in the segment for the name and
/// address to be stored, which can require segment extension, just like
/// allocate(). So it's possible to return true unlike
/// \c MemorySegmentLocal version of the method.
///
/// This method cannot be called if the segment object is created in the
/// read-only mode; in that case MemorySegmentError will be thrown.
virtual bool setNamedAddressImpl(const char* name, void* addr);
/// \brief Mapped segment version of getNamedAddress.
///
/// This version never throws.
virtual void* getNamedAddressImpl(const char* name);
/// \brief Mapped segment version of clearNamedAddress.
///
/// This method cannot be called if the segment object is created in the
/// read-only mode; in that case MemorySegmentError will be thrown.
virtual bool clearNamedAddressImpl(const char* name);
/// \brief Shrink the underlying mapped segment to actually used size.
///
/// When a large amount of memory is allocated and then deallocated
/// from the segment, this method can be used to keep the resulting
/// segment at a reasonable size.
///
/// This method works by a best-effort basis, and does not guarantee
/// any specific result.
///
/// This method is generally expected to be failure-free, but it's still
/// possible to fail. For example, the underlying file may not be writable
/// at the time of shrink attempt; it also tries to remap the shrunk
/// segment internally, and there's a small chance it could fail.
/// In such a case it throws \c MemorySegmentError. If it's thrown the
/// segment is not usable anymore.
///
/// This method cannot be called if the segment object is created in the
/// read-only mode; in that case MemorySegmentError will be thrown.
///
/// \throw MemorySegmentError see the description.
void shrinkToFit();
/// \brief Return the actual segment size.
///
/// This is generally expected to be the file size to map. It's
/// provided mainly for diagnosis and testing purposes; the application
/// shouldn't rely on specific return values of this method.
///
/// \throw None
size_t getSize() const;
/// \brief Calculate a checksum over the memory segment.
///
/// This method goes over all pages of the underlying mapped memory
/// segment, and returns the sum of the value of the first byte of each
/// page (wrapping around upon overflow). It only proves weak integrity
/// of the file contents, but can run fast enough and will ensure all
/// pages are actually in memory. The latter property will be useful
/// if the application cannot allow the initial page fault overhead.
///
/// \throw None
size_t getCheckSum() const;
private:
struct Impl;
Impl* impl_;
};
} // namespace util
} // namespace isc
#endif // MEMORY_SEGMENT_MAPPED_H
// Local Variables:
// mode: c++
// End:
| [
"dhc@dhc-VirtualBox.(none)"
] | dhc@dhc-VirtualBox.(none) |
c08e2c325f55f84677f31d6c431f395bca1d46d1 | 0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd | /chromeos/services/secure_channel/pending_ble_listener_connection_request_unittest.cc | 12872f097808162ccf901fd7c88f24ea24b8ccb5 | [
"BSD-3-Clause"
] | permissive | yachtcaptain23/browser-android-tabs | e5144cee9141890590d6d6faeb1bdc5d58a6cbf1 | a016aade8f8333c822d00d62738a922671a52b85 | refs/heads/master | 2021-04-28T17:07:06.955483 | 2018-09-26T06:22:11 | 2018-09-26T06:22:11 | 122,005,560 | 0 | 0 | NOASSERTION | 2019-05-17T19:37:59 | 2018-02-19T01:00:10 | null | UTF-8 | C++ | false | false | 3,234 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/services/secure_channel/pending_ble_listener_connection_request.h"
#include <memory>
#include "base/run_loop.h"
#include "base/test/scoped_task_environment.h"
#include "base/unguessable_token.h"
#include "chromeos/services/secure_channel/fake_client_connection_parameters.h"
#include "chromeos/services/secure_channel/fake_pending_connection_request_delegate.h"
#include "chromeos/services/secure_channel/public/cpp/shared/connection_priority.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace secure_channel {
namespace {
const char kTestFeature[] = "testFeature";
} // namespace
class SecureChannelPendingBleListenerConnectionRequestTest
: public testing::Test {
protected:
SecureChannelPendingBleListenerConnectionRequestTest() = default;
~SecureChannelPendingBleListenerConnectionRequestTest() override = default;
// testing::Test:
void SetUp() override {
fake_pending_connection_request_delegate_ =
std::make_unique<FakePendingConnectionRequestDelegate>();
auto fake_client_connection_parameters =
std::make_unique<FakeClientConnectionParameters>(kTestFeature);
fake_client_connection_parameters_ =
fake_client_connection_parameters.get();
pending_ble_listener_request_ =
PendingBleListenerConnectionRequest::Factory::Get()->BuildInstance(
std::move(fake_client_connection_parameters),
ConnectionPriority::kLow,
fake_pending_connection_request_delegate_.get());
}
const base::Optional<
PendingConnectionRequestDelegate::FailedConnectionReason>&
GetFailedConnectionReason() {
return fake_pending_connection_request_delegate_
->GetFailedConnectionReasonForId(
pending_ble_listener_request_->GetRequestId());
}
const base::Optional<mojom::ConnectionAttemptFailureReason>&
GetConnectionAttemptFailureReason() {
return fake_client_connection_parameters_->failure_reason();
}
void HandleConnectionFailure(BleListenerFailureType failure_type) {
pending_ble_listener_request_->HandleConnectionFailure(failure_type);
}
private:
const base::test::ScopedTaskEnvironment scoped_task_environment_;
std::unique_ptr<FakePendingConnectionRequestDelegate>
fake_pending_connection_request_delegate_;
FakeClientConnectionParameters* fake_client_connection_parameters_;
std::unique_ptr<PendingConnectionRequest<BleListenerFailureType>>
pending_ble_listener_request_;
DISALLOW_COPY_AND_ASSIGN(
SecureChannelPendingBleListenerConnectionRequestTest);
};
TEST_F(SecureChannelPendingBleListenerConnectionRequestTest,
HandleAuthenticationError) {
HandleConnectionFailure(BleListenerFailureType::kAuthenticationError);
EXPECT_EQ(
PendingConnectionRequestDelegate::FailedConnectionReason::kRequestFailed,
*GetFailedConnectionReason());
EXPECT_EQ(mojom::ConnectionAttemptFailureReason::AUTHENTICATION_ERROR,
*GetConnectionAttemptFailureReason());
}
} // namespace secure_channel
} // namespace chromeos
| [
"[email protected]"
] | |
6a982b4176838a7a7dbcc1331fecd9349913b750 | c9c5c2e97f4a18fc34c198640478ee533ee3d2cf | /src/qt/rpcconsole.cpp | 9a7d35c1ea7ecac835fa8fd9c476e77f05565890 | [
"MIT"
] | permissive | cashcash-project/cashcash-2.0 | d0c64f909f645f605412f5a2f8a14dbabdf36748 | 18ce7648c6f973a18bf8918d3cf68ff220cf8a3d | refs/heads/master | 2023-05-30T23:50:25.245029 | 2021-07-08T22:45:06 | 2021-07-08T22:45:06 | 383,936,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,139 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2020 The cashcash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "bantablemodel.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "peertablemodel.h"
#include "chainparams.h"
#include "netbase.h"
#include "rpc/client.h"
#include "rpc/server.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif // ENABLE_WALLET
#include <univalue.h>
#ifdef ENABLE_WALLET
#include <db_cxx.h>
#endif
#include <QDir>
#include <QKeyEvent>
#include <QMenu>
#include <QScrollBar>
#include <QThread>
#include <QTime>
#include <QTimer>
#include <QStringList>
// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
// Repair parameters
const QString SALVAGEWALLET("-salvagewallet");
const QString RESCAN("-rescan");
const QString ZAPTXES1("-zapwallettxes=1");
const QString ZAPTXES2("-zapwallettxes=2");
const QString UPGRADEWALLET("-upgradewallet");
const QString REINDEX("-reindex");
const QString RESYNC("-resync");
const struct {
const char* url;
const char* source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor : public QObject
{
Q_OBJECT
public Q_SLOTS:
void request(const QString& command);
Q_SIGNALS:
void reply(int category, const QString& command);
};
/** Class for handling RPC timers
* (used for e.g. re-locking the wallet after a timeout)
*/
class QtRPCTimerBase: public QObject, public RPCTimerBase
{
Q_OBJECT
public:
QtRPCTimerBase(std::function<void(void)>& _func, int64_t millis):
func(_func)
{
timer.setSingleShot(true);
connect(&timer, &QTimer::timeout, [this]{ func(); });
timer.start(millis);
}
~QtRPCTimerBase() {}
private:
QTimer timer;
std::function<void(void)> func;
};
class QtRPCTimerInterface: public RPCTimerInterface
{
public:
~QtRPCTimerInterface() {}
const char *Name() { return "Qt"; }
RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis)
{
return new QtRPCTimerBase(func, millis);
}
};
#include "rpcconsole.moc"
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string>& args, const std::string& strCommand)
{
enum CmdParseState {
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
for (char ch : strCommand) {
switch (state) {
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch (ch) {
case '"':
state = STATE_DOUBLEQUOTED;
break;
case '\'':
state = STATE_SINGLEQUOTED;
break;
case '\\':
state = STATE_ESCAPE_OUTER;
break;
case ' ':
case '\n':
case '\t':
if (state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default:
curarg += ch;
state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch (ch) {
case '\'':
state = STATE_ARGUMENT;
break;
default:
curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch (ch) {
case '"':
state = STATE_ARGUMENT;
break;
case '\\':
state = STATE_ESCAPE_DOUBLEQUOTED;
break;
default:
curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch;
state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if (ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch;
state = STATE_DOUBLEQUOTED;
break;
}
}
switch (state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString& command)
{
std::vector<std::string> args;
if (!parseCommandLine(args, command.toStdString())) {
Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if (args.empty())
return; // Nothing to do
try {
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
JSONRPCRequest req;
req.params = RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()));
req.strMethod = args[0];
UniValue result = tableRPC.execute(req);
// Format result reply
if (result.isNull())
strPrint = "";
else if (result.isStr())
strPrint = result.get_str();
else
strPrint = result.write(2);
Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
} catch (const UniValue& objError) {
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
} catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write()));
}
} catch (const std::exception& e) {
Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::RPCConsole),
clientModel(0),
historyPtr(0),
cachedNodeid(-1),
peersTableContextMenu(0),
banTableContextMenu(0)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);
#ifndef Q_OS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, &QPushButton::clicked, this, &RPCConsole::clear);
connect(ui->btnClearTrafficGraph, &QPushButton::clicked, ui->trafficGraph, &TrafficGraphWidget::clear);
// Wallet Repair Buttons
connect(ui->btn_salvagewallet, &QPushButton::clicked, this, &RPCConsole::walletSalvage);
connect(ui->btn_rescan, &QPushButton::clicked, this, &RPCConsole::walletRescan);
connect(ui->btn_zapwallettxes1, &QPushButton::clicked, this, &RPCConsole::walletZaptxes1);
connect(ui->btn_zapwallettxes2, &QPushButton::clicked, this, &RPCConsole::walletZaptxes2);
connect(ui->btn_upgradewallet, &QPushButton::clicked, this, &RPCConsole::walletUpgrade);
connect(ui->btn_reindex, &QPushButton::clicked, this, &RPCConsole::walletReindex);
connect(ui->btn_resync, &QPushButton::clicked, this, &RPCConsole::walletResync);
// set library version labels
#ifdef ENABLE_WALLET
std::string strPathCustom = gArgs.GetArg("-backuppath", "");
int nCustomBackupThreshold = gArgs.GetArg("-custombackupthreshold", DEFAULT_CUSTOMBACKUPTHRESHOLD);
if(!strPathCustom.empty()) {
ui->wallet_custombackuppath->setText(QString::fromStdString(strPathCustom));
ui->wallet_custombackuppath_label->show();
ui->wallet_custombackuppath->show();
if (nCustomBackupThreshold > 0) {
ui->wallet_custombackupthreshold->setText(QString::fromStdString(std::to_string(nCustomBackupThreshold)));
ui->wallet_custombackupthreshold_label->setVisible(true);
ui->wallet_custombackupthreshold->setVisible(true);
}
}
ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
ui->wallet_path->setText(QString::fromStdString(GetDataDir().string() + QDir::separator().toLatin1() + gArgs.GetArg("-wallet", DEFAULT_WALLET_DAT)));
#else
ui->label_berkeleyDBVersion->hide();
ui->berkeleyDBVersion->hide();
#endif
// Register RPC timer interface
rpcTimerInterface = new QtRPCTimerInterface();
// avoid accidentally overwriting an existing, non QTThread
// based timer interface
RPCSetTimerInterfaceIfUnset(rpcTimerInterface);
startExecutor();
setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
clear();
}
RPCConsole::~RPCConsole()
{
GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
Q_EMIT stopExecutor();
RPCUnsetTimerInterface(rpcTimerInterface);
delete rpcTimerInterface;
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent* keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch (key) {
case Qt::Key_Up:
if (obj == ui->lineEdit) {
browseHistory(-1);
return true;
}
break;
case Qt::Key_Down:
if (obj == ui->lineEdit) {
browseHistory(1);
return true;
}
break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if (obj == ui->lineEdit) {
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
case Qt::Key_Return:
case Qt::Key_Enter:
// forward these events to lineEdit
if(obj == autoCompleter->popup()) {
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if (obj == ui->messagesWidget && ((!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) {
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel* model)
{
clientModel = model;
ui->trafficGraph->setClientModel(model);
if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) {
// Keep up to date with client
setNumConnections(model->getNumConnections());
connect(model, &ClientModel::numConnectionsChanged, this, &RPCConsole::setNumConnections);
setNumBlocks(model->getNumBlocks());
connect(model, &ClientModel::numBlocksChanged, this, &RPCConsole::setNumBlocks);
connect(model, &ClientModel::strMasternodesChanged, this, &RPCConsole::setMasternodeCount);
updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
connect(model, &ClientModel::bytesChanged, this, &RPCConsole::updateTrafficStats);
// set up peer table
ui->peerWidget->setModel(model->getPeerTableModel());
ui->peerWidget->verticalHeader()->hide();
ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->peerWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
ui->peerWidget->horizontalHeader()->setStretchLastSection(true);
// create peer table context menu actions
QAction* disconnectAction = new QAction(tr("&Disconnect Node"), this);
QAction* banAction1h = new QAction(tr("Ban Node for") + " " + tr("1 &hour"), this);
QAction* banAction24h = new QAction(tr("Ban Node for") + " " + tr("1 &day"), this);
QAction* banAction7d = new QAction(tr("Ban Node for") + " " + tr("1 &week"), this);
QAction* banAction365d = new QAction(tr("Ban Node for") + " " + tr("1 &year"), this);
// create peer table context menu
peersTableContextMenu = new QMenu();
peersTableContextMenu->addAction(disconnectAction);
peersTableContextMenu->addAction(banAction1h);
peersTableContextMenu->addAction(banAction24h);
peersTableContextMenu->addAction(banAction7d);
peersTableContextMenu->addAction(banAction365d);
connect(banAction1h, &QAction::triggered, [this] { banSelectedNode(60 * 60); });
connect(banAction24h, &QAction::triggered, [this] { banSelectedNode(60 * 60 * 24); });
connect(banAction7d, &QAction::triggered, [this] { banSelectedNode(60 * 60 * 24 * 7); });
connect(banAction365d, &QAction::triggered, [this] { banSelectedNode(60 * 60 * 24 * 365); });
// peer table context menu signals
connect(ui->peerWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showPeersTableContextMenu);
connect(disconnectAction, &QAction::triggered, this, &RPCConsole::disconnectSelectedNode);
// peer table signal handling - update peer details when selecting new node
connect(ui->peerWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &RPCConsole::peerSelected);
// peer table signal handling - update peer details when new nodes are added to the model
connect(model->getPeerTableModel(), &PeerTableModel::layoutChanged, this, &RPCConsole::peerLayoutChanged);
// set up ban table
ui->banlistWidget->setModel(model->getBanTableModel());
ui->banlistWidget->verticalHeader()->hide();
ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);
// create ban table context menu action
QAction* unbanAction = new QAction(tr("&Unban Node"), this);
// create ban table context menu
banTableContextMenu = new QMenu();
banTableContextMenu->addAction(unbanAction);
// ban table context menu signals
connect(ui->banlistWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showBanTableContextMenu);
connect(unbanAction, &QAction::triggered, this, &RPCConsole::unbanSelectedNode);
// ban table signal handling - clear peer details when clicking a peer in the ban table
connect(ui->banlistWidget, &QTableView::clicked, this, &RPCConsole::clearSelectedNode);
// ban table signal handling - ensure ban table is shown or hidden (if empty)
connect(model->getBanTableModel(), &BanTableModel::layoutChanged, this, &RPCConsole::showOrHideBanTableIfRequired);
showOrHideBanTableIfRequired();
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->dataDir->setText(model->dataDir());
ui->startupTime->setText(model->formatClientStartupTime());
ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));
//Setup autocomplete and attach it
QStringList wordList;
std::vector<std::string> commandList = tableRPC.listCommands();
for (size_t i = 0; i < commandList.size(); ++i)
{
wordList << commandList[i].c_str();
wordList << ("help " + commandList[i]).c_str();
}
wordList.sort();
autoCompleter = new QCompleter(wordList, this);
autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
ui->lineEdit->setCompleter(autoCompleter);
// clear the lineEdit after activating from QCompleter
autoCompleter->popup()->installEventFilter(this);
}
}
static QString categoryClass(int category)
{
switch (category) {
case RPCConsole::CMD_REQUEST:
return "cmd-request";
break;
case RPCConsole::CMD_REPLY:
return "cmd-reply";
break;
case RPCConsole::CMD_ERROR:
return "cmd-error";
break;
default:
return "misc";
}
}
/** Restart wallet with "-salvagewallet" */
void RPCConsole::walletSalvage()
{
buildParameterlist(SALVAGEWALLET);
}
/** Restart wallet with "-rescan" */
void RPCConsole::walletRescan()
{
buildParameterlist(RESCAN);
}
/** Restart wallet with "-zapwallettxes=1" */
void RPCConsole::walletZaptxes1()
{
buildParameterlist(ZAPTXES1);
}
/** Restart wallet with "-zapwallettxes=2" */
void RPCConsole::walletZaptxes2()
{
buildParameterlist(ZAPTXES2);
}
/** Restart wallet with "-upgradewallet" */
void RPCConsole::walletUpgrade()
{
buildParameterlist(UPGRADEWALLET);
}
/** Restart wallet with "-reindex" */
void RPCConsole::walletReindex()
{
buildParameterlist(REINDEX);
}
/** Restart wallet with "-resync" */
void RPCConsole::walletResync()
{
QString resyncWarning = tr("This will delete your local blockchain folders and the wallet will synchronize the complete Blockchain from scratch.<br /><br />");
resyncWarning += tr("This needs quite some time and downloads a lot of data.<br /><br />");
resyncWarning += tr("Your transactions and funds will be visible again after the download has completed.<br /><br />");
resyncWarning += tr("Do you want to continue?.<br />");
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm resync Blockchain"),
resyncWarning,
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval != QMessageBox::Yes) {
// Resync canceled
return;
}
// Restart and resync
buildParameterlist(RESYNC);
}
/** Build command-line parameter list for restart */
void RPCConsole::buildParameterlist(QString arg)
{
// Get command-line arguments and remove the application name
QStringList args = QApplication::arguments();
args.removeFirst();
// Remove existing repair-options
args.removeAll(SALVAGEWALLET);
args.removeAll(RESCAN);
args.removeAll(ZAPTXES1);
args.removeAll(ZAPTXES2);
args.removeAll(UPGRADEWALLET);
args.removeAll(REINDEX);
// Append repair parameter to command line.
args.append(arg);
// Send command-line arguments to BitcoinGUI::handleRestart()
Q_EMIT handleRestart(args);
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
history.clear();
historyPtr = 0;
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for (int i = 0; ICON_MAPPING[i].url; ++i) {
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Courier, Courier New, Lucida Console, monospace; font-size: 12px; } " // Todo: Remove fixed font-size
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
".secwarning { color: red; }"
"b { color: #006060; } ");
#ifdef Q_OS_MAC
QString clsKey = "(⌘)-L";
#else
QString clsKey = "Ctrl-L";
#endif
message(CMD_REPLY, (tr("Welcome to the cashcash RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.") +
"<br><span class=\"secwarning\"><br>" +
tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") +
"</span>"),
true);
}
void RPCConsole::reject()
{
// Ignore escape keypress if this is not a seperate window
if (windowType() != Qt::Widget)
QDialog::reject();
}
void RPCConsole::message(int category, const QString& message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if (html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
if (!clientModel)
return;
QString connections = QString::number(count) + " (";
connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
ui->numberOfConnections->setText(connections);
}
void RPCConsole::setNumBlocks(int count)
{
ui->numberOfBlocks->setText(QString::number(count));
if (clientModel) {
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
ui->lastBlockHash->setText(clientModel->getLastBlockHash());
}
}
void RPCConsole::setMasternodeCount(const QString& strMasternodes)
{
ui->masternodeCount->setText(strMasternodes);
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if (!cmd.isEmpty()) {
message(CMD_REQUEST, cmd);
Q_EMIT cmdRequest(cmd);
// Remove command, if already in history
history.removeOne(cmd);
// Append command to history
history.append(cmd);
// Enforce maximum history size
while (history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if (historyPtr < 0)
historyPtr = 0;
if (historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if (historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor* executor = new RPCExecutor();
executor->moveToThread(thread);
// Replies from executor object must go to this object
connect(executor, &RPCExecutor::reply, this, static_cast<void (RPCConsole::*)(int, const QString&)>(&RPCConsole::message));
// Requests from this object must go to executor
connect(this, &RPCConsole::cmdRequest, executor, &RPCExecutor::request);
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, &RPCConsole::stopExecutor, executor, &RPCExecutor::deleteLater);
connect(this, &RPCConsole::stopExecutor, thread, &QThread::quit);
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, &QThread::finished, thread, &QThread::deleteLater);
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if (ui->tabWidget->widget(index) == ui->tab_console) {
ui->lineEdit->setFocus();
} else if (ui->tabWidget->widget(index) != ui->tab_peers) {
clearSelectedNode();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar* scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_sldGraphRange_valueChanged(int value)
{
const int multiplier = 5; // each position on the slider represents 5 min
int mins = value * multiplier;
setTrafficGraphRange(mins);
}
QString RPCConsole::FormatBytes(quint64 bytes)
{
if (bytes < 1024)
return QString(tr("%1 B")).arg(bytes);
if (bytes < 1024 * 1024)
return QString(tr("%1 KB")).arg(bytes / 1024);
if (bytes < 1024 * 1024 * 1024)
return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);
return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
}
void RPCConsole::setTrafficGraphRange(int mins)
{
ui->trafficGraph->setGraphRangeMins(mins);
ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
}
void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
{
ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
}
void RPCConsole::showInfo()
{
ui->tabWidget->setCurrentIndex(0);
show();
}
void RPCConsole::showConsole()
{
ui->tabWidget->setCurrentIndex(1);
show();
}
void RPCConsole::showNetwork()
{
ui->tabWidget->setCurrentIndex(2);
show();
}
void RPCConsole::showPeers()
{
ui->tabWidget->setCurrentIndex(3);
show();
}
void RPCConsole::showRepair()
{
ui->tabWidget->setCurrentIndex(4);
show();
}
void RPCConsole::showConfEditor()
{
GUIUtil::openConfigfile();
}
void RPCConsole::showMNConfEditor()
{
GUIUtil::openMNConfigfile();
}
void RPCConsole::peerSelected(const QItemSelection& selected, const QItemSelection& deselected)
{
Q_UNUSED(deselected);
if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
return;
const CNodeCombinedStats* stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::peerLayoutChanged()
{
if (!clientModel || !clientModel->getPeerTableModel())
return;
const CNodeCombinedStats* stats = NULL;
bool fUnselect = false;
bool fReselect = false;
if (cachedNodeid == -1) // no node selected yet
return;
// find the currently selected row
int selectedRow = -1;
QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
if (!selectedModelIndex.isEmpty()) {
selectedRow = selectedModelIndex.first().row();
}
// check if our detail node has a row in the table (it may not necessarily
// be at selectedRow since its position can change after a layout change)
int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeid);
if (detailNodeRow < 0) {
// detail node dissapeared from table (node disconnected)
fUnselect = true;
} else {
if (detailNodeRow != selectedRow) {
// detail node moved position
fUnselect = true;
fReselect = true;
}
// get fresh stats on the detail node.
stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
}
if (fUnselect && selectedRow >= 0) {
clearSelectedNode();
}
if (fReselect) {
ui->peerWidget->selectRow(detailNodeRow);
}
if (stats)
updateNodeDetail(stats);
}
void RPCConsole::updateNodeDetail(const CNodeCombinedStats* stats)
{
// Update cached nodeid
cachedNodeid = stats->nodeStats.nodeid;
// update the detail ui with latest node information
QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
if (!stats->nodeStats.addrLocal.empty())
peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
ui->peerHeading->setText(peerAddrDetails);
ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastSend) : tr("never"));
ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nLastRecv) : tr("never"));
ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes));
ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes));
ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetTime() - stats->nodeStats.nTimeConnected));
ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));
// This check fails for example if the lock was busy and
// nodeStateStats couldn't be fetched.
if (stats->fNodeStateStatsAvailable) {
// Ban score is init to 0
ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));
// Sync height is init to -1
if (stats->nodeStateStats.nSyncHeight > -1)
ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
else
ui->peerSyncHeight->setText(tr("Unknown"));
// Common height is init to -1
if (stats->nodeStateStats.nCommonHeight > -1)
ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
else
ui->peerCommonHeight->setText(tr("Unknown"));
}
ui->detailWidget->show();
}
void RPCConsole::resizeEvent(QResizeEvent* event)
{
QWidget::resizeEvent(event);
}
void RPCConsole::showEvent(QShowEvent* event)
{
QWidget::showEvent(event);
if (!clientModel || !clientModel->getPeerTableModel())
return;
// start PeerTableModel auto refresh
clientModel->getPeerTableModel()->startAutoRefresh();
clientModel->startMasternodesTimer();
}
void RPCConsole::hideEvent(QHideEvent* event)
{
QWidget::hideEvent(event);
if (!clientModel || !clientModel->getPeerTableModel())
return;
// stop PeerTableModel auto refresh
clientModel->getPeerTableModel()->stopAutoRefresh();
clientModel->stopMasternodesTimer();
}
void RPCConsole::showBackups()
{
GUIUtil::showBackups();
}
void RPCConsole::showPeersTableContextMenu(const QPoint& point)
{
QModelIndex index = ui->peerWidget->indexAt(point);
if (index.isValid())
peersTableContextMenu->exec(QCursor::pos());
}
void RPCConsole::showBanTableContextMenu(const QPoint& point)
{
QModelIndex index = ui->banlistWidget->indexAt(point);
if (index.isValid())
banTableContextMenu->exec(QCursor::pos());
}
void RPCConsole::disconnectSelectedNode()
{
if(!g_connman)
return;
// Get currently selected peer address
NodeId id = GUIUtil::getEntryData(ui->peerWidget, 0, PeerTableModel::NetNodeId).toInt();
// Find the node, disconnect it and clear the selected node
if(g_connman->DisconnectNode(id))
clearSelectedNode();
}
void RPCConsole::banSelectedNode(int bantime)
{
if (!clientModel || !g_connman)
return;
// Get currently selected peer address
QString strNode = GUIUtil::getEntryData(ui->peerWidget, 0, PeerTableModel::Address).toString();
// Find possible nodes, ban it and clear the selected node
std::string nStr = strNode.toStdString();
std::string addr;
int port = 0;
SplitHostPort(nStr, port, addr);
CNetAddr resolved;
if (!LookupHost(addr.c_str(), resolved, false))
return;
g_connman->Ban(resolved, BanReasonManuallyAdded, bantime);
clearSelectedNode();
clientModel->getBanTableModel()->refresh();
}
void RPCConsole::unbanSelectedNode()
{
if (!clientModel)
return;
// Get currently selected ban address
QString strNode = GUIUtil::getEntryData(ui->banlistWidget, 0, BanTableModel::Address).toString();
CSubNet possibleSubnet;
LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
if (possibleSubnet.IsValid() && g_connman)
{
g_connman->Unban(possibleSubnet);
clientModel->getBanTableModel()->refresh();
}
}
void RPCConsole::clearSelectedNode()
{
ui->peerWidget->selectionModel()->clearSelection();
cachedNodeid = -1;
ui->detailWidget->hide();
ui->peerHeading->setText(tr("Select a peer to view detailed information."));
}
void RPCConsole::showOrHideBanTableIfRequired()
{
if (!clientModel)
return;
bool visible = clientModel->getBanTableModel()->shouldShow();
ui->banlistWidget->setVisible(visible);
ui->banHeading->setVisible(visible);
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.