blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
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
listlengths
1
1
author
stringlengths
0
119
2cb4b53bdfd350346e9c195abb3d3e46bd2cecec
f148621e215a0e35b4422085cdcc9fd062ff8bc0
/BattleTank/Source/BattleTank/Private/TankAIController.cpp
82d76d4922c90aa871560fbede83558f1fd37f82
[]
no_license
udemy-unreal-course/04_BattleTank
e014905c1cd892ad357a68685ae2b63ffc81c508
65fa8ea54fced5f0ce0a91d4029207d9382f17b4
refs/heads/master
2021-07-14T23:11:18.812796
2020-06-24T19:43:12
2020-06-24T19:43:12
175,212,778
0
0
null
null
null
null
UTF-8
C++
false
false
1,017
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "TankAIController.h" void ATankAIController::BeginPlay() { Super::BeginPlay(); auto PlayerTank = GetPlayerTank(); if (!PlayerTank) { UE_LOG(LogTemp, Warning, TEXT("AI Controller can't find player tank")); } else { UE_LOG(LogTemp, Warning, TEXT("AI Controller found player: %s"), *(PlayerTank->GetName())); } } void ATankAIController::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (GetControlledTank() && GetPlayerTank()) { // TODO Move towards the player. // Aim towards the player GetControlledTank()->AimAt(GetPlayerTank()->GetTargetLocation()); /// Figured this onmy own!!! ^^ !!! // Fire if ready } } ATank* ATankAIController::GetControlledTank() const { return Cast<ATank>(GetPawn()); } ATank* ATankAIController::GetPlayerTank() const { auto PlayerPawn = GetWorld()->GetFirstPlayerController()->GetPawn(); if (!PlayerPawn) { return nullptr; } return Cast<ATank>(PlayerPawn); }
[ "netshield@seznam.cz" ]
netshield@seznam.cz
da2f1a6402904f62c311eaaabd64541193850af9
78e6682db4899f76ae337b71fdbf55e768904d17
/s3_conn.h
ec716dc801e4a8c802fa1b24704031eaa59acf88
[ "BSD-2-Clause" ]
permissive
budevg/cloud-ping
abd3a9fc87d17f007589c66117f8ac7c497b3106
0051e15269d892f587a0dfc4274bc3bf80fe80eb
refs/heads/master
2021-01-01T17:16:39.523739
2013-11-22T19:27:55
2014-02-15T21:11:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
283
h
#ifndef _S3_CONN_H_ #define _S3_CONN_H_ #include "cloud_conn.h" class S3Connection : public CloudConnection { public: S3Connection(const string &url, const string &auth): CloudConnection(url, auth) {} virtual void PerformGet(Statistics *stat); }; #endif /* _S3_CONN_H_ */
[ "budevg@gmail.com" ]
budevg@gmail.com
49a1556bb4821acdcfe956f126638617cc6672db
9da824479d2f4189c9ddb3aa774959c65a90b222
/src/test.cpp
b6df90ee537801e9edbe35249a79e218ddbac0a7
[]
no_license
DedaleTSP/ddale_ardrone_nav
e6d5a415bde74ecaa9bec32e61a8207e04880ef7
be93d3d5ce7232555053f40ad5f76e18af802724
refs/heads/master
2016-09-13T18:50:17.641023
2016-06-08T08:52:50
2016-06-08T08:52:50
58,629,168
0
0
null
null
null
null
UTF-8
C++
false
false
2,325
cpp
#include "ros/ros.h" #include "std_msgs/Empty.h" #include "geometry_msgs/Twist.h" #include <geometry_msgs/Vector3.h> #include <ardrone_autonomy/Navdata.h> #include <boost/thread.hpp> #include <boost/chrono.hpp> #include <boost/lexical_cast.hpp> #include <sstream> #include <string> #include <iostream> using namespace std; std::string FloatToString(float n) { //std::string s = boost::lexical_cast<std::string>(n); std::ostringstream ss; ss << n; return (ss.str()); } void Sleepfor(int ms) { boost::this_thread::sleep_for(boost::chrono::milliseconds(ms)); } void chatterCallback(const ardrone_autonomy::Navdata::ConstPtr msg) { ardrone_autonomy::Navdata lastMsg = *msg; float x, y, z; x = lastMsg.rotX; y = lastMsg.rotY; z = lastMsg.rotZ; ROS_INFO("I heard: [%f,%f,%f]",x,y,z); //ROS_INFO("I heard: [%s]", FloatToString(msg->rotZ).c_str()); //std::string X, Y, Z; //X = FloatToString(x); //Y = FloatToString(y); //Z = FloatToString(z); //ROS_INFO("I heard: [%s,%s,%s] , [%f,%f,%f]", X.c_str(), Y.c_str(), Z.c_str(),x,y,z); } int main(int argc, char **argv) { ros::init(argc, argv, "testdrone"); ros::NodeHandle n; ros::Subscriber nav_sub = n.subscribe("/ardrone/navdata", 1,chatterCallback); ros::Publisher takeoff_pub = n.advertise<std_msgs::Empty>(n.resolveName("ardrone/takeoff"),1,true); ros::Publisher land_pub = n.advertise<std_msgs::Empty>(n.resolveName("ardrone/land"),1,true); std_msgs::Empty emp_msg; ros::Publisher twist_pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 1); geometry_msgs::Twist twist_msg; takeoff_pub.publish(emp_msg); ros::Duration(3).sleep(); ros::spinOnce(); ROS_INFO("##mycontroller:z=1"); twist_msg.angular.z=1; twist_pub.publish(twist_msg); ros::Duration(2).sleep(); ros::spinOnce(); ROS_INFO("##mycontroller:z=0"); twist_msg.angular.z=0; twist_pub.publish(twist_msg); ros::Duration(2).sleep(); ros::spinOnce(); ROS_INFO("##mycontroller:z=-1"); twist_msg.angular.z=-1; twist_pub.publish(twist_msg); ros::Duration(2).sleep(); ros::spinOnce(); ROS_INFO("##mycontroller:z=0"); twist_msg.angular.z=0; twist_pub.publish(twist_msg); ros::Duration(2).sleep(); ros::Duration(2).sleep(); land_pub.publish(emp_msg); ros::Duration(2).sleep(); return 0; }
[ "anatole.lefort@gmail.com" ]
anatole.lefort@gmail.com
187dbc1fc843086078bfecbe2fc44c15a4fbf6f8
6149561f6b2c00335e8d9d09a1aeffad49e59422
/studyC++/依赖倒置原则.cpp
74676fe8dcab9d44d77a6e3f34a834fa39c1dfbc
[]
no_license
Smartuil/Study-CPP
3196405f107de0762c2900d0dac89917b2183902
f646eab0a11c1fc8750fe608ce9c8f2360f3cf34
refs/heads/master
2022-11-29T02:28:10.759993
2020-07-29T07:05:11
2020-07-29T07:05:11
259,013,860
0
0
null
null
null
null
GB18030
C++
false
false
1,200
cpp
#include<iostream> using namespace std; //让电脑框架和具体厂商进行接耦合 class HardDisk { public: virtual void work()=0; }; class Memory { public: virtual void work()=0; }; class Cpu { public: virtual void work()=0; }; class Computer { public: //HardDisk //Memory //Memory Computer(HardDisk *harddisk, Memory *memory, Cpu *cpu) { m_harddisk = harddisk; m_memory = memory; m_cpu = cpu; } public: void work() { m_harddisk->work(); m_memory->work(); m_cpu->work(); } private: HardDisk *m_harddisk; Memory *m_memory; Cpu *m_cpu; }; class InterCpu :public Cpu{ public: void work() { cout << "我是因特尔" << endl; } }; class XSHardDisk :public HardDisk { public: void work() { cout << "我是三星" << endl; } }; class JSDMemory :public Memory { public: void work() { cout << "我是金士顿" << endl; } }; void main2() { HardDisk *harddisk = NULL; Memory *memory = NULL; Cpu *cpu = NULL; harddisk = new XSHardDisk; memory = new JSDMemory; cpu = new InterCpu; Computer *mycomputer = new Computer(harddisk, memory, cpu); mycomputer->work(); delete mycomputer; delete cpu; delete memory; delete harddisk; system("pause"); }
[ "563412673@qq.com" ]
563412673@qq.com
a7174113df50955c3a9bc7b3328e18be358715b8
83463dfbd412e5558923a46499ebf4bc26b59f09
/LESSON2018 1/CW/task2.cpp
ac1569edefc1fa61d1a605cbd3fd491359fad99a
[]
no_license
Azhitlukhina96/CCourse
f3b319c4472b65d4c509a89cb3bc25c4da9a1c32
1290b25f8bb54bac8cfb649ad3de0986f264d198
refs/heads/master
2021-09-15T04:39:27.473589
2018-05-26T08:09:41
2018-05-26T08:09:41
104,557,457
0
0
null
null
null
null
UTF-8
C++
false
false
2,636
cpp
// ConsoleApplication2.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> #define SIZE 100 #define BUFFER_SIZE 1024 int max_products(int prices[], int size) { int max_price = 0; for (int i = 0; i < size; i++) { if (prices[i] > max_price) { max_price = prices[i]; } } return max_price; } int min_products(int prices[], int size) { int min_price = 1000; for (int i = 0; i < size; i++) { if (prices[i] < min_price) { min_price = prices[i]; } } return min_price; } //поиск транзакций с тем товаром, название которого ввёл пользователь программы void search(char descriptions[1000][100], int size) { int transaction_id = 0; char description[BUFFER_SIZE]; char *sub_string = NULL; int counter = 0; scanf_s("%s", description, BUFFER_SIZE); for (int i = 0; i < size; i++) { sub_string = strstr(descriptions[i], description); if (sub_string != NULL) { printf("transaction_id: %d\n", i); printf("description: %s\n", descriptions[i]); } counter++; } } struct all_transactions { int transaction_id; int price; char description[100]; // для упрощения, чтобы не вызывать функцию malloc }; int main() { FILE *all_transactions_file; struct all_transactions all_transaction_buffer; all_transaction_buffer.transaction_id = 0; all_transaction_buffer.price = 0; char buffer[BUFFER_SIZE]; // Это массив для чтения строк errno_t err = fopen_s(&all_transactions_file, "C:\\Users\\uc2\\Desktop\\files\\all_transactions.txt", "r"); int position = 0; int all_prices[1000]; char descriptions[1000][100]; if (err) printf_s("The file all_transactions.txt was not opened\n"); else { while (fgets(buffer, BUFFER_SIZE, all_transactions_file) != NULL) { printf("%s", buffer); int count_separator = 0; int price = 0; for (int i = 0; i < strlen(buffer); i++) { if (buffer[i] == ';') { printf_s("Position: %d\n", i); count_separator++; } if (count_separator == 1 && buffer[i] != ';') { price = price * 10 + (buffer[i] - 48); } } } } fclose(all_transactions_file); //определение времени поиска транзакций с наибольшим и наименьшим числим товаров //«структурa» для хранения информации о транзакции //10% самых дорогих покупок return 0; }
[ "noreply@github.com" ]
noreply@github.com
5d823d716712eb5c9a30f0fcb2ac3cd6048d05e2
9425363a4973ae8416f4c8f17d696de3efdc111b
/VX_Window_Lib/OpenGLRuntimeError.cpp
0c682c2ce8afef9e87fadf8936bce64f668a146d
[]
no_license
vexta/App
eae85429f48632ac791e810db4a2d0d471439780
c674cb86b56b3f0feb0151ff033ba6db8bbb101d
refs/heads/master
2021-01-21T04:59:29.614718
2016-06-07T12:00:55
2016-06-07T12:00:55
52,599,646
0
0
null
null
null
null
UTF-8
C++
false
false
346
cpp
#include "OpenGLRuntimeError.h" vx_opengl_namespace_::OpenGLRuntimeError::OpenGLRuntimeError(const char * message) : std::runtime_error(message) { } vx_opengl_namespace_::OpenGLRuntimeError::OpenGLRuntimeError(const std::string & message) : std::runtime_error(message) { } vx_opengl_namespace_::OpenGLRuntimeError::~OpenGLRuntimeError() { }
[ "lenka.kutlikova@gmail.com" ]
lenka.kutlikova@gmail.com
0fed383a4a3b8b09a78c9996c509d5e415d1a855
6e6e06f07ebeeb9cbb0ed08a1524dbba64d21980
/src/DOA_acoustic_source_localization.cpp
dc1e12d69338e274efb468fbd05f009fdb9616f9
[]
no_license
SiChiTong/DOA_acoustic_source_localization
dc1d9c282aa30ca6686a5a7be5998f271aef4826
62421c1c1d64d3ba1cd94111d56481e096c94c8e
refs/heads/master
2021-05-03T22:01:47.438878
2015-06-30T09:45:51
2015-06-30T09:45:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,604
cpp
/* * Copyright (c) 2015, Riccardo Levorato <riccardo.levorato@dei.unipd.it> * * 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(s) 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 <COPYRIGHT HOLDER> 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. */ #include <ros/ros.h> #include <ros/package.h> #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> #include <visualization_msgs/Marker.h> #include "tf_conversions/tf_eigen.h" #include <Eigen/Dense> #include <Eigen/Geometry> #include <Eigen/StdVector> #include <eigen_conversions/eigen_msg.h> #include <hark_msgs/HarkSource.h> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <math.h> #include <limits> using namespace Eigen; using namespace std; // Association of the number of the hw audio: For now it is progressive and it depends by the order of the usb-plugin of the kinect. So for now plug in first kinect 1, after kinect 2, etc.. //TODO insert weights for gaussian //TODO insert gaussian formula vector<vector<hark_msgs::HarkSourceVal> > DOAs_hark; vector<Eigen::Affine3d, Eigen::aligned_allocator<Eigen::Affine3d> > sensors_3D_pose; double get_absolute_DOA(Eigen::Affine3d sensor_3D_pose, vector<hark_msgs::HarkSourceVal> DOA_hark) { double relative_DOA = 0, max_power = -1; int num_sources_detected = DOA_hark.size(); for (int i = 0; i < num_sources_detected; i++) { if (DOA_hark[i].power > max_power) // use the DOA detection with higher power { max_power = DOA_hark[i].power; relative_DOA = (DOA_hark[i].azimuth / 180.0) * M_PI; // hark returns angles in degrees } } double sensor_yaw = atan2(sensor_3D_pose.rotation().matrix()(1,0), sensor_3D_pose.rotation().matrix()(0,0)); return relative_DOA + sensor_yaw; } void harkCallback(const hark_msgs::HarkSource::ConstPtr & msg, int i) { DOAs_hark[i] = msg->src; /*ROS_INFO("DOAs_hark from sensor: %d", msg->exist_src_num); for (unsigned j = 0; j < DOAs_hark[i].size(); j++) { ROS_INFO("\t%d DOAs_hark from sensor: %d - azimuth: %f, power: %f", i, DOAs_hark[i][j].azimuth/180.0 * M_PI, DOAs_hark[i][j].power); }*/ } Eigen::Vector3d locate_WLS_2D(vector<bool> detected_DOA) { int n_sources = 0; for (unsigned int i = 0; i < detected_DOA.size(); i++) { if (detected_DOA[i]) { n_sources++; } } int dim = 2; // TODO insert the possibility to set different weights MatrixXd w = MatrixXd::Ones(n_sources, 1); MatrixXd W = MatrixXd::Identity(n_sources, n_sources); MatrixXd K = MatrixXd::Zero(2, n_sources); for (unsigned int k = 0; k < detected_DOA.size(); k++) { if (detected_DOA[k]) { double relative_DOA = get_absolute_DOA(sensors_3D_pose[k], DOAs_hark[k]); K.col(k) << cos(relative_DOA), sin(relative_DOA); } } MatrixXd I = MatrixXd::Identity(dim, dim); MatrixXd A = MatrixXd::Zero(dim, n_sources); for (int i = 0; i < n_sources; i++) { A.col(i) = (I - K.col(i) * K.col(i).adjoint()) * sensors_3D_pose[i].translation().head(2); } Eigen::Vector2d solution_2D = (w.sum() * I - K * K.adjoint()).lu().solve(A * w); Eigen::Vector3d solution_3D; solution_3D << solution_2D, 0; return solution_3D; } double evaluate_angle_from_2D_grid(double x, double y) { double value = 0; for (unsigned int i = 0; i < sensors_3D_pose.size(); i++) { double absolute_DOA = get_absolute_DOA(sensors_3D_pose[i], DOAs_hark[i]); double angle_point2sensor = atan2(y - sensors_3D_pose[i].translation()(1), x - sensors_3D_pose[i].translation()(0)); double angle = angle_point2sensor - absolute_DOA; double range = M_PI; while (angle > range) { angle = angle - 2*M_PI; } while (angle < -range) { angle = angle + 2*M_PI; } value += angle * angle; } return value; } Eigen::Vector3d locate_min_angle_2D_slow(double start_x, double start_y, double range, double precision_grid) { double x_sol = 0, y_sol = 0; double min_val = std::numeric_limits<double>::max(); for (double x = start_x - range/2; x <= start_x + range/2; x += precision_grid) { for (double y = start_y - range/2; y <= start_y + range/2; y += precision_grid) { double tmp_val = evaluate_angle_from_2D_grid(x, y); if (tmp_val < min_val) { min_val = tmp_val; x_sol = x; y_sol = y; } } } Eigen::Vector3d solution; solution << x_sol, y_sol, 0; return solution; } void set_max_rec(int n_coordinate, double x_tmp_value, Eigen::Vector3d value_indexes, double *max_value, Eigen::Vector3d *max_value_indexes, int *x_max_index) { if (x_tmp_value > *max_value) { *max_value = x_tmp_value; *max_value_indexes = value_indexes; *x_max_index = value_indexes[n_coordinate]; } if (x_tmp_value == *max_value && value_indexes[n_coordinate] < *x_max_index) { *x_max_index = value_indexes[n_coordinate]; } } Eigen::Vector3d locate_min_angle_2D_fast_rec(int num_var, int n_max_coordinates, Eigen::Vector3d previous_indexes, double start_x, double start_y, double *max_value, double range, double precision_grid) { Eigen::Vector3d max_value_indexes = previous_indexes; int n_points = range/precision_grid; int levels = ceil(log2(n_points)); if (n_max_coordinates == 0) { double i = start_x + (- pow(2, levels-1) + previous_indexes[0]) * precision_grid; double j = start_y + (- pow(2, levels-1) + previous_indexes[1]) * precision_grid; *max_value = - evaluate_angle_from_2D_grid(i, j); } else { *max_value = -std::numeric_limits<double>::max(); int x_tmp_index = pow(2, levels-1); int x_max_index = std::numeric_limits<int>::max(); int l = (levels-1); while (l >= 0) { previous_indexes[num_var - n_max_coordinates] = x_tmp_index; // update value of pivot index double x_tmp_value; Eigen::Vector3d value_indexes = locate_min_angle_2D_fast_rec(num_var, n_max_coordinates - 1, previous_indexes, start_x, start_y, &x_tmp_value, range, precision_grid); // update max value set_max_rec(num_var - n_max_coordinates, x_tmp_value, value_indexes, max_value, &max_value_indexes, &x_max_index); if (l > 0) { if (l < levels -1 && x_tmp_value < *max_value)// jump immedialtely if the tmp_value is less than the maximum value. If equal (--^--) continue the research of a different value. { if (x_tmp_index < max_value_indexes[num_var - n_max_coordinates]) { x_tmp_index = x_tmp_index + pow(2, l-1); } else { x_tmp_index = x_tmp_index - pow(2, l-1); } } else { // update value and index of back pivot double x_tmp_back_value = x_tmp_value; double x_tmp_back_index = x_tmp_index; while (((x_tmp_index - x_tmp_back_index) < pow(2, l)-1) && (x_tmp_back_value == x_tmp_value)) { x_tmp_back_index = x_tmp_back_index-1; previous_indexes[num_var - n_max_coordinates] = x_tmp_back_index; value_indexes = locate_min_angle_2D_fast_rec(num_var, n_max_coordinates - 1, previous_indexes, start_x, start_y, &x_tmp_back_value, range, precision_grid); } // update max value set_max_rec(num_var - n_max_coordinates, x_tmp_back_value, value_indexes, max_value, &max_value_indexes, &x_max_index); // jump if (x_tmp_back_value > x_tmp_value)// if back value is higher, jump back { x_tmp_index = x_tmp_index - pow(2, l-1); while (x_tmp_index > x_tmp_back_index) { l = l - 1; x_tmp_index = x_tmp_index - pow(2, l-1); } }else// if back value is less or equal (after having arrived to the previous level), jump next { if (x_tmp_index == pow(2, levels) - 1)// look forward to reach 2^(levels) element { x_tmp_index = x_tmp_index+1; previous_indexes[num_var - n_max_coordinates] = x_tmp_index; Eigen::Vector3d value_indexes = locate_min_angle_2D_fast_rec(num_var, n_max_coordinates - 1, previous_indexes, start_x, start_y, &x_tmp_value, range, precision_grid); // update max value set_max_rec(num_var - n_max_coordinates, x_tmp_value, value_indexes, max_value, &max_value_indexes, &x_max_index); }else { x_tmp_index = x_tmp_index + pow(2, l-1); } } } } l = l - 1; } max_value_indexes[num_var - n_max_coordinates] = x_max_index; } return max_value_indexes; } Eigen::Vector3d locate_min_angle_2D_fast(double start_x, double start_y, double range, double precision_grid) { double max_value; Eigen::Vector3d previous_indexes; previous_indexes << 0, 0, 0; Eigen::Vector3d solution = locate_min_angle_2D_fast_rec(2, 2, previous_indexes, start_x, start_y, &max_value, range, precision_grid); int n_points = range/precision_grid; int levels = ceil(log2(n_points)); solution[0] = start_x + (- pow(2,levels-1) + solution[0]) * precision_grid; solution[1] = start_y + (- pow(2,levels-1) + solution[1]) * precision_grid; solution[2] = 0; return solution; } void update_sensors_pose(string tf_world_name, vector<string> sensors_3D_pose_topics){ tf::TransformListener listener; for (unsigned int i = 0; i < sensors_3D_pose.size(); i++) { bool found = false; tf::StampedTransform tmp_transform; while (!found) { try { ros::Time now = ros::Time(0); listener.waitForTransform(tf_world_name, sensors_3D_pose_topics[i], now, ros::Duration(0.5)); listener.lookupTransform(tf_world_name, sensors_3D_pose_topics[i], ros::Time(0), tmp_transform); found = true; } catch (tf::TransformException ex) { ROS_ERROR("%s", ex.what()); } } Eigen::Affine3d tmp_eigen_transform; tf::transformTFToEigen(tmp_transform, tmp_eigen_transform); sensors_3D_pose[i] = tmp_eigen_transform; } } int main(int argc, char **argv) { ros::init(argc, argv, "DOA_acoustic_source_localization"); ros::NodeHandle nh; ros::NodeHandle input_nh("~"); ros::Rate lr(10); bool is_simulation; input_nh.getParam("is_simulation", is_simulation); cout << "is_simulation: " << is_simulation << endl; string data_simulation_file_path; input_nh.getParam("data_simulation_file_path", data_simulation_file_path); if (is_simulation){ cout << "data_simulation_file_path: " << data_simulation_file_path << endl; } int n_acoustic_DOA_sensors; input_nh.getParam("n_acoustic_DOA_sensors", n_acoustic_DOA_sensors); cout << "n_acoustic_DOA_sensors: " << n_acoustic_DOA_sensors << endl; double audio_signal_power_threshold = 0; input_nh.getParam("audio_signal_power_threshold", audio_signal_power_threshold); cout << "audio_signal_power_threshold: " << audio_signal_power_threshold << endl; int algorithm_type; input_nh.getParam("algorithm_type", algorithm_type); cout << "algorithm_type: " << algorithm_type << endl; double range = 10; input_nh.getParam("range", range); cout << "range: " << range << endl; double precision_grid = 0.01; input_nh.getParam("precision_grid", precision_grid); cout << "precision_grid: " << precision_grid << endl; string tf_world_name; input_nh.getParam("tf_world_name", tf_world_name); cout << "tf_world_name: " << tf_world_name << endl; string tf_solution_name; input_nh.getParam("tf_solution_name", tf_solution_name); cout << "tf_solution_name: " << tf_solution_name << endl; double rviz_DOA_line_lenght = 20; input_nh.getParam("rviz_DOA_line_lenght", rviz_DOA_line_lenght); cout << "rviz_DOA_line_lenght: " << rviz_DOA_line_lenght << endl; DOAs_hark.resize(n_acoustic_DOA_sensors); sensors_3D_pose.resize(n_acoustic_DOA_sensors); vector<string> sensors_3D_pose_topics(n_acoustic_DOA_sensors); vector<string> DOA_topics(n_acoustic_DOA_sensors); vector<ros::Subscriber> sub(n_acoustic_DOA_sensors); int start_numbering_labels = 1; for (int i = 0; i < n_acoustic_DOA_sensors; i++) { std::ostringstream oss; oss << i + start_numbering_labels; input_nh.getParam("sensor_3D_pose_topic_" + oss.str(), sensors_3D_pose_topics[i]); input_nh.getParam("DOA_topic_" + oss.str(), DOA_topics[i]); if (!is_simulation) { sub[i] = nh.subscribe<hark_msgs::HarkSource>(DOA_topics[i], 100, boost::bind(harkCallback, _1, i)); } } ros::Publisher visualization_marker_pub = nh.advertise<visualization_msgs::Marker>( "visualization_marker", 10); while (ros::ok()) { ros::spinOnce(); // Points visualization visualization_msgs::Marker solution_points, line_strip; solution_points.header.frame_id = line_strip.header.frame_id = tf_world_name; solution_points.header.stamp = line_strip.header.stamp = ros::Time(0); line_strip.ns = "points_and_lines"; solution_points.ns = "solutions"; solution_points.action = line_strip.action = visualization_msgs::Marker::ADD; solution_points.pose.orientation.w = line_strip.pose.orientation.w = 1.0; solution_points.id = 0; solution_points.type = visualization_msgs::Marker::POINTS; // Points markers use x and y scale for width/height respectively solution_points.scale.x = 0.05; solution_points.scale.y = 0.05; // Solution points are red solution_points.color.r = 1.0f; solution_points.color.a = 1.0; line_strip.id = 1; line_strip.type = visualization_msgs::Marker::LINE_LIST; // Line_strip markers use only the x component of scale, for the line width line_strip.scale.x = 0.01; line_strip.scale.y = 0.01; // Line strip is blue line_strip.color.b = 1.0; line_strip.color.a = 1.0; if (is_simulation) { audio_signal_power_threshold = -1; std::ifstream infile(data_simulation_file_path.c_str()); std::string line; vector<double> simulation_angles; while (std::getline(infile, line)) { std::istringstream iss(line); double a; if (!(iss >> a)){break; } // error simulation_angles.push_back(a); // cout << "angle: " << a << endl; } // cout << endl; DOAs_hark.clear(); for (int i = 0; i < n_acoustic_DOA_sensors; i++) { vector<hark_msgs::HarkSourceVal> vec; hark_msgs::HarkSourceVal tmp_hark; tmp_hark.azimuth = simulation_angles[i]; vec.push_back(tmp_hark); DOAs_hark.push_back(vec); } } update_sensors_pose(tf_world_name, sensors_3D_pose_topics); // Plotting lines for (int k = 0; k < n_acoustic_DOA_sensors; k++) { double absolute_DOA = get_absolute_DOA(sensors_3D_pose[k], DOAs_hark[k]); Vector3d prt = sensors_3D_pose[k].translation(); Vector3d p1, p2; p1 << prt[0] + rviz_DOA_line_lenght * cos(absolute_DOA), prt[1] + rviz_DOA_line_lenght * sin(absolute_DOA), 0; p2 << prt; geometry_msgs::Point gp1, gp2; tf::pointEigenToMsg(p1, gp1); tf::pointEigenToMsg(p2, gp2); line_strip.points.push_back(gp1); line_strip.points.push_back(gp2); } vector<bool> detected_DOA(n_acoustic_DOA_sensors); // Control if there is at least one acoustic detected in each DOA sensor int n_detected = 0; for (int i = 0; i < n_acoustic_DOA_sensors; i++) { int num_sources_detected = DOAs_hark[i].size(); detected_DOA[i] = false; if (num_sources_detected > 0){ int j = 0; bool detected = false; while (!detected && j < num_sources_detected) { if (DOAs_hark[i][j].power > audio_signal_power_threshold) { detected = true; n_detected++; } j++; } if (detected) { detected_DOA[i] = true; } } } Eigen::Vector3d solution, WLS_solution; geometry_msgs::Point gp; if (n_detected >= 2) { WLS_solution = locate_WLS_2D(detected_DOA); if (n_detected == 2) { solution = WLS_solution; } } if (n_detected >= 3) { switch (algorithm_type) { case 1: solution = locate_min_angle_2D_fast(WLS_solution[0], WLS_solution[1], range, precision_grid); break; case 2: solution = locate_min_angle_2D_slow(WLS_solution[0], WLS_solution[1], range, precision_grid); break; case 3: solution = WLS_solution; break; } } // Publish TF_solution tf::Transform transform; transform.setOrigin( tf::Vector3(solution(0), solution(1), 0.0) ); tf::Quaternion q; q.setRPY(0, 0, 0); transform.setRotation(q); static tf::TransformBroadcaster br; br.sendTransform(tf::StampedTransform(transform, ros::Time(0),tf_world_name, tf_solution_name)); // Visualize solution tf::pointEigenToMsg(solution, gp); solution_points.points.push_back(gp); visualization_marker_pub.publish(solution_points); visualization_marker_pub.publish(line_strip); lr.sleep(); } }
[ "riccardo@riccardo-pc.(none)" ]
riccardo@riccardo-pc.(none)
62f23534d2c3c4fc3f74f2737c9cb0edf847f406
9f96206c9b2af71256e43624a250d300c3f5ab6a
/samples/browser/src/MeshPrimitiveSample.cpp
c77a2a1d09765b911ca5700ddb7f5e0a4c4a8bb4
[]
no_license
playbar/VkCore
2ead714b7e45205cf973e124bd542f4f6c275814
0cb393a6b6f12e2864ba93fdae2ed9f2808c6d75
refs/heads/master
2021-06-08T20:31:19.535405
2017-01-03T07:07:55
2017-01-03T07:07:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,965
cpp
#include "MeshPrimitiveSample.h" #include "SamplesGame.h" #if defined(ADD_SAMPLE) ADD_SAMPLE("Graphics", "Mesh Primitives", MeshPrimitiveSample, 2); #endif /** * Creates a triangle mesh with vertex colors. */ static Mesh* createTriangleMesh() { // Calculate the vertices of the equilateral triangle. float a = 0.25f; // Length of side Vector2 p1(0.0f, a / sqrtf(3.0f)); Vector2 p2(-a / 2.0f, -a / (2.0f * sqrtf(3.0f))); Vector2 p3( a / 2.0f, -a / (2.0f * sqrtf(3.0f))); // Create 3 vertices. Each vertex has position (x, y, z) and color (red, green, blue) float vertices[] = { p1.x, p1.y, 0.0f, 1.0f, 0.0f, 0.0f, p2.x, p2.y, 0.0f, 0.0f, 1.0f, 0.0f, p3.x, p3.y, 0.0f, 0.0f, 0.0f, 1.0f, }; unsigned int vertexCount = 3; VertexFormat::Element elements[] = { VertexFormat::Element(VertexFormat::POSITION, 3), VertexFormat::Element(VertexFormat::COLOR, 3) }; Mesh* mesh = Mesh::createMesh(VertexFormat(elements, 2), vertexCount, false); if (mesh == NULL) { GP_ERROR("Failed to create mesh."); return NULL; } mesh->setPrimitiveType(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); mesh->setVertexData(vertices, 0, vertexCount); return mesh; } static Mesh* createTriangleStripMesh() { float scale = 0.02f; unsigned int vertexCount = 20; std::vector<float> vertices; vertices.reserve(vertexCount * 6); float x = -0.2f; float y = -0.05f; float step = fabs(x) * 2.0f / (float)vertexCount; for (unsigned int i = 0; i < vertexCount; ++i) { // x, y, z, r, g, b vertices.push_back(x); vertices.push_back(y + MATH_RANDOM_MINUS1_1() * scale); vertices.push_back(MATH_RANDOM_MINUS1_1() * scale * 2); vertices.push_back(MATH_RANDOM_0_1()); vertices.push_back(MATH_RANDOM_0_1()); vertices.push_back(MATH_RANDOM_0_1()); x += step; y *= -1.0f; } VertexFormat::Element elements[] = { VertexFormat::Element(VertexFormat::POSITION, 3), VertexFormat::Element(VertexFormat::COLOR, 3) }; Mesh* mesh = Mesh::createMesh(VertexFormat(elements, 2), vertexCount, false); if (mesh == NULL) { GP_ERROR("Failed to create mesh."); return NULL; } mesh->setPrimitiveType(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP); // mesh->setVertexData(&vertices[0], 0, vertexCount); return mesh; } static Mesh* createLineStripMesh() { float a = 0.1f; float vertices[] = { 0, 0, 0, 1, 0, 0, a, 0, -a, 0, 1, 0, 0, -a, a, 0, 0, 1, -a, 0, -a, 1, 0, 1, 0, a, a, 0, 1, 1, }; unsigned int vertexCount = 5; VertexFormat::Element elements[] = { VertexFormat::Element(VertexFormat::POSITION, 3), VertexFormat::Element(VertexFormat::COLOR, 3) }; Mesh* mesh = Mesh::createMesh(VertexFormat(elements, 2), vertexCount, false); if (mesh == NULL) { GP_ERROR("Failed to create mesh."); return NULL; } mesh->setPrimitiveType(VK_PRIMITIVE_TOPOLOGY_LINE_STRIP); mesh->setVertexData(vertices, 0, vertexCount); return mesh; } static Mesh* createLinesMesh() { float scale = 0.2f; unsigned int vertexCount = 40; std::vector<float> vertices; vertices.reserve(vertexCount * 6); for (unsigned int i = 0; i < vertexCount; ++i) { // x, y, z, r, g, b vertices.push_back(MATH_RANDOM_MINUS1_1() * scale); vertices.push_back(MATH_RANDOM_MINUS1_1() * scale); vertices.push_back(MATH_RANDOM_MINUS1_1() * scale); vertices.push_back(MATH_RANDOM_0_1()); vertices.push_back(MATH_RANDOM_0_1()); vertices.push_back(MATH_RANDOM_0_1()); } VertexFormat::Element elements[] = { VertexFormat::Element(VertexFormat::POSITION, 3), VertexFormat::Element(VertexFormat::COLOR, 3) }; Mesh* mesh = Mesh::createMesh(VertexFormat(elements, 2), vertexCount, false); if (mesh == NULL) { GP_ERROR("Failed to create mesh."); return NULL; } mesh->setPrimitiveType(VK_PRIMITIVE_TOPOLOGY_LINE_LIST); // mesh->setVertexData(&vertices[0], 0, vertexCount); return mesh; } MeshPrimitiveSample::MeshPrimitiveSample() : _font(NULL), _triangles(NULL), _triangleStrip(NULL), _lineStrip(NULL), _lines(NULL), _points(NULL) { } void MeshPrimitiveSample::initialize() { // Create the font for drawing the framerate. _font = Font::create("res/ui/arial.gpb"); // Create an orthographic projection matrix. float width = getWidth() / (float)getHeight(); float height = 1.0f; Matrix::createOrthographic(width, height, -1.0f, 1.0f, &_viewProjectionMatrix); // Create a model for the triangle mesh. A model is an instance of a Mesh that can be drawn with a specified material. Mesh* triangleMesh = createTriangleMesh(); _triangles = Model::create(triangleMesh); SAFE_RELEASE(triangleMesh); // Create a material from the built-in "colored-unlit" vertex and fragment shaders. // This sample doesn't use lighting so the unlit shader is used. // This sample uses vertex color so VERTEX_COLOR is defined. Look at the shader source files to see the supported defines. _triangles->setMaterial("res/shaders/colored.vert", "res/shaders/colored.frag", "VERTEX_COLOR"); Mesh* triangleStripMesh = createTriangleStripMesh(); _triangleStrip = Model::create(triangleStripMesh); SAFE_RELEASE(triangleStripMesh); Material* material = _triangleStrip->setMaterial("res/shaders/colored.vert", "res/shaders/colored.frag", "VERTEX_COLOR"); material->getStateBlock()->setDepthTest(true); material->getStateBlock()->setDepthWrite(true); Mesh* lineStripMesh = createLineStripMesh(); _lineStrip = Model::create(lineStripMesh); SAFE_RELEASE(lineStripMesh); _lineStrip->setMaterial("res/shaders/colored.vert", "res/shaders/colored.frag", "VERTEX_COLOR"); Mesh* lineMesh = createLinesMesh(); _lines = Model::create(lineMesh); SAFE_RELEASE(lineMesh); _lines->setMaterial("res/shaders/colored.vert", "res/shaders/colored.frag", "VERTEX_COLOR"); } void MeshPrimitiveSample::finalize() { // Model and font are reference counted and should be released before closing this sample. SAFE_RELEASE(_triangles); SAFE_RELEASE(_triangleStrip); SAFE_RELEASE(_lineStrip); SAFE_RELEASE(_lines); SAFE_RELEASE(_points); SAFE_RELEASE(_font); } void MeshPrimitiveSample::update(float elapsedTime) { if (_touchPoint.x == -1.0f && _touchPoint.y == -1.0f) { _tilt.x *= powf(0.99f, elapsedTime); _tilt.y *= powf(0.99f, elapsedTime); } } void MeshPrimitiveSample::render(float elapsedTime) { // Clear the color and depth buffers clear(CLEAR_COLOR_DEPTH, Vector4::zero(), 1.0f, 0); Matrix wvp; wvp.rotateY(_tilt.x * 0.01f); wvp.rotateX(_tilt.y * 0.01f); Matrix::multiply(wvp, _viewProjectionMatrix, &wvp); Matrix m; float offset = 0.5f; // Bind the view projection matrix to the model's paramter. This will transform the vertices when the model is drawn. m.setIdentity(); m.translate(-offset, offset, 0); Matrix::multiply(m, wvp, &m); _triangles->getMaterial()->getParameter("u_worldViewProjectionMatrix")->setValue(m); _triangles->draw(); m.setIdentity(); m.translate(0, offset, 0); Matrix::multiply(m, wvp, &m); _triangleStrip->getMaterial()->getParameter("u_worldViewProjectionMatrix")->setValue(m); _triangleStrip->draw(); m.setIdentity(); m.translate(-offset, -offset, 0); Matrix::multiply(m, wvp, &m); _lineStrip->getMaterial()->getParameter("u_worldViewProjectionMatrix")->setValue(m); _lineStrip->draw(); m.setIdentity(); m.translate(0, -offset, 0); Matrix::multiply(m, wvp, &m); _lines->getMaterial()->getParameter("u_worldViewProjectionMatrix")->setValue(m); _lines->draw(); drawFrameRate(_font, Vector4(0, 0.5f, 1, 1), 5, 1, getFrameRate()); } void MeshPrimitiveSample::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex) { switch (evt) { case Touch::TOUCH_PRESS: if (x < 75 && y < 50) { // Toggle Vsync if the user touches the top left corner setVsync(!isVsync()); } else { _touchPoint.set(x, y); } break; case Touch::TOUCH_RELEASE: _touchPoint.set(-1.0f, -1.0f); break; case Touch::TOUCH_MOVE: if (_touchPoint.x > 0.0f && _touchPoint.y > 0.0f) { float deltaX = x - _touchPoint.x; float deltaY = y - _touchPoint.y; _tilt.x -= deltaX; _tilt.y += deltaY; _touchPoint.set(x, y); } break; }; }
[ "hgl868@126.com" ]
hgl868@126.com
8cad2dbc7fa6efbb507c5d55a1c11a2bad0f67ac
c67ed12eae84af574406e453106b7d898ff47dc7
/chap19/Exer19_17.cpp
fa970740016c375403e0b02e98fa27e18410b0a0
[ "Apache-2.0" ]
permissive
chihyang/CPP_Primer
8374396b58ea0e1b0f4c4adaf093a7c0116a6901
9e268d46e9582d60d1e9c3d8d2a41c1e7b83293b
refs/heads/master
2022-09-16T08:54:59.465691
2022-09-03T17:25:59
2022-09-03T17:25:59
43,039,810
58
23
Apache-2.0
2023-01-14T07:06:19
2015-09-24T02:25:47
C++
UTF-8
C++
false
false
482
cpp
#include <iostream> #include "Exer19_17_Screen.h" using std::cout; using std::endl; int main() { Screen::Action1 get1 = &Screen::get; Screen::Action2 get2 = &Screen::get; Screen::Action3 mv = &Screen::move; Screen myScreen(20, 30, 'o'), *pScreen = &myScreen; cout << (myScreen.*get1)() << endl; // call get() cout << (pScreen->*get2)(0, 0) << endl; // call get(pos, pos) (myScreen.*mv)(0, 0); // call move(pos, pos) return 0; }
[ "chihyanghsin@gmail.com" ]
chihyanghsin@gmail.com
3b718c85499a1c7fe85509ac65a9f39a65afed7e
f998f715a2212ceb4c4b63373a35efe4a4180c68
/Codeforces/EC42/B.cpp
76c79633620b0ee3ca04616ecc112245053cb6d4
[]
no_license
its-mash/Competitive-Programming
3e0e85c2d954a0d00192cfb8b7a3943d11d9e00d
1a5148f154afdf073044cd1027b17a5c4f6ba4d0
refs/heads/master
2022-12-18T20:43:54.861791
2020-09-20T01:00:44
2020-09-20T01:00:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
737
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int main(){ #ifndef ONLINE_JUDGE freopen("in","r",stdin); #endif int n,a,b; cin>>n>>a>>b; string ex; cin>>ex; vector<int> dot; for(int i=0;i<n;i++){ int c=0; while(i<n && ex[i++]=='.') c++; if(c!=0) dot.push_back(c); i--; } if(b>a) swap(a,b); sort(dot.begin(),dot.end()); ll ans=0; int i=dot.size()-1; // cout<<a<<" "<<b<<endl; while(i>=0 && (a || b)){ int v=dot[i]; // cout<<v<<endl; if((v+1)/2 < a){ ans+=(v+1)/2; a-=(v+1)/2; } else{ ans+=a; a=0; // cout<<ans<<endl; } if((v)/2 < b){ ans+=(v)/2; b-=(v)/2; } else{ ans+=b; b=0; } if(b>a)swap(a,b); i--; } cout<<ans<<endl; }
[ "orionsami160@gmail.com" ]
orionsami160@gmail.com
51cf91cffa944fd48571894a813683efc17cac20
14488b38a3faf88df270866581c9a6d54d687185
/main.cpp
2ad187b0667266a2ca9df2578272d8884614c5b0
[]
no_license
tommy0/transform-picture-negative
24114c5e6fa88645caa22b6371c1149e375ead49
2a6d58c01e0966a025ab99dcef94a7accffd765f
refs/heads/master
2021-01-10T02:43:42.161053
2016-02-24T18:03:58
2016-02-24T18:03:58
52,309,539
0
0
null
null
null
null
UTF-8
C++
false
false
984
cpp
#include <iostream> #include "png/png.hpp" #include <cmath> #include "png/convert_color_space.hpp" using namespace std; int main() { png::image< png::rgba_pixel > images("small.png"); png::image< png::rgb_pixel > image("small.png"); for(int i=0; i<images.get_height(); i++) { for(int j=0; j<images.get_width(); j++) { png::rgb_pixel a=png::rgb_pixel(255-image[i][j].red,255-image[i][j].green,255-image[i][j].blue); image[i][j]=png::convert_color_space<a>; //rgb_pixel(255-images[i][j].red*images[i][j].alpha+(1-images[i][j].alpha)*255 , // 255-image[i][j].green*images[i][j].alpha+(1-images[i][j].alpha)*255, // 255-image[i][j].blue*images[i][j].alpha+(1-images[i][j].alpha)*255); //image[i][j]=png::rgb_pixel(255-image[i][j].red,255-image[i][j].green,255-image[i][j].blue); } } image.write("output.png"); }
[ "tommy0@mail.ru" ]
tommy0@mail.ru
9fd4c8e7fce6327a1c3ddc45e9fb2e389c1e4b03
93b24e6296dade8306b88395648377e1b2a7bc8c
/client/OGRE/OgreMain/include/OgreDataStream.h
7088214e56fcff3de22c0d03653aab05c75e3640
[]
no_license
dahahua/pap_wclinet
79c5ac068cd93cbacca5b3d0b92e6c9cba11a893
d0cde48be4d63df4c4072d4fde2e3ded28c5040f
refs/heads/master
2022-01-19T21:41:22.000190
2013-10-12T04:27:59
2013-10-12T04:27:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,895
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2005 The OGRE Team Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ #ifndef __DataStream_H__ #define __DataStream_H__ #include "OgrePrerequisites.h" #include "OgreString.h" #include "OgreSharedPtr.h" #include <istream> namespace Ogre { /** General purpose class used for encapsulating the reading of data. @remarks This class performs basically the same tasks as std::basic_istream, except that it does not have any formatting capabilities, and is designed to be subclassed to receive data from multiple sources, including libraries which have no compatiblity with the STL's stream interfaces. As such, this is an abstraction of a set of wrapper classes which pretend to be standard stream classes but can actually be implemented quite differently. @par Generally, if a plugin or application provides an ArchiveFactory, it should also provide a DataStream subclass which will be used to stream data out of that Archive implementation, unless it can use one of the common implementations included. @note Ogre makes no guarantees about thread safety, for performance reasons. If you wish to access stream data asynchronously then you should organise your own mutexes to avoid race conditions. */ class _OgreExport DataStream { protected: /// The name (e.g. resource name) that can be used to identify the source fot his data (optional) String mName; /// Size of the data in the stream (may be 0 if size cannot be determined) size_t mSize; #define OGRE_STREAM_TEMP_SIZE 128 public: /// Constructor for creating unnamed streams DataStream() : mSize(0) {} /// Constructor for creating named streams DataStream(const String& name) : mName(name), mSize(0) {} /// Returns the name of the stream, if it has one. const String& getName(void) { return mName; } virtual ~DataStream() {} // Streaming operators template<typename T> DataStream& operator>>(T& val); /** Read the requisite number of bytes from the stream, stopping at the end of the file. @param buf Reference to a buffer pointer @param count Number of bytes to read @returns The number of bytes read */ virtual size_t read(void* buf, size_t count) = 0; /** Get a single line from the stream. @remarks The delimiter character is not included in the data returned, and it is skipped over so the next read will occur after it. The buffer contents will include a terminating character. @note If you used this function, you <b>must</b> open the stream in <b>binary mode</b>, otherwise, it'll produce unexpected results. @param buf Reference to a buffer pointer @param maxCount The maximum length of data to be read, excluding the terminating character @param delim The delimiter to stop at @returns The number of bytes read, excluding the terminating character */ virtual size_t readLine(char* buf, size_t maxCount, const String& delim = "\n"); /** Returns a String containing the next line of data, optionally trimmed for whitespace. @remarks This is a convenience method for text streams only, allowing you to retrieve a String object containing the next line of data. The data is read up to the next newline character and the result trimmed if required. @note If you used this function, you <b>must</b> open the stream in <b>binary mode</b>, otherwise, it'll produce unexpected results. @param trimAfter If true, the line is trimmed for whitespace (as in String.trim(true,true)) */ virtual String getLine( bool trimAfter = true ); /** Returns a String containing the entire stream. @remarks This is a convenience method for text streams only, allowing you to retrieve a String object containing all the data in the stream. */ virtual String getAsString(void); /** Skip a single line from the stream. @note If you used this function, you <b>must</b> open the stream in <b>binary mode</b>, otherwise, it'll produce unexpected results. @param delim The delimiter(s) to stop at @returns The number of bytes skipped */ virtual size_t skipLine(const String& delim = "\n"); /** Skip a defined number of bytes. This can also be a negative value, in which case the file pointer rewinds a defined number of bytes. */ virtual void skip(long count) = 0; /** Repositions the read point to a specified byte. */ virtual void seek( size_t pos ) = 0; /** Returns the current byte offset from beginning */ virtual size_t tell(void) const = 0; /** Returns true if the stream has reached the end. */ virtual bool eof(void) const = 0; /** Returns the total size of the data to be read from the stream, or 0 if this is indeterminate for this stream. */ size_t size(void) const { return mSize; } /** Close the stream; this makes further operations invalid. */ virtual void close(void) = 0; }; /** Shared pointer to allow data streams to be passed around without worrying about deallocation */ typedef SharedPtr<DataStream> DataStreamPtr; /// List of DataStream items typedef std::list<DataStreamPtr> DataStreamList; /// Shared pointer to list of DataStream items typedef SharedPtr<DataStreamList> DataStreamListPtr; /** Common subclass of DataStream for handling data from chunks of memory. */ class _OgreExport MemoryDataStream : public DataStream { protected: /// Pointer to the start of the data area uchar* mData; /// Pointer to the current position in the memory uchar* mPos; /// Pointer to the end of the memory uchar* mEnd; /// Do we delete the memory on close bool mFreeOnClose; public: /** Wrap an existing memory chunk in a stream. @param pMem Pointer to the exising memory @param size The size of the memory chunk in bytes @param freeOnClose If true, the memory associated will be destroyed when the stream is destroyed. */ MemoryDataStream(void* pMem, size_t size, bool freeOnClose = false); /** Wrap an existing memory chunk in a named stream. @param name The name to give the stream @param pMem Pointer to the exising memory @param size The size of the memory chunk in bytes @param freeOnClose If true, the memory associated will be destroyed when the stream is destroyed. */ MemoryDataStream(const String& name, void* pMem, size_t size, bool freeOnClose = false); /** Create a stream which pre-buffers the contents of another stream. @remarks This constructor can be used to intentionally read in the entire contents of another stream, copying them to the internal buffer and thus making them available in memory as a single unit. @param sourceStream Another DataStream which will provide the source of data @param freeOnClose If true, the memory associated will be destroyed when the stream is destroyed. */ MemoryDataStream(DataStream& sourceStream, bool freeOnClose = true); /** Create a stream which pre-buffers the contents of another stream. @remarks This constructor can be used to intentionally read in the entire contents of another stream, copying them to the internal buffer and thus making them available in memory as a single unit. @param sourceStream Weak reference to another DataStream which will provide the source of data @param freeOnClose If true, the memory associated will be destroyed when the stream is destroyed. */ MemoryDataStream(DataStreamPtr& sourceStream, bool freeOnClose = true); /** Create a named stream which pre-buffers the contents of another stream. @remarks This constructor can be used to intentionally read in the entire contents of another stream, copying them to the internal buffer and thus making them available in memory as a single unit. @param name The name to give the stream @param sourceStream Another DataStream which will provide the source of data @param freeOnClose If true, the memory associated will be destroyed when the stream is destroyed. */ MemoryDataStream(const String& name, DataStream& sourceStream, bool freeOnClose = true); /** Create a named stream which pre-buffers the contents of another stream. @remarks This constructor can be used to intentionally read in the entire contents of another stream, copying them to the internal buffer and thus making them available in memory as a single unit. @param name The name to give the stream @param sourceStream Another DataStream which will provide the source of data @param freeOnClose If true, the memory associated will be destroyed when the stream is destroyed. */ MemoryDataStream(const String& name, const DataStreamPtr& sourceStream, bool freeOnClose = true); /** Create a stream with a brand new empty memory chunk. @param size The size of the memory chunk to create in bytes @param freeOnClose If true, the memory associated will be destroyed when the stream is destroyed. */ MemoryDataStream(size_t size, bool freeOnClose = true); /** Create a named stream with a brand new empty memory chunk. @param name The name to give the stream @param size The size of the memory chunk to create in bytes @param freeOnClose If true, the memory associated will be destroyed when the stream is destroyed. */ MemoryDataStream(const String& name, size_t size, bool freeOnClose = true); ~MemoryDataStream(); /** Get a pointer to the start of the memory block this stream holds. */ uchar* getPtr(void) { return mData; } /** Get a pointer to the current position in the memory block this stream holds. */ uchar* getCurrentPtr(void) { return mPos; } /** @copydoc DataStream::read */ size_t read(void* buf, size_t count); /** @copydoc DataStream::readLine */ size_t readLine(char* buf, size_t maxCount, const String& delim = "\n"); /** @copydoc DataStream::skipLine */ size_t skipLine(const String& delim = "\n"); /** @copydoc DataStream::skip */ void skip(long count); /** @copydoc DataStream::seek */ void seek( size_t pos ); /** @copydoc DataStream::tell */ size_t tell(void) const; /** @copydoc DataStream::eof */ bool eof(void) const; /** @copydoc DataStream::close */ void close(void); /** Sets whether or not to free the encapsulated memory on close. */ void setFreeOnClose(bool free) { mFreeOnClose = free; } }; /** Shared pointer to allow memory data streams to be passed around without worrying about deallocation */ typedef SharedPtr<MemoryDataStream> MemoryDataStreamPtr; /** Common subclass of DataStream for handling data from std::basic_istream. */ class _OgreExport FileStreamDataStream : public DataStream { protected: /// Reference to source stream std::ifstream* mpStream; bool mFreeOnClose; public: /** Construct stream from an STL stream @param s Pointer to source stream @param freeOnClose Whether to delete the underlying stream on destruction of this class */ FileStreamDataStream(std::ifstream* s, bool freeOnClose = true); /** Construct named stream from an STL stream @param name The name to give this stream @param s Pointer to source stream @param freeOnClose Whether to delete the underlying stream on destruction of this class */ FileStreamDataStream(const String& name, std::ifstream* s, bool freeOnClose = true); /** Construct named stream from an STL stream, and tell it the size @remarks This variant tells the class the size of the stream too, which means this class does not need to seek to the end of the stream to determine the size up-front. This can be beneficial if you have metadata about the contents of the stream already. @param name The name to give this stream @param s Pointer to source stream @param size Size of the stream contents in bytes @param freeOnClose Whether to delete the underlying stream on destruction of this class */ FileStreamDataStream(const String& name, std::ifstream* s, size_t size, bool freeOnClose = true); ~FileStreamDataStream(); /** @copydoc DataStream::read */ size_t read(void* buf, size_t count); /** @copydoc DataStream::readLine */ size_t readLine(char* buf, size_t maxCount, const String& delim = "\n"); /** @copydoc DataStream::skip */ void skip(long count); /** @copydoc DataStream::seek */ void seek( size_t pos ); /** @copydoc DataStream::tell */ size_t tell(void) const; /** @copydoc DataStream::eof */ bool eof(void) const; /** @copydoc DataStream::close */ void close(void); }; /** Common subclass of DataStream for handling data from C-style file handles. @remarks Use of this class is generally discouraged; if you want to wrap file access in a DataStream, you should definitely be using the C++ friendly FileStreamDataStream. However, since there are quite a few applications and libraries still wedded to the old FILE handle access, this stream wrapper provides some backwards compatibility. */ class _OgreExport FileHandleDataStream : public DataStream { protected: FILE* mFileHandle; public: /// Create stream from a C file handle FileHandleDataStream(FILE* handle); /// Create named stream from a C file handle FileHandleDataStream(const String& name, FILE* handle); ~FileHandleDataStream(); /** @copydoc DataStream::read */ size_t read(void* buf, size_t count); /** @copydoc DataStream::skip */ void skip(long count); /** @copydoc DataStream::seek */ void seek( size_t pos ); /** @copydoc DataStream::tell */ size_t tell(void) const; /** @copydoc DataStream::eof */ bool eof(void) const; /** @copydoc DataStream::close */ void close(void); }; } #endif
[ "viticm@126.com" ]
viticm@126.com
5bce89eaff78dff8826ee9bcc25fb79320c691ed
50f63963e73a8436bef3c0e6e3be7056291e1e3b
/panda/include/vrpnClient.h
1fd02676012f705fc157162ad19764fa93671d53
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
MTTPAM/installer
7f4ad0c29631548345fac29ca7fbfcb38e37a111
aee7a9b75f1da88fdf6d5eae5cdf24739c540438
refs/heads/master
2020-03-09T15:32:48.765847
2018-11-13T03:35:50
2018-11-13T03:35:50
128,861,764
1
4
null
2018-11-13T03:35:50
2018-04-10T02:28:29
Python
UTF-8
C++
false
false
3,161
h
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file vrpnClient.h * @author jason * @date 2000-08-04 */ #ifndef VRPNCLIENT_H #define VRPNCLIENT_H #include "pandabase.h" #include "clientBase.h" #include "vrpn_interface.h" class VrpnTracker; class VrpnTrackerDevice; class VrpnButton; class VrpnButtonDevice; class VrpnAnalog; class VrpnAnalogDevice; class VrpnDial; class VrpnDialDevice; /** * A specific ClientBase that connects to a VRPN server and records * information on the connected VRPN devices. */ class EXPCL_VRPN VrpnClient : public ClientBase { PUBLISHED: VrpnClient(const string &server_name); ~VrpnClient(); INLINE const string &get_server_name() const; INLINE bool is_valid() const; INLINE bool is_connected() const; void write(ostream &out, int indent_level = 0) const; public: INLINE static double convert_to_secs(struct timeval msg_time); protected: virtual PT(ClientDevice) make_device(TypeHandle device_type, const string &device_name); virtual bool disconnect_device(TypeHandle device_type, const string &device_name, ClientDevice *device); virtual void do_poll(); private: PT(ClientDevice) make_tracker_device(const string &device_name); PT(ClientDevice) make_button_device(const string &device_name); PT(ClientDevice) make_analog_device(const string &device_name); PT(ClientDevice) make_dial_device(const string &device_name); void disconnect_tracker_device(VrpnTrackerDevice *device); void disconnect_button_device(VrpnButtonDevice *device); void disconnect_analog_device(VrpnAnalogDevice *device); void disconnect_dial_device(VrpnDialDevice *device); VrpnTracker *get_tracker(const string &tracker_name); void free_tracker(VrpnTracker *vrpn_tracker); VrpnButton *get_button(const string &button_name); void free_button(VrpnButton *vrpn_button); VrpnAnalog *get_analog(const string &analog_name); void free_analog(VrpnAnalog *vrpn_analog); VrpnDial *get_dial(const string &dial_name); void free_dial(VrpnDial *vrpn_dial); private: string _server_name; vrpn_Connection *_connection; typedef pmap<string, VrpnTracker *> Trackers; typedef pmap<string, VrpnButton *> Buttons; typedef pmap<string, VrpnAnalog *> Analogs; typedef pmap<string, VrpnDial *> Dials; Trackers _trackers; Buttons _buttons; Analogs _analogs; Dials _dials; public: static TypeHandle get_class_type() { return _type_handle; } static void init_type() { ClientBase::init_type(); register_type(_type_handle, "VrpnClient", ClientBase::get_class_type()); } virtual TypeHandle get_type() const { return get_class_type(); } virtual TypeHandle force_init_type() {init_type(); return get_class_type();} private: static TypeHandle _type_handle; }; #include "vrpnClient.I" #endif
[ "linktlh@gmail.com" ]
linktlh@gmail.com
d66af175a88e61fdcf3ff3ab7e7e0a6f774518c8
fb330c7409647dd07aeafe08ef37df4f66bb1e72
/LightOj 1300 - Odd Personality.cpp
651aa6ef967350d8408e1739c466370c6536b3ec
[]
no_license
RKrava/Articulation-Point-Problems
095b665c536b2fd0212d912c1460f57dae3c65f6
10cb835a5d8e698e2bd668f5e253a1e288d0d22e
refs/heads/master
2022-12-10T10:56:13.194239
2020-09-20T19:43:16
2020-09-20T19:43:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,056
cpp
/* First ,exactly we have to count the nodes of a cycle where the amount of nodes of a particular cycle is odd. So, first of all finding all bridge edges and remove them from the graph and store them in a set array called newGraph. We could take array of vector ,but it will take O(n) time complexity to erase a value from a node's adjacency vector, That's why I used array of set which will take O(logn) in average to erase any value from a set. Then we use another dfs which will run over the cycle only ,as all critical edges are removed. So, if we find cycle of odd length then we will count those nodes. */ /// Time-0.443s /// Very Nice one #include<bits/stdc++.h> using namespace std; const int mx=10002; vector<int>adj[mx];/// adjacency matrix set<int>newGraph[mx];/// adjacentry matrix used for graph without all critical edges bool visited[mx];/// visited or not ?? int disc[mx]={0};/// dfs time finding,dfs number of a node int low[mx]={0};/// low dfs time for purpose to find a cycle int parent[mx]={-1};/// -1 holds for Null int dist[mx]; int nodes=0; bool oddCycle; void bcc(int u) { ///this parameter will be used for counting discovery time of a node static int time=0; ///for marking a node visited[u]=true; ///keeping dfs(discovery) time and low discovery time disc[u]=low[u]=time++; vector<int>::iterator it; ///iterator to iterate adjacency matrix of graph for(it=adj[u].begin();it!=adj[u].end();it++) { ///neighbour's node of v from u, u->v int v=(*it); ///if not visited ,then proceed apu_finding for new node(v) if(!visited[v]) { parent[v]=u; bcc(v); ///this is for finding low dfs number of a node low[u]=min(low[u],low[v]); /// when low[v]>disc[u] , this u-v is the critical edges,bridge (u-v) if(low[v]>disc[u]) { newGraph[u].erase(v); newGraph[v].erase(u); /// removing bridges pairs } } /// this means that, visited[v] is true i.e. already v is visited /// if u's parent is not v,then this is a back edge , u-v .so we will take low[] time from disc[] time of v else if(v!=parent[u]) { low[u]=min(low[u],disc[v]); } } } /// is Oddcycle ? void cycle_dfs(int u,int p,int len) { nodes++; dist[u] = len; visited[u] = true; set<int>::iterator it; for(it=newGraph[u].begin();it!=newGraph[u].end();it++) { int v=(*it); if(!visited[v]) cycle_dfs(v,u,len+1); else if (visited[v] && (dist[v]-dist[u])%2==0) /** check the length of the loop defined by each back-edge **/ oddCycle = true; } } int main() { int tc; cin>>tc; for(int tst=1;tst<=tc;tst++) { for(int k=0;k<mx;k++) { adj[k].clear(); newGraph[k].clear(); visited[k]=false; disc[k]=0; low[k]=0; parent[k]=-1; dist[k]=0; } int V,E,u,v; cin>>V>>E; while(E--) { cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); newGraph[u].insert(v); newGraph[v].insert(u); } for(int i=0;i<V;i++) { ///this node is not visited yet ///the graph may be not connected ///iterate for every connected component if(!visited[i]) { bcc(i); } } /// now again make visited array false to run over dfs for(int i=0;i<mx;i++) visited[i]=false; int res = 0; for(int i=0; i<V; i++) { nodes = 0; oddCycle = false; if(!visited[i]) cycle_dfs(i,-1,0); if(oddCycle) res += nodes; } cout<<"Case "<<tst<<": "; cout<<res<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
bb9566c88aca4be60334dc60c5d096f7cc3e0cf4
463ccbc7b19822e3695e02d27e255ce64eacb627
/ie3D-Core/Sources/IGameLoopHandler.cpp
8cff19a18a3af174c20b9d05f2b4c8ede736f3b8
[]
no_license
codeoneclick/ie3D
8abd318361ff80fbbfe5273943183fe158bf40af
46f109a520c6d813c3994b5cf2b12e2de5625371
refs/heads/master
2021-01-24T06:37:41.615380
2014-05-23T14:02:12
2014-05-23T14:02:12
9,913,979
10
2
null
null
null
null
UTF-8
C++
false
false
1,014
cpp
// // IGameLoopHandler.cpp // indi2dEngine-Core // // Created by Sergey Sergeev on 5/7/13. // Copyright (c) 2013 Sergey Sergeev. All rights reserved. // #include "IGameLoopHandler.h" CGameLoopCommands::CGameLoopCommands(void) : m_gameLoopUpdateCommand(nullptr) { } CGameLoopCommands::~CGameLoopCommands(void) { m_gameLoopUpdateCommand = nullptr; } void CGameLoopCommands::_ConnectGameLoopUpdateCommand(const __GAME_LOOP_UPDATE_COMMAND &_command) { assert(_command != nullptr); m_gameLoopUpdateCommand = _command; } void CGameLoopCommands::_ExecuteGameLoopUpdateCommand(f32 _deltatime) { assert(m_gameLoopUpdateCommand != nullptr); m_gameLoopUpdateCommand(_deltatime); } IGameLoopHandler::IGameLoopHandler(void) { IGameLoopHandler::_ConnectCommands(); } IGameLoopHandler::~IGameLoopHandler(void) { } void IGameLoopHandler::_ConnectCommands(void) { m_commands._ConnectGameLoopUpdateCommand(std::bind(&IGameLoopHandler::_OnGameLoopUpdate, this, std::placeholders::_1)); }
[ "sergey.sergeev@khawks0292.kha.gameloft.org" ]
sergey.sergeev@khawks0292.kha.gameloft.org
22e793833bc90237423eee894a99ae8103ed81e4
153f3ef1854209d7112aa412b098d7736deb6efa
/src/Human.h
1f70907ac71674dcb2e9b11f82563083a82f6406
[]
no_license
ben31w/Composition_Intro
dc25240ced286b7bd79151e71575381982ff257f
cf22ce71540eacdce11a154854906ee2666a9d96
refs/heads/master
2022-04-19T14:43:59.870899
2020-04-20T04:19:15
2020-04-20T04:19:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
400
h
/* * Human.h * * Created on: Apr 19, 2020 * Author: keith */ #ifndef HUMAN_H_ #define HUMAN_H_ #include "Watch.h" class Human { public: Human(Watch *w); virtual ~Human(); //how to get time from a human? You ask. //this is called delegation //if has a watch, returns time, otherwise says //I dont have a watch std::string getTime(); private: Watch *w; }; #endif /* HUMAN_H_ */
[ "keith.perkins@cnu.edu" ]
keith.perkins@cnu.edu
6b4cacab6d27c38ca36f20a92b39b222ad7326ed
670cc962162aad7d92f6d9d0721dc41a65209de1
/Strategy y Template method (ej navegador)/src/Bueno.cpp
8dbe7ba9020dfc72910276d1de2117a73380631a
[]
no_license
Zarakinoa/Design-Patterns
1d133764ae9b16fb8fecb1c000be533741dccbac
e141146b15d22f09aa670815b9a2c16dbb0c8257
refs/heads/master
2022-02-19T04:02:13.075807
2019-09-25T03:42:33
2019-09-25T03:42:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
193
cpp
#include "Bueno.h" Bueno::Bueno() { //ctor } Bueno::~Bueno() { //dtor } string Bueno::bajarDatos(string url){ return "<Datos de la pagina (con calidad BUENA) de " + url + ">"; }
[ "mathias2b@gmail.com" ]
mathias2b@gmail.com
f105b7255ca564f928f196a4155be663da115ddc
8a68c26ccdba4156b5f28ef4e4e22540654553d5
/src/Features/DeepFeaturesInception.h
24cff170594977652dc6836d505f2bf79b38a212
[]
no_license
lilin201501/Antrack
1e5cd5ee4bd3a61665ac5e9deea16657a875c745
5c13619329a0ba9be61146d48e25ecea47f8edd0
refs/heads/master
2020-12-27T12:38:21.896233
2016-06-11T01:29:47
2016-06-11T01:29:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,167
h
// DeepFeaturesInception.h // // last-edit-by: <> // // Description: // ////////////////////////////////////////////////////////////////////// #ifdef USE_DEEP_FEATURES #ifndef DEEPFEATURES_H_INCEPTION #define DEEPFEATURES_H_INCEPTION 1 #include "DeepFeatures.h" #include "boost/algorithm/string.hpp" #include "google/protobuf/text_format.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/net.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/db.hpp" #include "caffe/util/io.hpp" #include "caffe/vision_layers.hpp" class DeepFeaturesInception:public DeepFeatures { public: DeepFeaturesInception(){}; ~DeepFeaturesInception(){} int calculateFeatureDimension() { return 1024; //return 1000; } cv::Mat prepareImage(cv::Mat* imageIn){ return DeepFeatures::prepareImage(imageIn); } arma::mat calculateFeature(cv::Mat& processedImage, std::vector<cv::Rect>& rects); std::string getInfo(); }; #endif #endif // DEEPFEATURES_H_INCEPTION ////////////////////////////////////////////////////////////////////// // $Log:$ //
[ "ibogun2010@my.fit.edu" ]
ibogun2010@my.fit.edu
6f9a8192e30751827ca3c12cbe2ea8ea1281018f
f4f82289d3c3fb7b34da170aeea8a0d05aebf148
/source/render/gizmos/GizmoManager.h
7d33e77a20c176cd0d476987f470e390abdd783a
[ "MIT" ]
permissive
freneticmonkey/epsilonc
4b8486ef3a66f9f11dd356d568c4f6833e066150
0fb7c6c4c6342a770e2882bfd67ed34719e79066
refs/heads/master
2021-01-18T15:16:34.845535
2015-02-06T11:57:01
2015-02-06T11:57:01
21,097,234
0
0
null
null
null
null
UTF-8
C++
false
false
1,235
h
#pragma once #include "EpsilonCore.h" #include "render/gizmos/GizmoType.h" #include "render/gizmos/GizmoCube.h" #include "render/gizmos/GizmoSphere.h" #include "render/gizmos/GizmoLine.h" #include "render/gizmos/GizmoAxis.h" namespace epsilon { // Manages current gizmo operations. class GizmoManager { GizmoManager(void); typedef std::vector<GizmoType *> GizmoTypes; public: static GizmoManager & GetInstance() { static GizmoManager instance; return instance; } ~GizmoManager(void); void Setup(void); void Draw(); void OnUpdate(float el); void Destroy(); GizmoManager & AddGizmo(GizmoType * newGizmo); // Draw Gizmos static void SetColour(Colour newColour); static void SetLife(float newLife); static void DrawCube(Vector3 position, Vector3 size); static void DrawSphere(Vector3 position, float radius); static void DrawLine(Vector3 from, Vector3 to); static void DrawAxisMatrix(Matrix4 mat); static void DrawAxisVectors(Vector3 pos, Vector3 right, Vector3 up, Vector3 forward); private: Colour gizmoColour; float gizmoLife; GizmoTypes gizmos; GizmoCube * gizmoCube; GizmoSphere * gizmoSphere; GizmoLine * gizmoLine; GizmoAxis * gizmoAxis; }; }
[ "scottporter@neuroticstudios.com" ]
scottporter@neuroticstudios.com
c242b9c8b817021e2269a9b7a849dae3846feec4
dcafc53ed795fb295fe41dfbe426497ac1eee076
/archive/basics/code_struct_12_arrays/dynamic_arrays.cpp
3ea1bb9136e99cb56336add724d5bddf9ca0cb52
[]
no_license
hoodielive/cplusplus
18b68537c26bb12388075262e2db3e5654301dea
8592ed7190ca335fdf13739d4682be253a88a8b8
refs/heads/master
2020-03-21T18:07:03.423697
2020-01-29T03:48:24
2020-01-29T03:48:24
138,873,323
0
0
null
null
null
null
UTF-8
C++
false
false
379
cpp
#include <iostream> using namespace std; int main() { int* p = new int[3]; *(p + 1) = 10; // p[1] = 10; cout << p[1] << endl; int length = sizeof(p) / sizeof(int); cout << length <<endl; int size = 3; int* q = new int[size]; // dynamically allocated array cout << q[1] << endl; delete[] p; // release allocated array cout << p[1] << endl; return 0; }
[ "hoodielive@gmail.com" ]
hoodielive@gmail.com
15b17099c1c4b4dfca00549ac1ef0b2f5a48363c
bf77f38c1d42ce97902bd5dc0e498d7d89ab4705
/atcoder/contest/abc/abc242/f.cpp
aa2f89e2d8885526d070fbe5b8efd46e689257d6
[]
no_license
byam/algorithms
6c570c8d00ad5457346d6851f634d962b2ef744e
f3db7230655c945412774505254e2be4cbf23074
refs/heads/master
2022-05-12T16:24:39.831337
2022-04-08T13:59:07
2022-04-08T13:59:07
68,830,972
3
0
null
null
null
null
UTF-8
C++
false
false
5,214
cpp
#include <bits/stdc++.h> #include <iostream> #include <map> #include <queue> #include <set> #include <vector> //#include <atcoder/all> // using namespace atcoder; using namespace std; // func #define rep(i, first, last) for (int i = (first); i < (last); i++) #define rrep(i, last, first) for (int i = (last); i >= (first); i--) #define srtv(v) sort((v).begin(), (v).end()) #define all(v) (v).begin(), (v).end() // template template <class T> void chmin(T& a, T b) { if (a > b) { a = b; } } template <class T> void chmax(T& a, T b) { if (a < b) { a = b; } } template <class T> T maxi(vector<T>& nums) { // return max value index left return max_element(nums.begin(), nums.end()) - nums.begin(); } template <class T> T mini(vector<T>& nums) { // return min value index left return min_element(nums.begin(), nums.end()) - nums.begin(); } // out -> print template <class T> void out(T x) { cout << x << "\n"; } template <class T> void out(vector<T> x) { int sz = x.size(); for (int i = 0; i < sz; i++) { cout << x[i]; if (i < sz - 1) cout << " "; } cout << "\n"; } template <class T> void out(vector<pair<T, T>> p) { for (auto [f, s] : p) { cout << f << " " << s << endl; } } template <class T> void out(map<T, T> m) { for (auto [k, v] : m) { cout << k << ": " << v << endl; } } template <class T> void out(set<T> s) { for (auto x : s) { cout << x << " "; } cout << endl; } // パラメータパックが空になったら終了 void outt() { cout << endl; } // ひとつ以上のパラメータを受け取るようにし、 // 可変引数を先頭とそれ以外に分割する template <class Head, class... Tail> void outt(Head&& head, Tail&&... tail) { std::cout << head << " "; // パラメータパックtailをさらにheadとtailに分割する outt(std::forward<Tail>(tail)...); } // in #define rd(...) \ __VA_ARGS__; \ read(__VA_ARGS__) #define rdv(value, ...) \ value(__VA_ARGS__); \ cin >> value template <class T> auto& operator>>(istream& is, vector<T>& xs) { for (auto& x : xs) is >> x; return is; } template <class T> auto& operator<<(ostream& os, vector<T>& xs) { int sz = xs.size(); rep(i, 0, sz) os << xs[i] << " \n"[i + 1 == sz]; return os; } template <class T, class Y> auto& operator<<(ostream& os, pair<T, Y>& xs) { os << "{" << xs.first << ", " << xs.second << "}"; return os; } template <class T, class Y> auto& operator>>(istream& is, vector<pair<T, Y>>& xs) { for (auto& [x1, x2] : xs) is >> x1 >> x2; return is; } template <class... Args> auto& read(Args&... args) { return (cin >> ... >> args); } // type typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<bool> vb; typedef vector<long long> vll; typedef pair<int, int> pii; typedef pair<long long, long long> pll; typedef priority_queue<int> pqi; // greater typedef priority_queue<int, vector<int>, greater<int>> pqli; // less typedef priority_queue<long long, vector<long long>, greater<long long>> pqlll; typedef vector<pair<int, int>> vpii; typedef vector<vector<int>> vvi; typedef vector<vector<long long>> vvll; typedef vector<vector<int>> Graph; // get divisors: 10 => 1, 2, 5, 10 set<ll> all_factors(ll n) { // Vector to store half of the divisors set<ll> v; for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { v.insert(i); v.insert(n / i); } } return v; } // get prime divisors: 12 => 2(2), 3(1) map<ll, ll> prime_factors_map(ll n) { map<ll, ll> m; ll k = sqrt(n); for (int i = 2; i <= k; i++) { while (n % i == 0) { m[i]++; n /= i; } } if (n > 1) m[n]++; return m; } vector<long long> prime_factors(long long N) { long long rem = N; vector<long long> p; for (long long i = 2; i * i <= N; i++) { while (rem % i == 0) { rem /= i; p.push_back(i); } } if (rem != 1LL) p.push_back(rem); return p; } bool is_prime(long long N) { bool res = true; for (long long i = 2; i * i <= N; i++) { if (N % i == 0) res = false; } return res; } // geometry #define PI 3.14159265358979323846264338327950288 template <class T> T to_rad(T angle) { return angle * PI / 180.; } // 二乗法 long long binpower(long long a, long long b, long long mod) { long long ans = 1; while (b != 0) { if (b % 2 == 1) { ans = (long long)(ans)*a % mod; } a = (long long)(a)*a % mod; b /= 2; } return ans; } // const const ll MOD = 1000000007; const ll INF = 1e18; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; /*----------------------------------- Coding Starts Here ------------------------------------*/ void solve() { // in int rd(n); vi rdv(a, n); vvi d(n); } int main() { // make input and output more efficient ios::sync_with_stdio(0); cin.tie(0); int t; t = 1; // cin >> t; while (t--) solve(); return 0; }
[ "bya_ganbaatar@r.recruit.co.jp" ]
bya_ganbaatar@r.recruit.co.jp
445be39d679e2a32851e291956566ef938bf24c2
798dd8cc7df5833999dfceb0215bec7384783e6a
/schema.h
1368fc45971247c0a3ef02129b75ea433187e273
[ "BSD-3-Clause" ]
permissive
sblanas/pythia
8cf85b39d555c6ce05445d9d690d5462d0e80007
b138eaa0fd5917cb4665094b963abe458bd33d0f
refs/heads/master
2016-09-06T03:43:26.647265
2014-02-10T21:39:24
2014-02-10T21:39:24
16,710,063
15
8
null
2014-03-08T05:29:34
2014-02-10T21:31:16
C++
UTF-8
C++
false
false
10,643
h
/* * Copyright 2007, Pythia authors (see AUTHORS file). * 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 __MYSCHEMA__ #define __MYSCHEMA__ #include <vector> #include <utility> #include <string> #include <cstring> #include <cassert> #include <ctime> #include "libconfig.h++" #include "util/custom_asserts.h" #include "util/static_assert.h" #include "exceptions.h" using namespace std; enum ColumnType { CT_INTEGER, /**< Integer is sizeof(int), either 32 or 64 bits. */ CT_LONG, /**< Long is sizeof(long long), exactly 64 bits. */ CT_DECIMAL, /**< Decimal is sizeof(double). */ CT_CHAR, /**< Char has user-defined length, no zero padding is done in this class. */ CT_DATE, /**< Date is sizeof(CtLong), custom format (see DateT class). */ CT_POINTER /**< Pointer is sizeof(void*). */ }; typedef int CtInt; typedef long long CtLong; typedef double CtDecimal; typedef char CtChar; typedef void* CtPointer; /** * Class representing date objects. Bit structure: * * Bit range | Number | Discrete | * (0 is LSB) | of bits | values | Purpose * -----------+---------+----------+--------------- * 00-09 | 10 | 1024 | Microseconds * 10-19 | 10 | 1024 | Milliseconds * 20-25 | 6 | 64 | Seconds * 26-31 | 6 | 64 | Minutes * 32-36 | 5 | 32 | Hours * 37-41 | 5 | 32 | Days * 42-45 | 4 | 16 | Months * 46-63 | 18 | 262144 | Years */ class DateT { public: explicit DateT() { date = 0; } inline const DateT& operator=(const DateT& rhs) { date = rhs.date; return rhs; } inline void setFromTM(const struct tm* t) { date = 0; date |= (t->tm_sec & MASKSEC) << SHIFTSEC; date |= (t->tm_min & MASKMIN) << SHIFTMIN; date |= (t->tm_hour & MASKHOUR) << SHIFTHOUR; date |= (t->tm_mday & MASKDAY) << SHIFTDAY; date |= (t->tm_mon & MASKMONTH) << SHIFTMONTH; date |= (t->tm_year & MASKYEAR) << SHIFTYEAR; } inline void produceTM(struct tm* out) { memset(out, 0, sizeof(struct tm)); out->tm_sec = (date >> SHIFTSEC) & MASKSEC; out->tm_min = (date >> SHIFTMIN) & MASKMIN; out->tm_hour = (date >> SHIFTHOUR) & MASKHOUR; out->tm_mday = (date >> SHIFTDAY) & MASKDAY; out->tm_mon = (date >> SHIFTMONTH) & MASKMONTH; out->tm_year = (date >> SHIFTYEAR) & MASKYEAR; } private: static const unsigned long long MASK4 = 0x0000F; static const unsigned long long MASK5 = 0x0001F; static const unsigned long long MASK6 = 0x0003F; static const unsigned long long MASK10 = 0x003FF; static const unsigned long long MASK18 = 0x3FFFF; static const unsigned long long MASKUSEC = MASK10; static const unsigned long long MASKMSEC = MASK10; static const unsigned long long MASKSEC = MASK6; static const unsigned long long MASKMIN = MASK6; static const unsigned long long MASKHOUR = MASK5; static const unsigned long long MASKDAY = MASK5; static const unsigned long long MASKMONTH= MASK4; static const unsigned long long MASKYEAR = MASK18; static const unsigned long long SHIFTUSEC = 0; static const unsigned long long SHIFTMSEC = 10; static const unsigned long long SHIFTSEC = 20; static const unsigned long long SHIFTMIN = 26; static const unsigned long long SHIFTHOUR = 32; static const unsigned long long SHIFTDAY = 37; static const unsigned long long SHIFTMONTH= 42; static const unsigned long long SHIFTYEAR = 46; CtLong date; }; typedef class DateT CtDate; struct ColumnSpec { ColumnSpec(ColumnType ct, unsigned int sz, const string& str) : type(ct), size(sz), formatstr(str) { } ColumnType type; /**< Type of field. */ unsigned int size; /**< Size of field, in bytes. */ const string& formatstr; /**< Format string, only valid for CT_DATE. */ }; #include "comparator.h" class Schema { public: Schema() : totalsize(0) { } /** * Add new column at the end of this schema. * @param ct Column type. * @param size Max characters (valid for CHAR(x) type only). */ void add(ColumnType ct, unsigned int size = 0); /** * Add new column at the end of this schema. * @param ct Column type -- date only. * @param format Date format string. */ void add(ColumnType ct, const string& formatstr); void add(ColumnSpec desc); /** * Returns columnt type at position \a pos. * @param pos Position in schema. * @return Column type. */ inline ColumnType getColumnType(unsigned int pos); /** * Returns a \a ColumSpec. * @param pos Position in schema. * @return A \a ColumnSpec for this column. */ inline ColumnSpec get(unsigned int pos); /** * Get width (in bytes) of column \a pos. */ inline unsigned int getColumnWidth(unsigned int pos); /** * Get total number of columns. * @return Total number of columns. */ inline unsigned int columns(); /** * Get a tuple size, in bytes, for this schema. * @return Tuple size in bytes. */ inline unsigned int getTupleSize(); /** * Return a string representation of the data in column \a pos. * @param data Tuple to work on. * @param pos Position of column to parse. * @throw IllegalConversionException. */ inline const CtChar* asString(void* data, unsigned int pos); /** * Calculate the position of data item \a pos inside tuple \a data. * @param data Tuple to work on. * @param pos Position in tuple. * @return Pointer to data of column \a pos. */ inline void* calcOffset(void* data, unsigned int pos); /** * Return an integer representation of the data in column \a pos. * @param data Tuple to work on. * @param pos Position of column to parse. * @throw IllegalConversionException. */ inline const CtInt asInt(void* data, unsigned int pos); /** * Return a date representation (seconds since epoch) of the data in column \a pos. * @param data Tuple to work on. * @param pos Position of column to parse. * @throw IllegalConversionException. */ inline const CtDate asDate(void* data, unsigned int pos); /** * Return an integer representation of the data in column \a pos. * @param data Tuple to work on. * @param pos Position of column to parse. * @throw IllegalConversionException. */ inline const CtLong asLong(void* data, unsigned int pos); /** * Return a double representation of the data in column \a pos. * @param data Tuple to work on. * @param pos Position of column to parse. * @throw IllegalConversionException. */ inline const CtDecimal asDecimal(void* data, unsigned int pos); /** * Return the data in column \a pos as a pointer. * @param data Tuple to work on. * @param pos Position of column to parse. * @throw IllegalConversionException. */ inline const CtPointer asPointer(void* data, unsigned int pos); /** * Write the input \a data to the tuple pointed by \a dest. * @pre Caller must have preallocated enough memory at \a dest. * @param dest Destination tuple to write. * @param pos Position in the tuple. * @param data Data to write. */ inline void writeData(void* dest, unsigned int pos, const void* const data); /** * Parse the input vector \a input, convert each element to * the appropriate type (according to the schema) and * call @ref writeData on that. * @pre Caller must have preallocated enough memory at \a dest. * @param dest Destination tuple to write. * @param input Vector of string inputs. */ void parseTuple(void* dest, const std::vector<std::string>& input); void parseTuple(void* dest, const char** input); /** * Returns a string representation of each column in the tuple. * @param data Tuple to parse. * @return Vector of strings. */ std::vector<std::string> outputTuple(void* data); /** * Copy a tuple from \a src to \a dest. The number of bytes * copied is equal to \ref getTupleSize. * @pre Caller must have preallocated enough memory at \a dest. * @param dest Destination address. * @param src Source address. */ inline void copyTuple(void* dest, const void* const src); /** * Pretty-print the tuple, using character \a sep as separator. */ string prettyprint(void* tuple, char sep); /** * Create Schema object from configuration node. */ static Schema create(const libconfig::Setting& line); /** * Create Comparator object. */ static Comparator createComparator(Schema& lhs, unsigned int lpos, Schema& rhs, unsigned int rpos, Comparator::Comparison op); static Comparator createComparator(Schema& lhs, unsigned int lpos, ColumnSpec& rhs, Comparator::Comparison op); static Comparator createComparator(ColumnSpec& lhs, Schema& rhs, unsigned int rpos, Comparator::Comparison op); static const string UninitializedFormatString; private: vector<ColumnType> vct; vector<unsigned short> voffset; vector<short> vmetadataidx; vector<string> vformatstr; int totalsize; }; #include "schema.inl" #endif
[ "blanas.2@osu.edu" ]
blanas.2@osu.edu
ee497ae72485530722d136f1d555a0d13a3bcd6b
0242b6a54ddf4685f3537d468b3649d7029d742e
/CSE 306 Discrete Mathematics/3.Cartesian-products.cpp
1a30598280c784839a9af48a13e76db33eb6fdb0
[]
no_license
mdminhazulhaque/ruet-cse-codes
45a1fa1e227d62081224063d168a402607a03a31
496f335f47509753b4fdc529824f338da7836925
refs/heads/master
2021-06-21T08:41:28.159152
2017-07-20T20:01:09
2017-07-20T20:01:09
41,544,708
1
0
null
null
null
null
UTF-8
C++
false
false
646
cpp
#include <iostream> #define size 4 using namespace std; int main() { int setA[size] = {1,2,3,4}; int setB[size] = {5,6,7,8}; int i; /** Print Sets ***/ cout << "Set A = { "; for(i=0; i<size; i++) cout << setA[i] << ' '; cout << "}" << endl; cout << "Set B = { "; for(i=0; i<size; i++) cout << setB[i] << ' '; cout << "}" << endl; /*** Calculate Curtesian ***/ cout << "AxB = { "; for (int i=0; i<size; i++) for (int j=0; j<size; j++) { cout << "(" << setA[i] << ","; cout << setB[j] <<") "; } cout << "}"; return 0; }
[ "mdminhazulhaque@gmail.com" ]
mdminhazulhaque@gmail.com
cd9998ea79822bf44fd0bb00832de141b4dadfb4
bb5ae0c5f2fcc917d5c95f5f0886d262d8f55021
/Source/TheTree/Public/4.Character/BasicEnemy/TTArgoniteTrooper.h
0baa548545be626a58dfc14a1e4833de983dd5fc
[]
no_license
doyoulikerock/TheTree
efa2f634a17826cd78c04647f2d2d4030030e7e7
fc0d08bb1944a4f3355d6af5db949dd46442d053
refs/heads/master
2023-03-19T07:43:35.695149
2020-08-25T11:19:37
2020-08-25T11:19:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
675
h
#pragma once #include "TheTree.h" #include "TTEnemyBase.h" #include "TTArgoniteTrooper.generated.h" UCLASS() class THETREE_API ATTArgoniteTrooper : public ATTEnemyBase { GENERATED_BODY() protected: virtual void BeginPlay() override; void AttackCheck(); UFUNCTION() void OnMontageEnded(UAnimMontage* Montage, bool bInterrupted); public: ATTArgoniteTrooper(); virtual void PostInitializeComponents() override; virtual void PossessedBy(AController* NewController) override; virtual void Tick(float DeltaTime) override; virtual float TakeDamage(float DamageAmount, const FDamageEvent& DamageEvent, AController* EventInstigator, AActor* DamageCauser) override; };
[ "zoemfhs123@gmail.com" ]
zoemfhs123@gmail.com
efbec88a153334f353aaeb8cfb5172bf77425039
055a18a71df36bb8789192e8b89fd1adcd2993a5
/NN.hpp
22d31345c619dfd07b7951a071a65057812c494d
[]
no_license
maverickdas/Movie-Review-Sentiment-Analysis
e799008b8de4011b297295da76b9e226f411ddd3
3a062155e5bc84739a97c5070297da0c38c7d11a
refs/heads/master
2020-04-06T15:39:36.914945
2018-11-20T14:42:54
2018-11-20T14:42:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,256
hpp
#include "Activations.hpp" #include <iostream> #include <random> #include <algorithm> struct Net { std::vector<af::array> A; std::vector<af::array> dA; std::vector<af::array> W; std::vector<std::pair<af::array(*)(const af::array&),af::array(*)(const af::array&)>> activations; af::array Y; std::vector<int> layout; double alpha = 0.001; int iterations = 1; Net(std::vector<int> tmp); void setInputMatrix(const std::vector<std::vector<float>> &x); void setInputFile(std::string file); void setOutputMatrix(const std::vector<std::vector<float>> &y); void setOutputFile(std::string file); void setActivationFunction(int layer, af::array(*acti)(const af::array&), af::array(*actiDerivative)(const af::array&)); void setLearningRate(double x); void setIterations(int iter); void feedForward(); void backPropagate(); std::vector<float> getResults(); void train(); void predict(const std::vector<std::vector<float>> &x); void save(std::string pathname); void loadModel(std::string pathname); void shuffle(); void shuffleInput(const std::vector<int> &indices); void shuffleOutput(const std::vector<int> &indices); }; Net::Net(std::vector<int> tmp) { for(int i = 0; i < tmp.size() - 1; i++) tmp[i]++; layout = tmp; A = std::vector<af::array>(layout.size()); dA = std::vector<af::array>(layout.size()); W = std::vector<af::array>(layout.size() - 1); af::setSeed(std::random_device()()); for(int i = 0; i < W.size(); i++) W[i] = af::randn(layout[i], layout[i+1]); activations = std::vector<std::pair<af::array(*)(const af::array&),af::array(*)(const af::array&)>>(layout.size() - 1); for(int i = 0; i < activations.size() - 1; i++) activations[i] = std::make_pair(act::ReLu, act::ReLuDerivative); activations[activations.size() - 1] = std::make_pair(act::sigmoid, act::sigmoidDerivative); } void Net::setInputMatrix(const std::vector<std::vector<float>> &x) { A[0] = af::array(x.size(), layout[0]); for(int i = 0; i < A[0].dims(0); i++) for(int j = 0; j < A[0].dims(1); j++) if(j == x[i].size()) A[0](i, j) = 1.0; else A[0](i, j) = x[i][j]; } void Net::setInputFile(std::string file) { FILE *in=fopen(file.c_str(), "r"); fseek(in, 0, SEEK_END); size_t size = ftell(in); std::vector<char> buffer(size); rewind(in); fread(buffer.data(), 1, size, in); fclose(in); std::vector<float> tmp; std::string tmp1 = ""; for(const auto& i : buffer) { if( i == ' ' || i == '\n') { if(tmp1 != "") tmp.emplace_back((float)std::atof(tmp1.c_str())); tmp1 = ""; } else tmp1 += i; } if(tmp1 != "") tmp.emplace_back((float)std::atof(tmp1.c_str())); tmp.shrink_to_fit(); A[0] = af::array(layout[0] - 1, tmp.size() / (layout[0] - 1), tmp.data(), afHost); A[0] = A[0].T(); A[0] = af::join(1, A[0], af::constant(1.0, A[0].dims(0))); } void Net::setOutputFile(std::string file) { FILE *in=fopen(file.c_str(), "r"); fseek(in, 0, SEEK_END); size_t size = ftell(in); std::vector<char> buffer(size); rewind(in); fread(buffer.data(), 1, size, in); fclose(in); std::vector<float> tmp; std::string tmp1 = ""; for(const auto& i : buffer) { if( i == ' ' || i == '\n') { if(tmp1 != "") tmp.emplace_back((float)std::atof(tmp1.c_str())); tmp1 = ""; } else tmp1 += i; } if(tmp1 != "") tmp.emplace_back((float)std::atof(tmp1.c_str())); tmp.shrink_to_fit(); Y = af::array(layout[layout.size() - 1], tmp.size() / layout[layout.size() - 1], tmp.data(), afHost); Y = Y.T(); } void Net::setOutputMatrix(const std::vector<std::vector<float>> &y) { Y = af::array(y.size(), y[0].size()); for(int i = 0; i < y.size(); i++) for(int j = 0; j < y[0].size(); j++) Y(i, j) = y[i][j]; } void Net::setLearningRate(double x) { alpha = x; } void Net::setIterations(int iter) { iterations = iter; } void Net::feedForward() { for(int i = 1; i < layout.size(); i++) A[i] = activations[i-1].first(af::matmul(A[i-1], W[i-1])); } void Net::backPropagate() { for(int i = layout.size() - 1; i > 0; i--) { if(i == layout.size() - 1) { af::array error = A[i] - Y; dA[i] = error * activations[i-1].second(A[i]); W[i-1] = W[i-1] - alpha * af::matmul(A[i-1].T(), dA[i]); } else { dA[i] = af::matmul(dA[i+1], W[i].T()) * activations[i-1].second(A[i]); W[i-1] = W[i-1] - alpha * af::matmul(A[i-1].T(), dA[i]); } } } std::vector<float> Net::getResults() { std::vector<float> res(A[layout.size() - 1].elements()); A[layout.size() - 1].T().host(res.data()); return res; } void Net::train() { for(int iter = 1; iter <= iterations; iter++) { feedForward(); backPropagate(); if(iter % 1000 == 0) { af::array error = A[layout.size() - 1] - Y; af::array mean = af::mean(error); std::cout<<"After "<<iter<<" iterations, error =\n"; af_print(mean); } } } void Net::predict(const std::vector<std::vector<float>> &x) { setInputMatrix(x); feedForward(); } void Net::setActivationFunction(int layer, af::array(*acti)(const af::array&), af::array(*actiDerivative)(const af::array&)) { activations[layer - 1] = std::make_pair(acti, actiDerivative); } void Net::save(std::string pathname) { std::string tmp = "layer"; for(int i = 0; i < W.size(); i++) { std::string key = tmp + std::to_string(i); if(i == 0) af::saveArray(key.c_str(), W[i], pathname.c_str()); else af::saveArray(key.c_str(), W[i], pathname.c_str(), true); } } void Net::loadModel(std::string pathname) { std::string tmp = "layer"; for(int i = 0; i < W.size(); i++) { std::string key = tmp + std::to_string(i); W[i] = af::readArray(pathname.c_str(), key.c_str()); } } void Net::shuffle() { std::mt19937_64 rng; rng.seed(std::random_device()()); std::vector<int> index(A[0].dims(0)); for(int i = 0; i < index.size(); i++) index[i] = i; std::shuffle(index.begin(), index.end(), rng); shuffleInput(index); shuffleOutput(index); } void Net::shuffleInput(const std::vector<int> &indices) { af::array tmp(A[0].dims(0), A[0].dims(1)); for(int i = 0; i < indices.size(); i++) tmp(i, af::span) = A[0](indices[i], af::span); A[0] = tmp; } void Net::shuffleOutput(const std::vector<int> &indices) { af::array tmp(Y.dims(0), Y.dims(1)); for(int i = 0; i < indices.size(); i++) tmp(i, af::span) = Y(indices[i], af::span); Y = tmp; }
[ "rohanmarkgomes@gmail.com" ]
rohanmarkgomes@gmail.com
234d48feba811309895d5e6181d15d197614a41e
dcfe8989affa812a26aa672f5bf81923666ea2c3
/libs/ofxLineaDeTiempo/src/View/TimeRuler.cpp
4e267cda13edf7db992b1c766dec7ce8a3eeb0f1
[ "MIT" ]
permissive
Jonathhhan/ofxLineaDeTiempo
ea7753e5c29595ec11d2e8088b87b5a7e42b3afb
cefbfe790370bc85a6c0111204eecdfb1bb2d5fc
refs/heads/master
2023-06-25T18:24:00.361585
2023-02-08T13:33:24
2023-02-08T13:33:24
577,052,060
0
0
null
null
null
null
UTF-8
C++
false
false
4,747
cpp
// // TimeRuler.cpp // tracksAndTimeTest // // Created by Roy Macdonald on 4/2/20. // #include "LineaDeTiempo/View/TimeRuler.h" #include "LineaDeTiempo/View/TracksPanel.h" #include "LineaDeTiempo/Utils/ConstVars.h" #include "MUI/Constants.h" #include <chrono> #include "ofMath.h" namespace ofx { namespace LineaDeTiempo { //========================================================================================================== TimeRuler::TimeRuler(TracksPanel* panel, TimeControl* timeControl, const ofRectangle& rect, MUI::ZoomScrollbar * scrollbar) : DOM::Element("timeRuler", rect) , _panel(panel) , _timeControl(timeControl) , _scrollbar(scrollbar) { _header = addChild<TimeRulerHeader>(ofRectangle (0, 0, _panel->getTracksHeaderWidth(), ConstVars::TimeRulerInitialHeight), panel, timeControl); _header->updateLayout(); _bar = addChild<TimeRulerBar>( this, timeControl); _playhead = addChild<Playhead>(this, timeControl, _bar); _playhead->updatePosition(); _totalTimeLoopButtons = addChild<TimeControlView>(ofRectangle (rect.getMaxX()-MUI::ConstVars::getScrollBarSize(), 0, MUI::ConstVars::getScrollBarSize() + MUI::ConstVars::getContainerMargin(), ConstVars::TimeRulerInitialHeight), panel, timeControl, DOM::VERTICAL); _totalTimeLoopButtons->add(SET_TOTAL_TIME_BUTTON); _totalTimeLoopButtons->add(SPACER); _totalTimeLoopButtons->add(LOOP_TOGGLE); _totalTimeListener = _timeControl->totalTimeChangedEvent.newListener(this, &TimeRuler::_totalTimeChanged, std::numeric_limits<int>::lowest()); if(_scrollbar) { _horizontalZoomScrollbarListener = _scrollbar->handleChangeEvent.newListener(this, &TimeRuler::_horizontalZoomChanged, std::numeric_limits<int>::lowest()); } else { ofLogError("TimeRuler::TimeRuler") << "TracksView horizontal scrollbar is nullptr. This shouldnt happen"; } _updateVisibleTimeRange(); updateLayout(); setDrawChildrenOnly(true); moveToFront(); _playhead->moveToFront(); } void TimeRuler::_horizontalZoomChanged(ofRange& zoom) { _updateVisibleTimeRange(); } void TimeRuler::_updateVisibleTimeRange() { if(_scrollbar) { auto zoom = _scrollbar->getValue(); auto tt = _timeControl->getTotalTime(); _visibleTimeRange.min = ofMap(zoom.min, 0, 1, 0, tt, true ); _visibleTimeRange.max = ofMap(zoom.max, 0, 1, 0, tt, true ); _setBarShape(true); } } void TimeRuler::_setBarShape(bool dontCheck) { if(_bar && _panel && _panel->getTracksView()) { auto cv = _panel->getTracksView()->getClippingView(); if(cv){ float x = cv->getX() + _header->getWidth(); if( dontCheck || !ofIsFloatEqual(x, _bar->getX()) || !ofIsFloatEqual(cv->getWidth(), _bar->getWidth())) { _bar->setShape({x, 0, cv->getWidth(), ConstVars::TimeRulerInitialHeight}); _bar->makeRulerLines(); if(_playhead) _playhead->updatePosition(); } } } } void TimeRuler::updateLayout() { if(_panel && _header && _bar) { auto w = _panel->getTracksHeaderWidth(); if(! ofIsFloatEqual(w, _header->getWidth()) || ! ofIsFloatEqual(ConstVars::TimeRulerInitialHeight.get(), _header->getHeight()) ){ _header->setShape({0, 0, w, ConstVars::TimeRulerInitialHeight}); _header->updateLayout(); } _setBarShape(); if(_totalTimeLoopButtons) { _totalTimeLoopButtons->setShape(ofRectangle (_bar->getShape().getMaxX() , 0, MUI::ConstVars::getScrollBarSize() + MUI::ConstVars::getContainerMargin(), ConstVars::TimeRulerInitialHeight)); } if(_panel->getTracksView() && _panel->getTracksView()->getClippingView()) { float h = _panel->getTracksView()->getClippingView()->getScreenShape().getMaxY() - getScreenY(); setPlayheadHeight(h); } } } float TimeRuler::timeToScreenPosition(uint64_t time) const { if(_bar) { auto s = _bar->getScreenShape(); return MUI::Math::lerp(time, _visibleTimeRange.min, _visibleTimeRange.max, s.getMinX(), s.getMaxX()); } return 0; } uint64_t TimeRuler::screenPositionToTime(float x) const { if(_bar) { auto s = _bar->getScreenShape(); return MUI::Math::lerp(x, s.getMinX(), s.getMaxX(), _visibleTimeRange.min, _visibleTimeRange.max); } return 0; } void TimeRuler::setPlayheadHeight(float height) { if(_playhead){ _playhead->setHeight(height); _playhead->moveToFront(); } } const ofRange64u & TimeRuler::getVisibleTimeRange() const { return _visibleTimeRange; } void TimeRuler::_totalTimeChanged() { _updateVisibleTimeRange(); updateLayout(); } void TimeRuler::printStatus() { std::cout << "TimeRuler status: _visibleTimeRange: " << _visibleTimeRange << " totalTime: " << _timeControl->getTotalTime(); if(_bar) { std::cout << " bar screenShape: " << _bar->getScreenShape(); } std::cout << "\n"; } } } // ofx::LineaDeTiempo
[ "macdonald.roy@gmail.com" ]
macdonald.roy@gmail.com
9a3f06337cdf6fcc701729338549e46c62fc57b3
97aab27d4410969e589ae408b2724d0faa5039e2
/SDK/EXES/INSTALL VISUAL 6 SDK/INPUT/6.0_980820/MSDN/VCPP/SMPL/MSDN98/98VSa/1036/SAMPLES/VC98/sdk/graphics/video/dseqfile/factory.cpp
c997da3df811fa3d1d1f8a8b078e1c7fa4f1d024
[]
no_license
FutureWang123/dreamcast-docs
82e4226cb1915f8772418373d5cb517713f858e2
58027aeb669a80aa783a6d2cdcd2d161fd50d359
refs/heads/master
2021-10-26T00:04:25.414629
2018-08-10T21:20:37
2018-08-10T21:20:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,885
cpp
/************************************************************************** * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * * Copyright (C) 1992 - 1997 Microsoft Corporation. All Rights Reserved. * **************************************************************************/ #define _INC_OLE #include <windows.h> #include <windowsx.h> #include <mmsystem.h> #include <string.h> #include <ole2.h> #define INITGUID #include <initguid.h> // Bring in the external GUIDs we need.... //DEFINE_OLEGUID(IID_IUnknown, 0x00000000L, 0, 0); //DEFINE_OLEGUID(IID_IClassFactory, 0x00000001L, 0, 0); //DEFINE_OLEGUID(IID_IMarshal, 0x00000003L, 0, 0); #include <vfw.h> #include "handler.h" HMODULE ghModule = NULL; // global HMODULE/HINSTANCE for resource access /* - - - - - - - - */ EXTERN_C BOOL APIENTRY DllMain(HANDLE, DWORD, LPVOID); EXTERN_C BOOL APIENTRY DllMain( HANDLE hModule, DWORD dwReason, LPVOID lpReserved ) { switch( dwReason) { case DLL_PROCESS_ATTACH: if(ghModule == NULL) ghModule = (HMODULE)hModule; break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } return TRUE; } /* - - - - - - - - */ EXTERN_C BOOL FAR PASCAL WEP( BOOL fSystemExit) { return TRUE; } /* - - - - - - - - */ STDAPI DllCanUnloadNow( void) { return ResultFromScode((fLocked || uUseCount) ? S_FALSE : S_OK); } /* - - - - - - - - */ STDAPI DllGetClassObject( const CLSID FAR& rclsid, const IID FAR& riid, void FAR* FAR* ppv) { HRESULT hresult; hresult = CAVIFileCF::Create(rclsid, riid, ppv); return hresult; } /* - - - - - - - - */ HRESULT CAVIFileCF::Create( const CLSID FAR& rclsid, const IID FAR& riid, void FAR* FAR* ppv) { CAVIFileCF FAR* pAVIFileCF; IUnknown FAR* pUnknown; HRESULT hresult; pAVIFileCF = new FAR CAVIFileCF(rclsid, &pUnknown); if (pAVIFileCF == NULL) return ResultFromScode(E_OUTOFMEMORY); hresult = pUnknown->QueryInterface(riid, ppv); if (FAILED(GetScode(hresult))) delete pAVIFileCF; return hresult; } /* - - - - - - - - */ CAVIFileCF::CAVIFileCF( const CLSID FAR& rclsid, IUnknown FAR* FAR* ppUnknown) { m_clsid = rclsid; m_refs = 0; *ppUnknown = this; } /* - - - - - - - - */ STDMETHODIMP CAVIFileCF::QueryInterface( const IID FAR& iid, void FAR* FAR* ppv) { if (iid == IID_IUnknown) *ppv = this; else if (iid == IID_IClassFactory) *ppv = this; else return ResultFromScode(E_NOINTERFACE); AddRef(); return NULL; } /* - - - - - - - - */ STDMETHODIMP_(ULONG) CAVIFileCF::AddRef() { return ++m_refs; } /* - - - - - - - - */ STDMETHODIMP_(ULONG) CAVIFileCF::Release() { if (!--m_refs) { delete this; return 0; } return m_refs; } /* - - - - - - - - */ STDMETHODIMP CAVIFileCF::CreateInstance( IUnknown FAR* pUnknownOuter, const IID FAR& riid, void FAR* FAR* ppv) { HRESULT hresult; // Actually create a real object using the CAVIFile class.... // !!! We should really make sure they're using IAVIFile or IMarshal! if (m_clsid == CLSID_DIBSEQFileReader) { hresult = CAVIFile::Create(pUnknownOuter, riid, ppv); return hresult; } else { return ResultFromScode(E_UNEXPECTED); } } /* - - - - - - - - */ STDMETHODIMP CAVIFileCF::LockServer( BOOL fLock) { fLocked = fLock; return NULL; } /* - - - - - - - - */
[ "david.koch@9online.fr" ]
david.koch@9online.fr
b1922a177f869e997eecdfbde6461c7a2cc17df7
36b3f72ce8db957ad174235dcae57269a1dfd67f
/CAL-PROJ/src/TSPNearestNeighbor.h
42cafe831ad712e367c70eece39f8d29fd2d7004
[]
no_license
Revuj/HealthCarrier
d4e7f7cba7fcdff944d9561470138c6953a7ed05
38ccf2cf98b3e778342500682a0cd7e147c19042
refs/heads/master
2022-01-15T17:41:41.595912
2019-06-21T15:05:38
2019-06-21T15:05:38
193,113,897
0
0
null
null
null
null
UTF-8
C++
false
false
6,819
h
#ifndef CAL_TSPNEARESTNEIGHBOR_H #define CAL_TSPNEARESTNEIGHBOR_H #include <unordered_set> #include <list> #include "DFS.h" #include "AStar.h" using namespace std; #define INFINITE_DOUBLE std::numeric_limits<double>::max() template<class T> class TSPNearestNeighbor { private: // Data Structures Graph<T> map; DFS<T> dfs; VertexHashTable<T> pois; vector<T> visitOrder; vector<T> lastSolution; // Variables for current calculation Vertex<T> finishNode; Vertex<T> startNode; double solutionTotalCost = INFINITE_DOUBLE; unsigned int visitOrderFinalSize = 0; // Verifies if nodes to visit are valid : throws InvalidNodeId(id) if invalid node is found! void verifyValidNodes(const vector<T> & pointsOfInterest); // Returns the closest node to 'node' in the 'otherNodes' hash table Vertex<T> getClosestNode(const Vertex<T> & node, const VertexHashTable<T> otherNodes) const; // Adds 'node' to the visit order void addToVisitOrder(const Vertex<T> & node); // Removes 'node' from the visit order void removeFromVisitOrder(const Vertex<T> & node); // Builds the path by performing A-Star algorithm between the nodes in the visitOrder, in the corret order void buildSolution(); // Appends two vectors void append_vector(vector<T> & v1, const vector<T> & v2); // Initializes Data Structures for algorithm to operate void initDataStructures(); public: TSPNearestNeighbor(const Graph<T> &graph); // Finds the best visit order between start and finish, placing that order in the 'visitOrder' list void findBestVisitOrder(const Vertex<T> & start, const Vertex<T> & finish); // Calculates path between two nodes, passing through all the points of interest vector<T> calcPath(int startNodeId, int finishNodeId, const vector<T> & pois); // Calculates path between two nodes, passing through all the points of interest vector<T> calcPathWithCondition(int startNodeId, int finishNodeId, const vector<T> & pointsOfInterest); // Returns a vector with the Points of Interest Visit Order vector<T> getVisitOrder() const; // Returns the solution weight, if there is a solution at the present moment double getSolutionWeight() const; }; template<class T> TSPNearestNeighbor<T>::TSPNearestNeighbor(const Graph<T> &graph) : map(graph), dfs() { dfs.setGraph(map); } template<class T> vector<T> TSPNearestNeighbor<T>::calcPath(int startNodeId, int finishNodeId, const vector<T> & pointsOfInterest) { initDataStructures(); startNode = *map.getVertex(startNodeId); finishNode = *map.getVertex(finishNodeId); verifyValidNodes(pointsOfInterest); // When the visit order list is complete it should have the startNodeId + all the POIS ids in the correct order + finishNodeId visitOrderFinalSize = 2 + pois.size(); findBestVisitOrder(startNode, finishNode); visitOrder.push_back(finishNodeId); // There was no possible path. if (visitOrder.size() != visitOrderFinalSize) { lastSolution.clear(); std::cout << "Impossible Path" << std::endl; return lastSolution; } else { buildSolution(); return lastSolution; } } template<class T> vector<T> TSPNearestNeighbor<T>::calcPathWithCondition(int startNodeId, int finishNodeId, const vector<T> & pointsOfInterest) { initDataStructures(); startNode = *map.getVertex(startNodeId); finishNode = *map.getVertex(finishNodeId); verifyValidNodes(pointsOfInterest); // When the visit order list is complete it should have the startNodeId + all the POIS ids in the correct order + finishNodeId visitOrderFinalSize = 2 + pois.size(); findBestVisitOrder(startNode, finishNode); visitOrder.push_back(finishNodeId); // There was no possible path. if (visitOrder.size() != visitOrderFinalSize) { lastSolution.clear(); std::cout << "BAD PATH" << std::endl; return lastSolution; } else { buildSolution(); return lastSolution; } } template<class T> double TSPNearestNeighbor<T>::getSolutionWeight() const { return solutionTotalCost; } template<class T> void TSPNearestNeighbor<T>::initDataStructures() { visitOrder.clear(); lastSolution.clear(); pois.clear(); } template<class T> void TSPNearestNeighbor<T>::verifyValidNodes( const vector<T> & pointsOfInterest) { for (T id : pointsOfInterest) { if (id != startNode.getInfo() && id != finishNode.getInfo()) { pois.insert(*map.getVertex(id)); } } } template<class T> void TSPNearestNeighbor<T>::findBestVisitOrder(const Vertex<T> & start, const Vertex<T> & finish) { // All are reachable from this node -> Add it to the visit order list and removed it from the POIs hash table addToVisitOrder(start); Vertex<T> closestNode; VertexHashTable<T> poisToVisit = pois; while (!poisToVisit.empty()) { closestNode = getClosestNode(startNode, poisToVisit); findBestVisitOrder(closestNode, finishNode); // If the list is not complete, the current order does not provide a possible path if (visitOrder.size() != visitOrderFinalSize - 1) { poisToVisit.erase(closestNode); } else { return; } } // Perform back-tracking if solution wasn't achieved if (visitOrder.size() != visitOrderFinalSize - 1) { removeFromVisitOrder(start); } return; } template<class T> void TSPNearestNeighbor<T>::addToVisitOrder(const Vertex<T> & node) { visitOrder.push_back(node.getInfo()); pois.erase(node); } template<class T> void TSPNearestNeighbor<T>::removeFromVisitOrder(const Vertex<T> & node) { visitOrder.pop_back(); pois.insert(node); } template<class T> Vertex<T> TSPNearestNeighbor<T>::getClosestNode(const Vertex<T> & node, const VertexHashTable<T> otherNodes) const { Vertex<T> closestNode = *(otherNodes.begin()); double closestNodeDistance = node.getDistanceToOtherVertex(closestNode); double dist; for (Vertex<T> n : otherNodes) { dist = node.getDistanceToOtherVertex(n); if (dist < closestNodeDistance) { closestNode = n; closestNodeDistance = dist; } } return closestNode; } template<class T> void TSPNearestNeighbor<T>::buildSolution() { AStar<T> astar(map); solutionTotalCost = 0; for (int i = 0; i < visitOrder.size() - 1; i++) { append_vector(lastSolution, astar.calcOptimalPath(visitOrder.at(i), visitOrder.at(i + 1))); solutionTotalCost += astar.getSolutionWeight(); if (i != visitOrder.size() - 2) { lastSolution.pop_back(); } } } template<class T> void TSPNearestNeighbor<T>::append_vector(vector<T> & v1, const vector<T> & v2) { for (int i : v2) { v1.push_back(i); } } template<class T> vector<T> TSPNearestNeighbor<T>::getVisitOrder() const { return this->visitOrder; } #endif //CAL_TSPNEARESTNEIGHBOR_H
[ "revuj112@gmail.com" ]
revuj112@gmail.com
08a851fa1bfea7b4081c0f0388bc4416baa89e95
495cad2bc9ceb5bda14ed083728f4cd9a1aba241
/vehicle-sensor/sound.ino
4010241cbece6271bcae821dd44672e254329bdf
[ "MIT" ]
permissive
pedroetb/fixed-parking-sensor
1861f58f82b81714b7e95047ef170946d5497520
e12c45d077a16df3f98ebbfca50735f5d286e2f5
refs/heads/master
2022-02-10T04:54:33.376202
2019-06-09T22:04:46
2019-06-09T22:04:46
119,109,892
2
0
null
null
null
null
UTF-8
C++
false
false
1,799
ino
constexpr uint8_t buzzerPin = 3; constexpr uint16_t highFrequency = 1000; constexpr uint16_t mediumFrequency = 600; constexpr uint16_t lowFrequency = 400; constexpr uint16_t longDistanceThreshold = 350; constexpr uint16_t mediumDistanceThreshold = 200; constexpr uint16_t shortDistanceThreshold = 15; constexpr uint16_t toneDurationBasis = 500; constexpr uint16_t toneShortDistanceDuration = 2 * toneDurationBasis; constexpr uint8_t toneMediumDistanceDurationFactor = 3; constexpr uint16_t toneLongDistanceDuration = 6 * toneDurationBasis; uint32_t lastSoundMillis = 0; uint16_t currentToneDelay = 0; void soundSetup() { pinMode(buzzerPin, OUTPUT); } void emitAcousticSignals(uint16_t distanceInCm) { if (millis() < (lastSoundMillis + currentToneDelay)) { return; } lastSoundMillis = millis(); evaluateDistanceToEmitTone(distanceInCm); } void evaluateDistanceToEmitTone(uint16_t distanceInCm) { if ((distanceInCm <= 0) || (distanceInCm >= longDistanceThreshold)) { stopAcousticSignals(); } else if (distanceInCm < shortDistanceThreshold) { emitShortRangeTone(); } else if (distanceInCm < mediumDistanceThreshold) { emitMediumRangeTone(distanceInCm); } else if (distanceInCm < longDistanceThreshold) { emitLongRangeTone(); } } void stopAcousticSignals() { noTone(buzzerPin); } void emitShortRangeTone() { tone(buzzerPin, highFrequency, toneShortDistanceDuration); currentToneDelay = toneShortDistanceDuration - 10; } void emitMediumRangeTone(uint16_t distanceInCm) { uint16_t toneDuration = toneMediumDistanceDurationFactor * distanceInCm; tone(buzzerPin, mediumFrequency, toneDuration); currentToneDelay = 2 * toneDuration; } void emitLongRangeTone() { tone(buzzerPin, lowFrequency, toneDurationBasis); currentToneDelay = toneLongDistanceDuration; }
[ "pedroetb@gmail.com" ]
pedroetb@gmail.com
370bc538cdcc35da839c9eb3833086b7f2db29a3
cc1db5ea34700d9f3e397251fe2fa67838041202
/JSON/JSON/JSON_Object.cpp
5c1b1fcf08114e5f80ec76fd49a2b04b71f33ad8
[]
no_license
karolmikolajczuk/JSONParser
de69e7f9d292ebb2f7d23055802e0dade3eec5e4
2706bb0a40c93a15be7c613ba329085e8fc0f1e6
refs/heads/master
2020-09-26T07:27:25.996044
2020-03-25T22:09:04
2020-03-25T22:09:04
226,203,117
0
0
null
null
null
null
UTF-8
C++
false
false
4,798
cpp
#include "JSON_Object.h" #include <iostream> #define FLOW(text) std::cout << __FUNCTION__ << text << std::endl; JSON_Object::JSON_Object() : key_values{ } { } JSON_Object::JSON_Object(KEY key, VALUE value) : key_values{ } { this->key_values[key] = value; } RESULT JSON_Object::getValue(KEY key) { std::cout << "Looking for: " << key << std::endl; // dla kazdej pary z mapy for (const auto& pair : this->key_values) { // sprawdz klucz, czy to jest taki sam std::cout << "Printing key: " << pair.first << std::endl; if (pair.first == key) { if (pair.second.type() == typeid(std::string)) { std::cout << "Returning this value: " << std::any_cast<std::string>(pair.second); return std::any_cast<std::string>(pair.second); } else if (pair.second.type() == typeid(JSON_Object*)) { std::cout << "Returning this value: " << __LINE__; return std::any_cast<JSON_Object*>(pair.second); } else if (pair.second.type() == typeid(std::list<std::string>)) { std::cout << "Returning this value: " << __LINE__; return std::any_cast<std::list<std::string>>(pair.second); } else if (pair.second.type() == typeid(std::map<std::string, std::any>)) { std::cout << "Returning this value: " << __LINE__; return std::any_cast<std::map<std::string, std::any>>(pair.second); } } else if (pair.second.type() == typeid(JSON_Object*)) { std::any returned = std::any_cast<JSON_Object*>(pair.second)->getValue(key); if (returned.type() == typeid(std::string)) { std::cout << "Returning this value: " << std::any_cast<std::string>(returned); return std::any_cast<std::string>(returned); } else if (returned.type() == typeid(JSON_Object*)) { std::cout << "Returning this value: " << __LINE__; return std::any_cast<JSON_Object*>(returned); } else if (returned.type() == typeid(std::list<std::string>)) { std::cout << "Returning this value: " << __LINE__; return std::any_cast<std::list<std::string>>(returned); } else if (returned.type() == typeid(std::map<std::string, std::any>)) { std::cout << "Returning this value: " << __LINE__; return std::any_cast<std::map<std::string, std::any>>(returned); } } } std::cout << "Returning this value: " << __LINE__; return { }; } void JSON_Object::putData(KEY key, VALUE value) { try { this->key_values[key] = value; } catch (std::exception& exc) { FLOW(exc.what()); } } static int tabs = 0; void JSON_Object::printData() { for (auto& key_value : this->key_values) { //FLOW(key_value.second.type().name()); for (int i = 0; i < tabs; ++i) std::cout << '\t'; std::cout << key_value.first << " : "; if (key_value.second.type() == typeid(std::string)) { std::cout << std::any_cast<std::string>(key_value.second) << std::endl; } else if (key_value.second.type() == typeid(JSON_Object*)) { ++tabs; std::cout << "{\n"; std::any_cast<JSON_Object*>(key_value.second)->printData(); } else if (key_value.second.type() == typeid(std::list<std::string>)) { std::cout << "[ "; for (auto val : std::any_cast<std::list<std::string>>(key_value.second)) { std::cout << val << " "; } std::cout << "]\n"; } else if (key_value.second.type() == typeid(std::map<std::string, std::string>)) { std::cout << "[\n"; for (auto val : std::any_cast<std::map<std::string, std::string>>(key_value.second)) { std::cout << val.first << ": " << val.second << std::endl; } std::cout << "]\n"; } else if (key_value.second.type() == typeid(std::map<std::string, std::any>)) { std::cout << "[\n"; for (auto pair_map : std::any_cast<std::map<std::string, std::any>>(key_value.second)) { std::cout << pair_map.first << ": "; if (pair_map.second.type() == typeid(std::string)) { std::cout << std::any_cast<std::string>(pair_map.second) << std::endl; } else if (pair_map.second.type() == typeid(JSON_Object*)) { std::cout << "{\n"; std::any_cast<JSON_Object*>(pair_map.second)->printData(); } else if (pair_map.second.type() == typeid(std::list<std::string>)) { std::cout << "[ "; for (auto val : std::any_cast<std::list<std::string>>(pair_map.second)) { std::cout << val << " "; } std::cout << "]\n"; } else if (pair_map.second.type() == typeid(std::map<std::string, std::string>)) { std::cout << "[\n"; for (auto val : std::any_cast<std::map<std::string, std::string>>(key_value.second)) { std::cout << val.first << ": " << val.second << std::endl; } std::cout << "]\n"; } } std::cout << "]\n"; } } --tabs; } void JSON_Object::printResult(RESULT result) { std::string toPrint = ""; toPrint = std::get<std::string>(result); std::cout << "Value: " << toPrint << std::endl; }
[ "karol.mikolajczuk@outlook.com" ]
karol.mikolajczuk@outlook.com
28075bc4704823013b4634eabd53f0e1b48fd824
4d86256d7dcc97cc2804c66d862192b8dfee2e78
/Physika_Src/Physika_Dynamics/ParticleSystem/INeighbors.h
e9f64d6a45feda4f2be60d2102edb40e4de50a21
[]
no_license
cenyc/Physika_BUAA
ca478682097550a2e7cc087dcf8b2f27ac58d4b3
527f8bd89eaa2ef32082a6ff52b7c8da3a327497
refs/heads/master
2020-03-28T13:38:18.504661
2019-04-15T11:25:15
2019-04-15T11:25:15
148,413,092
0
2
null
null
null
null
UTF-8
C++
false
false
623
h
#pragma once #include <vector_types.h> #include "Platform.h" namespace Physika { #define NEIGHBOR_SIZE 30 class NeighborList { public: HYBRID_FUNC NeighborList() { size = 0; } HYBRID_FUNC ~NeighborList() {}; HYBRID_FUNC int& operator[] (int id) { return ids[id]; } HYBRID_FUNC int operator[] (int id) const { return ids[id]; } public: int size; int ids[NEIGHBOR_SIZE]; }; class RestShape { public: HYBRID_FUNC RestShape() { size = 0; } HYBRID_FUNC ~RestShape() {}; public: int size; int idx; int ids[NEIGHBOR_SIZE]; float distance[NEIGHBOR_SIZE]; float3 pos[NEIGHBOR_SIZE]; }; }
[ "14007653@qq.com" ]
14007653@qq.com
4fd26a70a7abcd3f5222a65111199f8e1b57ac72
5cad8d9664c8316cce7bc57128ca4b378a93998a
/CI/rule/pclint/pclint_include/include_linux/c++/4.3/ext/pb_ds/detail/ov_tree_map_/node_iterators.hpp
5b9f9a873aa1de54bfa01d7bde8258d4dcea811e
[ "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "GPL-3.0-only", "curl", "Zlib", "LicenseRef-scancode-warranty-disclaimer", "OpenSSL", "GPL-1.0-or-later", "MIT", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "BSD-3-...
permissive
huaweicloud/huaweicloud-sdk-c-obs
0c60d61e16de5c0d8d3c0abc9446b5269e7462d4
fcd0bf67f209cc96cf73197e9c0df143b1d097c4
refs/heads/master
2023-09-05T11:42:28.709499
2023-08-05T08:52:56
2023-08-05T08:52:56
163,231,391
41
21
Apache-2.0
2023-06-28T07:18:06
2018-12-27T01:15:05
C
UTF-8
C++
false
false
9,108
hpp
// -*- C++ -*- // Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 2, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // You should have received a copy of the GNU General Public License // along with this library; see the file COPYING. If not, write to // the Free Software Foundation, 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA. // As a special exception, you may use this file as part of a free // software library without restriction. Specifically, if other files // instantiate templates or use macros or inline functions from this // file, or you compile this file and link it with other files to // produce an executable, this file does not by itself cause the // resulting executable to be covered by the GNU General Public // License. This exception does not however invalidate any other // reasons why the executable file might be covered by the GNU General // Public License. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file node_iterators.hpp * Contains an implementation class for ov_tree_. */ #ifndef PB_DS_OV_TREE_NODE_ITERATORS_HPP #define PB_DS_OV_TREE_NODE_ITERATORS_HPP #include <ext/pb_ds/tag_and_trait.hpp> #include <ext/pb_ds/detail/type_utils.hpp> #include <debug/debug.h> namespace __gnu_pbds { namespace detail { #define PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC \ ov_tree_node_const_it_<Value_Type, Metadata_Type, Allocator> // Const node reference. template<typename Value_Type, typename Metadata_Type, class Allocator> class ov_tree_node_const_it_ { protected: typedef typename Allocator::template rebind< Value_Type>::other::pointer pointer; typedef typename Allocator::template rebind< Value_Type>::other::const_pointer const_pointer; typedef typename Allocator::template rebind< Metadata_Type>::other::const_pointer const_metadata_pointer; typedef PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC this_type; protected: template<typename Ptr> inline static Ptr mid_pointer(Ptr p_begin, Ptr p_end) { _GLIBCXX_DEBUG_ASSERT(p_end >= p_begin); return (p_begin + (p_end - p_begin) / 2); } public: typedef trivial_iterator_tag iterator_category; typedef trivial_iterator_difference_type difference_type; typedef typename Allocator::template rebind< Value_Type>::other::const_pointer value_type; typedef typename Allocator::template rebind< typename remove_const< Value_Type>::type>::other::const_pointer reference; typedef typename Allocator::template rebind< typename remove_const< Value_Type>::type>::other::const_pointer const_reference; typedef Metadata_Type metadata_type; typedef typename Allocator::template rebind< metadata_type>::other::const_reference const_metadata_reference; public: inline ov_tree_node_const_it_(const_pointer p_nd = NULL, const_pointer p_begin_nd = NULL, const_pointer p_end_nd = NULL, const_metadata_pointer p_metadata = NULL) : m_p_value(const_cast<pointer>(p_nd)), m_p_begin_value(const_cast<pointer>(p_begin_nd)), m_p_end_value(const_cast<pointer>(p_end_nd)), m_p_metadata(p_metadata) { } inline const_reference operator*() const { return m_p_value; } inline const_metadata_reference get_metadata() const { enum { has_metadata = !is_same<Metadata_Type, null_node_metadata>::value }; PB_DS_STATIC_ASSERT(should_have_metadata, has_metadata); _GLIBCXX_DEBUG_ASSERT(m_p_metadata != NULL); return *m_p_metadata; } inline this_type get_l_child() const { if (m_p_begin_value == m_p_value) return (this_type(m_p_begin_value, m_p_begin_value, m_p_begin_value)); const_metadata_pointer p_begin_metadata = m_p_metadata - (m_p_value - m_p_begin_value); return (this_type(mid_pointer(m_p_begin_value, m_p_value), m_p_begin_value, m_p_value, mid_pointer(p_begin_metadata, m_p_metadata))); } inline this_type get_r_child() const { if (m_p_value == m_p_end_value) return (this_type(m_p_end_value, m_p_end_value, m_p_end_value)); const_metadata_pointer p_end_metadata = m_p_metadata + (m_p_end_value - m_p_value); return (this_type(mid_pointer(m_p_value + 1, m_p_end_value), m_p_value + 1, m_p_end_value,(m_p_metadata == NULL) ? NULL : mid_pointer(m_p_metadata + 1, p_end_metadata))); } inline bool operator==(const this_type& other) const { const bool is_end = m_p_begin_value == m_p_end_value; const bool is_other_end = other.m_p_begin_value == other.m_p_end_value; if (is_end) return (is_other_end); if (is_other_end) return (is_end); return m_p_value == other.m_p_value; } inline bool operator!=(const this_type& other) const { return !operator==(other); } public: pointer m_p_value; pointer m_p_begin_value; pointer m_p_end_value; const_metadata_pointer m_p_metadata; }; #define PB_DS_OV_TREE_NODE_ITERATOR_C_DEC \ ov_tree_node_it_<Value_Type, Metadata_Type, Allocator> // Node reference. template<typename Value_Type, typename Metadata_Type, class Allocator> class ov_tree_node_it_ : public PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC { private: typedef PB_DS_OV_TREE_NODE_ITERATOR_C_DEC this_type; typedef PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC base_type; typedef typename base_type::pointer pointer; typedef typename base_type::const_pointer const_pointer; typedef typename base_type::const_metadata_pointer const_metadata_pointer; public: typedef trivial_iterator_tag iterator_category; typedef trivial_iterator_difference_type difference_type; typedef typename Allocator::template rebind< Value_Type>::other::pointer value_type; typedef typename Allocator::template rebind< typename remove_const< Value_Type>::type>::other::pointer reference; typedef typename Allocator::template rebind< typename remove_const< Value_Type>::type>::other::pointer const_reference; public: inline ov_tree_node_it_(const_pointer p_nd = NULL, const_pointer p_begin_nd = NULL, const_pointer p_end_nd = NULL, const_metadata_pointer p_metadata = NULL) : base_type(p_nd, p_begin_nd, p_end_nd, p_metadata) { } // Access. inline reference operator*() const { return reference(base_type::m_p_value); } // Returns the node reference associated with the left node. inline ov_tree_node_it_ get_l_child() const { if (base_type::m_p_begin_value == base_type::m_p_value) return (this_type(base_type::m_p_begin_value, base_type::m_p_begin_value, base_type::m_p_begin_value)); const_metadata_pointer p_begin_metadata = base_type::m_p_metadata - (base_type::m_p_value - base_type::m_p_begin_value); return (this_type(base_type::mid_pointer(base_type::m_p_begin_value, base_type::m_p_value), base_type::m_p_begin_value, base_type::m_p_value, base_type::mid_pointer(p_begin_metadata, base_type::m_p_metadata))); } // Returns the node reference associated with the right node. inline ov_tree_node_it_ get_r_child() const { if (base_type::m_p_value == base_type::m_p_end_value) return (this_type(base_type::m_p_end_value, base_type::m_p_end_value, base_type::m_p_end_value)); const_metadata_pointer p_end_metadata = base_type::m_p_metadata + (base_type::m_p_end_value - base_type::m_p_value); return (this_type(base_type::mid_pointer(base_type::m_p_value + 1, base_type::m_p_end_value), base_type::m_p_value + 1, base_type::m_p_end_value,(base_type::m_p_metadata == NULL)? NULL : base_type::mid_pointer(base_type::m_p_metadata + 1, p_end_metadata))); } }; #undef PB_DS_OV_TREE_NODE_ITERATOR_C_DEC #undef PB_DS_OV_TREE_CONST_NODE_ITERATOR_C_DEC } // namespace detail } // namespace __gnu_pbds #endif
[ "xiangshijian1@huawei.com" ]
xiangshijian1@huawei.com
1f25cfef4cee99792d78f30d31ac699eec93956b
515fd4af47f6ba2744d3c4b2ca4088b102f08026
/Arduino les 2_1 - knoppen.ino
30182639636f3d894b9e1acbc0928bb9db0febad
[]
no_license
educaris/arduinoBasis
a514981bcccf9f0b0b8d5689dba1f2957c33fa5b
0b6b2a5f73bd86703205318a946aaed25a336465
refs/heads/master
2020-02-26T17:09:02.789759
2016-11-29T20:30:36
2016-11-29T20:30:36
71,658,870
0
0
null
null
null
null
UTF-8
C++
false
false
6,325
ino
/* SparkFun Inventor's Kit Example sketch 05 PUSH BUTTONS Use pushbuttons for digital input Previously we've used the analog pins for input, now we'll use the digital pins for input as well. Because digital pins only know about HIGH and LOW signals, they're perfect for interfacing to pushbuttons and switches that also only have "on" and "off" states. We'll connect one side of the pushbutton to GND, and the other side to a digital pin. When we press down on the pushbutton, the pin will be connected to GND, and therefore will be read as "LOW" by the Arduino. But wait - what happens when you're not pushing the button? In this state, the pin is disconnected from everything, which we call "floating". What will the pin read as then, HIGH or LOW? It's hard to say, because there's no solid connection to either 5 Volts or GND. The pin could read as either one. To deal with this issue, we'll connect a small (10K, or 10,000 Ohm) resistance between the pin and 5 Volts. This "pullup" resistor will ensure that when you're NOT pushing the button, the pin will still have a weak connection to 5 Volts, and therefore read as HIGH. (Advanced: when you get used to pullup resistors and know when they're required, you can activate internal pullup resistors on the ATmega processor in the Arduino. See http://arduino.cc/en/Tutorial/DigitalPins for information.) Hardware connections: Pushbuttons: Pushbuttons have two contacts that are connected if you're pushing the button, and disconnected if you're not. The pushbuttons we're using have four pins, but two pairs of these are connected together. The easiest way to hook up the pushbutton is to connect two wires to any opposite corners. Connect any pin on pushbutton 1 to ground (GND). Connect the opposite diagonal pin of the pushbutton to digital pin 2. Connect any pin on pushbutton 2 to ground (GND). Connect the opposite diagonal pin of the pushbutton to digital pin 3. Also connect 10K resistors (brown/black/red) between digital pins 2 and 3 and GND. These are called "pullup" resistors. They ensure that the input pin will be either 5V (unpushed) or GND (pushed), and not somewhere in between. (Remember that unlike analog inputs, digital inputs are only HIGH or LOW.) LED: Most Arduinos, including the Uno, already have an LED and resistor connected to pin 13, so you don't need any additional circuitry. But if you'd like to connect a second LED to pin 13, Connect the positive side of your LED to Arduino digital pin 13 Connect the negative side of your LED to a 330 Ohm resistor Connect the other side of the resistor to ground This sketch was written by SparkFun Electronics, with lots of help from the Arduino community. This code is completely free for any use. Visit http://learn.sparkfun.com/products/2 for SIK information. Visit http://www.arduino.cc to learn about the Arduino. Version 2.0 6/2012 MDG */ // First we'll set up constants for the pin numbers. // This will make it easier to follow the code below. const int button1Pin = 2; // pushbutton 1 pin const int button2Pin = 3; // pushbutton 2 pin const int ledPin = 13; // LED pin void setup() { // Set up the pushbutton pins to be an input: pinMode(button1Pin, INPUT); pinMode(button2Pin, INPUT); // Set up the LED pin to be an output: pinMode(ledPin, OUTPUT); } void loop() { int button1State, button2State; // variables to hold the pushbutton states // Since a pushbutton has only two states (pushed or not pushed), // we've run them into digital inputs. To read an input, we'll // use the digitalRead() function. This function takes one // parameter, the pin number, and returns either HIGH (5V) // or LOW (GND). // Here we'll read the current pushbutton states into // two variables: button1State = digitalRead(button1Pin); button2State = digitalRead(button2Pin); // Remember that if the button is being pressed, it will be // connected to GND. If the button is not being pressed, // the pullup resistor will connect it to 5 Volts. // So the state will be LOW when it is being pressed, // and HIGH when it is not being pressed. // Now we'll use those states to control the LED. // Here's what we want to do: // "If either button is being pressed, light up the LED" // "But, if BOTH buttons are being pressed, DON'T light up the LED" // Let's translate that into computer code. The Arduino gives you // special logic functions to deal with true/false logic: // A == B means "EQUIVALENT". This is true if both sides are the same. // A && B means "AND". This is true if both sides are true. // A || B means "OR". This is true if either side is true. // !A means "NOT". This makes anything after it the opposite (true or false). // We can use these operators to translate the above sentences // into logic statements (Remember that LOW means the button is // being pressed) // "If either button is being pressed, light up the LED" // becomes: // if ((button1State == LOW) || (button2State == LOW)) // light the LED // "If BOTH buttons are being pressed, DON'T light up the LED" // becomes: // if ((button1State == LOW) && (button2State == LOW)) // don't light the LED // Now let's use the above functions to combine them into one statement: if (((button1State == LOW) || (button2State == LOW)) // if we're pushing button 1 OR button 2 && ! // AND we're NOT ((button1State == LOW) && (button2State == LOW))) // pushing button 1 AND button 2 // then... { digitalWrite(ledPin, HIGH); // turn the LED on } else { digitalWrite(ledPin, LOW); // turn the LED off } // As you can see, logic operators can be combined to make // complex decisions! // Don't forget that we use = when we're assigning a value, // and use == when we're testing a value for equivalence. }
[ "noreply@github.com" ]
noreply@github.com
f760c57aceb5fc0f2080d6142b80aac5117a60d5
b5206449cd89ee9861c83d1bbace55c908996f7e
/code/src/DLine.cxx
3b12b01f54c3989bde6be5d75d37c04e3465a994
[]
no_license
jeromebaudot/taf
396d0b86277f111ba04e3adbeecef2fae6595c70
92f3ea52e545b4509ad3c810041332b5e49c57db
refs/heads/master
2022-05-16T02:29:07.372117
2022-02-19T16:08:42
2022-02-19T16:08:42
129,721,599
1
6
null
2021-06-14T12:25:45
2018-04-16T09:52:37
C
UTF-8
C++
false
false
5,196
cxx
// @(#)maf/dtools:$Name: $:$Id: DLine.cxx,v.1 2005/10/02 18:03:46 sha Exp $ // Author : Dirk Meier 98/01/09 ////////////////////////////////////////////////////////////////////////////////////////////// // // // Class Description of DLine // // // // a Line object is defined by its // // origin = (x_0,y_0,z_0), // // direction = (dx,dy,dz), // // and length. // // Points on the line at r_i are given as a function // // of the parameter beta. beta has no dimension. // // r_i(beta) = origin_i + beta * direction_i // // If one wants the pair (x,y) as a function of z along (0,0,dz) then beta = z/dz // // and r_1(beta) = x_0 + z * dx/dz // // r_2(beta) = y_0 + z * dy/dz // // r_3(beta) = z_0 + z * 1 // // In case one needs pair (x,y,z) as a function of l along (dx,dy,dz) then beta' = l/dl // // and r_1(beta') = x_0 + l * dx/dl // // r_2(beta') = y_0 + l * dy/dl // // r_3(beta') = z_0 + l * dz/dl // // with the relation beta^2 = beta'^2 * (1-x^2/l^2-y^2/l^2) / (1-dx^2/dl^2-dy^2/dl^2) // // // ////////////////////////////////////////////////////////////////////////////////////////////// //*-- Modified : //*-- Copyright: RD42 //*-- Author : Dirk Meier 98/01/09 //*KEEP,CopyRight. // Last Modified: JB 2011/07/25 destructor /************************************************************************ * Copyright(c) 1997, DiamondTracking, RD42@cern.ch ***********************************************************************/ //*KEND. //*KEEP,DLine. #include "DLine.h" //*KEEP,DR3. #include "DR3.h" //*KEND. ClassImp(DLine) // Description of a Line //______________________________________________________________________________ // DLine::DLine(){ fOrigin = new DR3(); fDirection = new DR3(); fSlope = new DR3(); fLength = 0.0; } //______________________________________________________________________________ // DLine::DLine(DR3 &aOrigin, DR3 &aDirection, Float_t aLength){ fOrigin = new DR3(aOrigin); fDirection = new DR3(aDirection); fSlope = new DR3(); fLength = aLength; } //______________________________________________________________________________ // DLine::~DLine(){ // delete instruction modified to avoid crash, JB 2011/07/25 delete fOrigin; delete fDirection; delete fSlope; } //______________________________________________________________________________ // void DLine::SetValue(const DR3& aOrigin, const DR3& aDirection, const DR3& aSlope, const Float_t aLength){ *fOrigin = aOrigin; *fDirection = aDirection; *fSlope = aSlope; fLength = aLength; } //______________________________________________________________________________ // void DLine::Zero(){ fOrigin->Zero(); fDirection->Zero(); fSlope->Zero(); fLength = 0; } //______________________________________________________________________________ // DR3 DLine::GetPoint(Float_t beta){ DR3 result; result = (*fDirection) * beta; return result += *fOrigin; } //______________________________________________________________________________ // DR3 DLine::GetIntersectZ(Float_t aZvalue){ Float_t tDz; DR3 tZero; tDz = GetDirection()(2); if (tDz != 0.) return GetPoint(aZvalue/tDz); else return tZero; } //______________________________________________________________________________ // Float_t DLine::Distance(DR3 &p){ // distance d = sqrt(n_k n_k) between point p_k and line G // with G is set of r_k : r_k = a_k x + b_k ; for all x element R and k = 1..3 // ... now n_i pops out : // n_i = (1_ik - a_i a_k / a^2) (p_k - b_k) ; 1_ik is kronecker's thing // ... which delivers distance d: (note a,b,c,p are 3-Vectors) // d = sqrt(c^2 - 2 (a*c)^2 / a^2 + (a*c)^2) with c = p - b, // * is the scalar vector product // and wire it in: DR3 c; Float_t d; c.SetDifference(p, *fOrigin); d = c.InnerProduct(*fDirection); return sqrt(c.InnerProduct(c) - 2 * d * d / fDirection->InnerProduct(*fDirection) + d * d); }
[ "jerome.baudot@desy.de" ]
jerome.baudot@desy.de
da251a9e56c91956afe12b34544170d4187db265
af7a3b65aedf3c90ce53c23e64ae29217f2ee3f5
/Altera/AlteraDevices.hpp
8dfcaa1286b855cd683bf30125b9bd00d771f893
[ "ISC" ]
permissive
daveshah1/polymer
1609cc7c78537700f7a84289edb40d59806cbc7e
fd0c268d417169f2fb1ddd67bd97648934436d42
refs/heads/master
2020-04-09T14:39:59.710249
2018-12-04T18:48:03
2018-12-04T18:48:03
160,403,783
0
0
null
null
null
null
UTF-8
C++
false
false
1,383
hpp
#pragma once #include <vector> #include <string> #include <map> #include "../LogicDevice.hpp" using namespace std; namespace SynthFramework { namespace Polymer { //Altera fast carry logic class Altera_CarrySum : public VendorSpecificDevice { public: Altera_CarrySum(); Altera_CarrySum(Signal *sin, Signal *cin, Signal *sout, Signal *cout); virtual bool OptimiseDevice(LogicDesign *topLevel); private: static int cscount; }; //Altera single-port ROM primitive class Altera_ROM : public VendorSpecificDevice { public: Altera_ROM(); Altera_ROM(int _width, int _length, string _filename, Signal *clock, vector<Signal*> address, vector<Signal*> data); int width, length; string filename; private: static int romcount; }; //Altera 18x18 embedded multiplier (9x9 mode and registers NYI at the moment) class Altera_Multiplier18 : public VendorSpecificDevice { public: Altera_Multiplier18(); Altera_Multiplier18(vector<Signal*> a, vector<Signal*> b, vector<Signal*> out, bool _sign_a, bool _sign_b); virtual bool OptimiseDevice(LogicDesign *topLevel); bool sign_a, sign_b; private: static int mulcount; int actualsize = 36; //for optimisation purposes }; }; };
[ "dave@ds0.me" ]
dave@ds0.me
28f633a4acee928b8ba8935dafeb5f82c1c79d6a
52860d0eddf1f2f4c2f4a71158c14f51dd448692
/assignment_package/src/scene/materials/bsdf.cpp
dc8dd356b2f2681099c0963dab2b2774c3ce2a04
[]
no_license
hehehaha12139/PhotonMapping
f64d69c30e9857284ccc70d51cf2679050efd111
4b7e47be94708a8dbea5b850781c9a5e4d6d151c
refs/heads/main
2023-02-24T10:28:09.488070
2021-01-29T00:56:11
2021-01-29T00:56:11
333,997,193
0
0
null
null
null
null
UTF-8
C++
false
false
6,041
cpp
#include "bsdf.h" #include <warpfunctions.h> #include "specularreflection.h" #include "specularTransmission.h" BSDF::BSDF(const Intersection& isect, float eta /*= 1*/) //TODO: Properly set worldToTangent and tangentToWorld : worldToTangent(/*COMPUTE ME*/), tangentToWorld(/*COMPUTE ME*/), normal(isect.normalGeometric), eta(eta), numBxDFs(0), bxdfs{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr} { this->UpdateTangentSpaceMatrices(glm::normalize(isect.normalGeometric), isect.tangent, isect.bitangent); } void BSDF::UpdateTangentSpaceMatrices(const Normal3f& n, const Vector3f& t, const Vector3f b) { //TODO: Update worldToTangent and tangentToWorld based on the normal, tangent, and bitangent tangentToWorld = glm::mat3(t, b, n); worldToTangent = glm::transpose(tangentToWorld); } // Color3f BSDF::f(const Vector3f &woW, const Vector3f &wiW, BxDFType flags /*= BSDF_ALL*/) const { //TODO // Transform light direction to tangent space Vector3f woWTangent = worldToTangent * woW; Vector3f wiWTangent = worldToTangent * wiW; Color3f reColor = Color3f(0.0f); // Traverse BxDFs to get color sum for(int i = 0; i < numBxDFs; ++i) { if(bxdfs[i]->MatchesFlags(flags)) { reColor += bxdfs[i]->f(woWTangent, wiWTangent); } } return reColor; } // Use the input random number _xi_ to select // one of our BxDFs that matches the _type_ flags. // After selecting our random BxDF, rewrite the first uniform // random number contained within _xi_ to another number within // [0, 1) so that we don't bias the _wi_ sample generated from // BxDF::Sample_f. // Convert woW and wiW into tangent space and pass them to // the chosen BxDF's Sample_f (along with pdf). // Store the color returned by BxDF::Sample_f and convert // the _wi_ obtained from this function back into world space. // Iterate over all BxDFs that we DID NOT select above (so, all // but the one sampled BxDF) and add their PDFs to the PDF we obtained // from BxDF::Sample_f, then average them all together. // Finally, iterate over all BxDFs and sum together the results of their // f() for the chosen wo and wi, then return that sum. Color3f BSDF::Sample_f(const Vector3f &woW, Vector3f *wiW, const Point2f &xi, float *pdf, BxDFType type, BxDFType *sampledType) const { //TODO // Select random bxdf by xi int num = BxDFsMatchingFlags(type); int bxdfIndex = floor(xi[0] * num); int count = 0; BxDF *selected = nullptr; for(int i = 0; i < numBxDFs; i++) { if(bxdfs[i]->MatchesFlags(type)) { if(count == bxdfIndex) { selected = bxdfs[i]; break; } count++; } } if(sampledType) { *sampledType = selected->type; } // Update new rand for xi float newRand = (float)rand() / (float)RAND_MAX; // Convert world coordinate to local Vector3f woWTangent = worldToTangent * woW; Vector3f wiWTangent = worldToTangent * (*wiW); *pdf = 0.0f; Color3f reColor = Color3f(0.0f, 0.0f, 0.0f); reColor = selected->Sample_f(woWTangent, &wiWTangent, Point2f(newRand, xi[1]), pdf, sampledType); // Given direction's probablity equals to zero, return if(*pdf == 0) { if(sampledType) { *sampledType = BxDFType(0); } return Color3f(0.0f); } // Get new input direction *wiW = tangentToWorld * wiWTangent; float avgPdf = *pdf; *pdf /= num; count = 0; // Skip when given bsdf contains specular material if(!(selected->type & BSDF_SPECULAR)) { // Compute pdf for(int i = 0; i < numBxDFs; i++) { if(bxdfs[i]->MatchesFlags(type)) { if(count == bxdfIndex) { count++; continue; } avgPdf += bxdfs[i]->Pdf(woWTangent, wiWTangent); } } avgPdf = avgPdf / num; *pdf = avgPdf; reColor = Vector3f(0.0f); // Compute all color for(int i = 0; i < numBxDFs; i++) { if(bxdfs[i]->MatchesFlags(type)) { if(typeid(*(bxdfs[i])) == typeid(SpecularReflection) || typeid(*(bxdfs[i])) == typeid(SpecularTransmission)) { Vector3f newWi = wiWTangent; float newPdf = *pdf; reColor += bxdfs[i]->Sample_f(woWTangent, &newWi, Point2f(newRand, xi[1]), &newPdf, sampledType); } reColor += bxdfs[i]->f(woWTangent, wiWTangent); } } } return reColor; } float BSDF::Pdf(const Vector3f &woW, const Vector3f &wiW, BxDFType flags) const { //TODO Vector3f woWTangent = worldToTangent * woW; Vector3f wiWTangent = worldToTangent * wiW; float pdf = 0.0f; // Sum the pdf from bxdfs for(int i = 0; i < numBxDFs; i++) { if(bxdfs[i]->MatchesFlags(flags)) { pdf = bxdfs[i]->Pdf(woWTangent, wiWTangent); } } return pdf / BxDFsMatchingFlags(flags); } Color3f BxDF::Sample_f(const Vector3f &wo, Vector3f *wi, const Point2f &xi, Float *pdf, BxDFType *sampledType) const { //TODO *wi = WarpFunctions::squareToHemisphereUniform(xi); if(wo.z < 0.0f) { *wi *= -1.0f; } *pdf = Pdf(wo, *wi); return f(wo, *wi); } // The PDF for uniform hemisphere sampling float BxDF::Pdf(const Vector3f &wo, const Vector3f &wi) const { return SameHemisphere(wo, wi) ? Inv2Pi : 0; } BSDF::~BSDF() { for(int i = 0; i < numBxDFs; i++) { delete bxdfs[i]; } }
[ "zelda2013e3@gmail.com" ]
zelda2013e3@gmail.com
e24e7dbad900d47721a90481af0d85cd7bae2746
76cda8357593caf4d1688c15e9f11eadcc0a1935
/libraries/Piece/Draw_Game.h
49c0e7e2952ff0f9f7657792ebe34424bc2cef51
[]
no_license
Aonton/Tetris
a6edfe5ba5a4a74fa7f001273afc254b2df5f7e1
3f6c605609be400bdc044ffaf9bee6bc55c45403
refs/heads/master
2021-01-01T18:59:04.439111
2017-08-29T17:04:30
2017-08-29T17:04:30
98,478,899
0
0
null
null
null
null
UTF-8
C++
false
false
353
h
// Header file for the Draw_Game class // Amy Feng // 8.27.2017 #ifndef DRAW_GAME_H #define DRAW_GAME_H #include "Board.h" #include "Types.h" class Draw_Game{ public: Draw_Game(); void Draw_Board(Board) const; void Draw_Title() const; void Draw_Next_Piece_Board() const; void Draw_Score() const; private: }; #endif
[ "afeng5@fordham.edu" ]
afeng5@fordham.edu
fab89482ab8384fa972f5ad92230fef66dbe5087
3113b3ed92063987040a652a1ca19231c33afc2c
/Stone Age/build-StoneAgeView-C_C-Debug/debug/moc_PlayerBoard.cpp
94240e06fb5cc0f49bff92ca75b3000470579594
[]
no_license
kristofleroux/uh-ogp1-project
1e61a198219e6d7ee62b3a67847e40ccc34b66ba
90047d39eb4cc14df9815decc472caf86a05d7b5
refs/heads/master
2022-01-24T23:07:06.643206
2019-07-16T08:44:41
2019-07-16T08:44:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,225
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'PlayerBoard.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Stone Age - Qt Application/model/PlayerBoard.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'PlayerBoard.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.12.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 QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_PlayerBoard_t { QByteArrayData data[14]; char stringdata0[110]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_PlayerBoard_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_PlayerBoard_t qt_meta_stringdata_PlayerBoard = { { QT_MOC_LITERAL(0, 0, 11), // "PlayerBoard" QT_MOC_LITERAL(1, 12, 16), // "s_setActiveState" QT_MOC_LITERAL(2, 29, 0), // "" QT_MOC_LITERAL(3, 30, 6), // "active" QT_MOC_LITERAL(4, 37, 19), // "s_updatePlayerBoard" QT_MOC_LITERAL(5, 57, 6), // "worker" QT_MOC_LITERAL(6, 64, 4), // "food" QT_MOC_LITERAL(7, 69, 5), // "score" QT_MOC_LITERAL(8, 75, 4), // "wood" QT_MOC_LITERAL(9, 80, 5), // "stone" QT_MOC_LITERAL(10, 86, 5), // "brick" QT_MOC_LITERAL(11, 92, 4), // "gold" QT_MOC_LITERAL(12, 97, 6), // "Tools*" QT_MOC_LITERAL(13, 104, 5) // "tools" }, "PlayerBoard\0s_setActiveState\0\0active\0" "s_updatePlayerBoard\0worker\0food\0score\0" "wood\0stone\0brick\0gold\0Tools*\0tools" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_PlayerBoard[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 2, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x06 /* Public */, 4, 8, 27, 2, 0x06 /* Public */, // signals: parameters QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::QString, QMetaType::QString, QMetaType::QString, QMetaType::QString, QMetaType::QString, QMetaType::QString, QMetaType::QString, 0x80000000 | 12, 5, 6, 7, 8, 9, 10, 11, 13, 0 // eod }; void PlayerBoard::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<PlayerBoard *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->s_setActiveState((*reinterpret_cast< bool(*)>(_a[1]))); break; case 1: _t->s_updatePlayerBoard((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3])),(*reinterpret_cast< QString(*)>(_a[4])),(*reinterpret_cast< QString(*)>(_a[5])),(*reinterpret_cast< QString(*)>(_a[6])),(*reinterpret_cast< QString(*)>(_a[7])),(*reinterpret_cast< Tools*(*)>(_a[8]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (PlayerBoard::*)(bool ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&PlayerBoard::s_setActiveState)) { *result = 0; return; } } { using _t = void (PlayerBoard::*)(QString , QString , QString , QString , QString , QString , QString , Tools * ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&PlayerBoard::s_updatePlayerBoard)) { *result = 1; return; } } } } QT_INIT_METAOBJECT const QMetaObject PlayerBoard::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_PlayerBoard.data, qt_meta_data_PlayerBoard, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *PlayerBoard::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *PlayerBoard::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_PlayerBoard.stringdata0)) return static_cast<void*>(this); return QObject::qt_metacast(_clname); } int PlayerBoard::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 < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } // SIGNAL 0 void PlayerBoard::s_setActiveState(bool _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void PlayerBoard::s_updatePlayerBoard(QString _t1, QString _t2, QString _t3, QString _t4, QString _t5, QString _t6, QString _t7, Tools * _t8) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)), const_cast<void*>(reinterpret_cast<const void*>(&_t5)), const_cast<void*>(reinterpret_cast<const void*>(&_t6)), const_cast<void*>(reinterpret_cast<const void*>(&_t7)), const_cast<void*>(reinterpret_cast<const void*>(&_t8)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "michiel.swaanen.gsm@gmail.com" ]
michiel.swaanen.gsm@gmail.com
f8fa20a3cc00d67566e3750e83a2b1a97223451e
de4551b0f14f4c2fafef6dd5662dd4caeea443f7
/warCPP/plugins/json/varianttomapconverter.cpp
1032c1c11e32022bbc1cd465c211d1321991c834
[]
no_license
jcambray/ProjetWarCPP
fa5a258a2aa2ba4b01695c9815f156dda4131771
0be8cf6f3e90cb737efa1af8245efabfd863d36a
refs/heads/master
2020-05-18T17:25:54.640673
2014-07-16T14:08:13
2014-07-16T14:08:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,939
cpp
/* * JSON Tiled Plugin * Copyright 2011, Porfírio José Pereira Ribeiro <porfirioribeiro@gmail.com> * Copyright 2011, Thorbjørn Lindeijer <thorbjorn@lindeijer.nl> * * This file is part of Tiled. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include "varianttomapconverter.h" #include "imagelayer.h" #include "map.h" #include "mapobject.h" #include "objectgroup.h" #include "properties.h" #include "tile.h" #include "tilelayer.h" #include "tileset.h" #include <QScopedPointer> using namespace Tiled; using namespace Json; static QString resolvePath(const QDir &dir, const QVariant &variant) { QString fileName = variant.toString(); if (QDir::isRelativePath(fileName)) fileName = QDir::cleanPath(dir.absoluteFilePath(fileName)); return fileName; } Map *VariantToMapConverter::toMap(const QVariant &variant, const QDir &mapDir) { mGidMapper.clear(); mMapDir = mapDir; const QVariantMap variantMap = variant.toMap(); const QString orientationString = variantMap["orientation"].toString(); Map::Orientation orientation = orientationFromString(orientationString); if (orientation == Map::Unknown) { mError = tr("Unsupported map orientation: \"%1\"") .arg(orientationString); return 0; } typedef QScopedPointer<Map> MapPtr; MapPtr map(new Map(orientation, variantMap["width"].toInt(), variantMap["height"].toInt(), variantMap["tilewidth"].toInt(), variantMap["tileheight"].toInt())); mMap = map.data(); map->setProperties(toProperties(variantMap["properties"])); const QString bgColor = variantMap["backgroundcolor"].toString(); if (!bgColor.isEmpty() && QColor::isValidColor(bgColor)) map->setBackgroundColor(QColor(bgColor)); foreach (const QVariant &tilesetVariant, variantMap["tilesets"].toList()) { Tileset *tileset = toTileset(tilesetVariant); if (!tileset) { qDeleteAll(map->tilesets()); // Delete tilesets loaded so far return 0; } map->addTileset(tileset); } foreach (const QVariant &layerVariant, variantMap["layers"].toList()) { Layer *layer = toLayer(layerVariant); if (!layer) { qDeleteAll(map->tilesets()); // Delete tilesets return 0; } map->addLayer(layer); } return map.take(); } Properties VariantToMapConverter::toProperties(const QVariant &variant) { const QVariantMap variantMap = variant.toMap(); Properties properties; QVariantMap::const_iterator it = variantMap.constBegin(); QVariantMap::const_iterator it_end = variantMap.constEnd(); for (; it != it_end; ++it) properties[it.key()] = it.value().toString(); return properties; } Tileset *VariantToMapConverter::toTileset(const QVariant &variant) { const QVariantMap variantMap = variant.toMap(); const int firstGid = variantMap["firstgid"].toInt(); const QString name = variantMap["name"].toString(); const int tileWidth = variantMap["tilewidth"].toInt(); const int tileHeight = variantMap["tileheight"].toInt(); const int spacing = variantMap["spacing"].toInt(); const int margin = variantMap["margin"].toInt(); const QVariantMap tileOffset = variantMap["tileoffset"].toMap(); const int tileOffsetX = tileOffset["x"].toInt(); const int tileOffsetY = tileOffset["y"].toInt(); if (tileWidth <= 0 || tileHeight <= 0 || firstGid == 0) { mError = tr("Invalid tileset parameters for tileset '%1'").arg(name); return 0; } typedef QScopedPointer<Tileset> TilesetPtr; TilesetPtr tileset(new Tileset(name, tileWidth, tileHeight, spacing, margin)); tileset->setTileOffset(QPoint(tileOffsetX, tileOffsetY)); const QString trans = variantMap["transparentcolor"].toString(); if (!trans.isEmpty() && QColor::isValidColor(trans)) tileset->setTransparentColor(QColor(trans)); QVariant imageVariant = variantMap["image"]; if (!imageVariant.isNull()) { QString imagePath = resolvePath(mMapDir, imageVariant); if (!tileset->loadFromImage(imagePath)) { mError = tr("Error loading tileset image:\n'%1'").arg(imagePath); return 0; } } tileset->setProperties(toProperties(variantMap["properties"])); // Read tile terrain and external image information const QVariantMap tilesVariantMap = variantMap["tiles"].toMap(); QVariantMap::const_iterator it = tilesVariantMap.constBegin(); for (; it != tilesVariantMap.end(); ++it) { bool ok; const int tileIndex = it.key().toInt(); if (tileIndex < 0) { mError = tr("Tileset tile index negative:\n'%1'").arg(tileIndex); } if (tileIndex >= tileset->tileCount()) { // Extend the tileset to fit the tile if (tileIndex >= tilesVariantMap.count()) { // If tiles are defined this way, there should be an entry // for each tile. // Limit the index to number of entries to prevent running out // of memory on malicious input. mError = tr("Tileset tile index too high:\n'%1'").arg(tileIndex); return 0; } int i; for (i=tileset->tileCount(); i <= tileIndex; i++) tileset->addTile(QPixmap()); } Tile *tile = tileset->tileAt(tileIndex); if (tile) { const QVariantMap tileVar = it.value().toMap(); QList<QVariant> terrains = tileVar["terrain"].toList(); if (terrains.count() == 4) { for (int i = 0; i < 4; ++i) { int terrainID = terrains.at(i).toInt(&ok); if (ok && terrainID >= 0 && terrainID < tileset->terrainCount()) tile->setCornerTerrain(i, terrainID); } } float terrainProbability = tileVar["probability"].toFloat(&ok); if (ok) tile->setTerrainProbability(terrainProbability); imageVariant = tileVar["image"]; if (!imageVariant.isNull()) { QString imagePath = resolvePath(mMapDir, imageVariant); tileset->setTileImage(tileIndex, QPixmap(imagePath), imagePath); } QVariantMap objectGroupVariant = tileVar["objectgroup"].toMap(); if (!objectGroupVariant.isEmpty()) { // A quick hack to avoid taking into account the map's tile size // for object groups associated with a tile. const int tileWidth = mMap->tileWidth(); const int tileHeight = mMap->tileHeight(); mMap->setTileWidth(1); mMap->setTileHeight(1); tile->setObjectGroup(toObjectGroup(objectGroupVariant)); mMap->setTileWidth(tileWidth); mMap->setTileHeight(tileHeight); } QVariantList frameList = tileVar["animation"].toList(); if (!frameList.isEmpty()) { QVector<Frame> frames(frameList.size()); for (int i = frameList.size() - 1; i >= 0; --i) { const QVariantMap frameVariantMap = frameList[i].toMap(); Frame &frame = frames[i]; frame.tileId = frameVariantMap["tileid"].toInt(); frame.duration = frameVariantMap["duration"].toInt(); } tile->setFrames(frames); } } } // Read tile properties QVariantMap propertiesVariantMap = variantMap["tileproperties"].toMap(); for (it = propertiesVariantMap.constBegin(); it != propertiesVariantMap.constEnd(); ++it) { const int tileIndex = it.key().toInt(); const QVariant propertiesVar = it.value(); if (tileIndex >= 0 && tileIndex < tileset->tileCount()) { const Properties properties = toProperties(propertiesVar); tileset->tileAt(tileIndex)->setProperties(properties); } } // Read terrains QVariantList terrainsVariantList = variantMap["terrains"].toList(); for (int i = 0; i < terrainsVariantList.count(); ++i) { QVariantMap terrainMap = terrainsVariantList[i].toMap(); tileset->addTerrain(terrainMap["name"].toString(), terrainMap["tile"].toInt()); } mGidMapper.insert(firstGid, tileset.data()); return tileset.take(); } Layer *VariantToMapConverter::toLayer(const QVariant &variant) { const QVariantMap variantMap = variant.toMap(); Layer *layer = 0; if (variantMap["type"] == "tilelayer") layer = toTileLayer(variantMap); else if (variantMap["type"] == "objectgroup") layer = toObjectGroup(variantMap); else if (variantMap["type"] == "imagelayer") layer = toImageLayer(variantMap); if (layer) layer->setProperties(toProperties(variantMap["properties"])); return layer; } TileLayer *VariantToMapConverter::toTileLayer(const QVariantMap &variantMap) { const QString name = variantMap["name"].toString(); const int width = variantMap["width"].toInt(); const int height = variantMap["height"].toInt(); const QVariantList dataVariantList = variantMap["data"].toList(); if (dataVariantList.size() != width * height) { mError = tr("Corrupt layer data for layer '%1'").arg(name); return 0; } typedef QScopedPointer<TileLayer> TileLayerPtr; TileLayerPtr tileLayer(new TileLayer(name, variantMap["x"].toInt(), variantMap["y"].toInt(), width, height)); const qreal opacity = variantMap["opacity"].toReal(); const bool visible = variantMap["visible"].toBool(); tileLayer->setOpacity(opacity); tileLayer->setVisible(visible); int x = 0; int y = 0; bool ok; foreach (const QVariant &gidVariant, dataVariantList) { const unsigned gid = gidVariant.toUInt(&ok); if (!ok) { mError = tr("Unable to parse tile at (%1,%2) on layer '%3'") .arg(x).arg(y).arg(tileLayer->name()); return 0; } const Cell cell = mGidMapper.gidToCell(gid, ok); tileLayer->setCell(x, y, cell); x++; if (x >= tileLayer->width()) { x = 0; y++; } } return tileLayer.take(); } ObjectGroup *VariantToMapConverter::toObjectGroup(const QVariantMap &variantMap) { typedef QScopedPointer<ObjectGroup> ObjectGroupPtr; ObjectGroupPtr objectGroup(new ObjectGroup(variantMap["name"].toString(), variantMap["x"].toInt(), variantMap["y"].toInt(), variantMap["width"].toInt(), variantMap["height"].toInt())); const qreal opacity = variantMap["opacity"].toReal(); const bool visible = variantMap["visible"].toBool(); objectGroup->setOpacity(opacity); objectGroup->setVisible(visible); objectGroup->setColor(variantMap.value("color").value<QColor>()); const QString drawOrderString = variantMap.value("draworder").toString(); if (!drawOrderString.isEmpty()) { objectGroup->setDrawOrder(drawOrderFromString(drawOrderString)); if (objectGroup->drawOrder() == ObjectGroup::UnknownOrder) { mError = tr("Invalid draw order: %1").arg(drawOrderString); return 0; } } foreach (const QVariant &objectVariant, variantMap["objects"].toList()) { const QVariantMap objectVariantMap = objectVariant.toMap(); const QString name = objectVariantMap["name"].toString(); const QString type = objectVariantMap["type"].toString(); const int gid = objectVariantMap["gid"].toInt(); const qreal x = objectVariantMap["x"].toReal(); const qreal y = objectVariantMap["y"].toReal(); const qreal width = objectVariantMap["width"].toReal(); const qreal height = objectVariantMap["height"].toReal(); const qreal rotation = objectVariantMap["rotation"].toReal(); const QPointF pos(x, y); const QSizeF size(width, height); MapObject *object = new MapObject(name, type, pos, size); object->setRotation(rotation); if (gid) { bool ok; object->setCell(mGidMapper.gidToCell(gid, ok)); } if (objectVariantMap.contains("visible")) object->setVisible(objectVariantMap["visible"].toBool()); object->setProperties(toProperties(objectVariantMap["properties"])); objectGroup->addObject(object); const QVariant polylineVariant = objectVariantMap["polyline"]; const QVariant polygonVariant = objectVariantMap["polygon"]; if (polygonVariant.isValid()) { object->setShape(MapObject::Polygon); object->setPolygon(toPolygon(polygonVariant)); } if (polylineVariant.isValid()) { object->setShape(MapObject::Polyline); object->setPolygon(toPolygon(polylineVariant)); } if (objectVariantMap.contains("ellipse")) object->setShape(MapObject::Ellipse); } return objectGroup.take(); } ImageLayer *VariantToMapConverter::toImageLayer(const QVariantMap &variantMap) { typedef QScopedPointer<ImageLayer> ImageLayerPtr; ImageLayerPtr imageLayer(new ImageLayer(variantMap["name"].toString(), variantMap["x"].toInt(), variantMap["y"].toInt(), variantMap["width"].toInt(), variantMap["height"].toInt())); const qreal opacity = variantMap["opacity"].toReal(); const bool visible = variantMap["visible"].toBool(); imageLayer->setOpacity(opacity); imageLayer->setVisible(visible); const QString trans = variantMap["transparentcolor"].toString(); if (!trans.isEmpty() && QColor::isValidColor(trans)) imageLayer->setTransparentColor(QColor(trans)); QVariant imageVariant = variantMap["image"].toString(); if (!imageVariant.isNull()) { QString imagePath = resolvePath(mMapDir, imageVariant); if (!imageLayer->loadFromImage(QImage(imagePath), imagePath)) { mError = tr("Error loading image:\n'%1'").arg(imagePath); return 0; } } return imageLayer.take(); } QPolygonF VariantToMapConverter::toPolygon(const QVariant &variant) const { QPolygonF polygon; foreach (const QVariant &pointVariant, variant.toList()) { const QVariantMap pointVariantMap = pointVariant.toMap(); const qreal pointX = pointVariantMap["x"].toReal(); const qreal pointY = pointVariantMap["y"].toReal(); polygon.append(QPointF(pointX, pointY)); } return polygon; }
[ "jerome.cambray@gmail.com" ]
jerome.cambray@gmail.com
340b4da6add20b416f738e08bbc088c27c169c55
8e819a06e2f7f3703765dc0ea2312fb01de5f376
/Genetic_algorithm_for_TSP/tsp.cpp
951994e66d078513b1f34c24c8fdf682989be467
[]
no_license
StefanoBarison/Example_code
ed8a48a9d38bc7ac19231106837ff85045ea9d67
2f79b7b31883b1e0c3b4c1d5ddfd68b4d63bfd8b
refs/heads/master
2022-10-06T08:17:13.290306
2020-06-08T10:14:15
2020-06-08T10:14:15
266,736,008
1
1
null
null
null
null
UTF-8
C++
false
false
10,964
cpp
#include<iostream> #include<fstream> #include<cmath> #include<iomanip> //Useful libraries #include<vector> #include<algorithm> #include<iterator> #include<random> #include<string> //Personal #include "tsp.h" using namespace std; random_device radm; mt19937_64 mt(radm()); ///////////////////// // Class individual// ///////////////////// bool individual:: operator ==(individual &ind2){ if(this->Get_lenght() == ind2.Get_lenght()){ return true; } else{ return false; } } bool individual::operator <(individual & ind2){ if(this->Get_lenght() < ind2.Get_lenght()){ return true; } else{ return false; } } void individual:: Evaluate(map cities){ double sum=0.0; int size= _chromosome.size(); for(int i=0;i<size-1;i++){ sum+=cities.Distance(_chromosome[i],_chromosome[i+1]); } sum+=cities.Distance(_chromosome[size-1],0); _lenght=sum; } double individual::Get_lenght(){ return _lenght; } void individual::Print(){ int size =_chromosome.size(); for(int i=0;i<size;i++){ cout<<setw(3)<<_chromosome[i]; } cout<<endl; } void individual::Print_lenght(){ cout<<_lenght<<endl; } vector<int> individual::Get_genes(){ return _chromosome; } void individual::Set_genes(vector<int> new_genes){ _chromosome=new_genes; } bool individual:: Check(){ vector<int> reference; int size=_chromosome.size(); for(int i=0;i<size;i++){ reference.push_back(i); } bool check=is_permutation(_chromosome.begin(),_chromosome.end(),reference.begin()); return check; } individual::~individual(){ _chromosome.clear(); } void individual::Swap_mutate(){ int size=_chromosome.size(); uniform_int_distribution<> dis(1,size-1); int x=dis(mt); int y=dis(mt); while(x==y){ y=dis(mt); } swap(_chromosome[x],_chromosome[y]); } void individual:: Push_back_mutate(int n){ vector<int> new_chromo; new_chromo.push_back(0); for(unsigned int i=n+1;i<_chromosome.size();i++){ new_chromo.push_back(_chromosome[i]); } for(int i=1;i<=n;i++){ new_chromo.push_back(_chromosome[i]); } _chromosome=new_chromo; } void individual:: Multi_swap_mutate(int n){ int size=_chromosome.size(); uniform_int_distribution<> dist(1,size-n); int x=dist(mt); int y=dist(mt); while(abs(x-y)<n){ y=dist(mt); } for(int i=0;i<n;i++){ swap(_chromosome[x+i],_chromosome[y+i]); } } void individual:: Uniform_swap_mutate(double p_u){ int size=_chromosome.size(); uniform_int_distribution<> dis(1,size-1); uniform_real_distribution<> r_dist(0,1); for(int i=1;i<size;i++){ double r=r_dist(mt); if(r<p_u){ int y=dis(mt); while(y==i){ y=dis(mt); } swap(_chromosome[i],_chromosome[y]); } } } //////////////////// //Class population// //////////////////// void population:: Initialize(){ vector<int> reference; for(int i=0;i<_ncities;i++){ reference.push_back(i); } for(int i=0;i<_size;i++){ shuffle(reference.begin()+1,reference.end(),mt); individual new_one(reference); _pop.push_back(new_one); } } void population:: Evaluate_all(map cities){ for(int i=0;i<_size;i++){ _pop[i].Evaluate(cities); } } individual* population::Get_individual(int i){ return &_pop[i]; } double population::Get_size(){ return _size; } void population::Print_best(map cities){ this-> Sort(cities); cout<<"Best candidate :"<<endl; _pop[0].Print(); _pop[0].Print_lenght(); } individual* population:: Get_best(map cities){ this->Sort(cities); return &_pop[0]; } double population:: Get_best_average(map cities){ this->Sort(cities); int half=_size/2; double sum=0.0; for(int i=0;i<half;i++){ sum+=_pop[i].Get_lenght(); } sum/=half; return sum; } void population:: Sort(map cities){ for(int i=0;i<_size;i++){ _pop[i].Evaluate(cities); } sort(_pop.begin(),_pop.end()); } void population:: Wheel_selection(map cities){ // First, order the cities this-> Sort(cities); //Then, generate the vector of probabilities, the probabilities are generated proportionally to the highet possible path vector<double> fitness; for(int i=0;i<_size;i++){ fitness.push_back(_pop[i].Get_lenght()); } //double tot=accumulate(fitness.begin(),fitness.end(),0.00); double max=_pop[_size-1].Get_lenght(); for(int i=0;i<_size;i++){ //fitness[i]=1.0-fitness[i]/tot; fitness[i]=1.0-fitness[i]/max; } vector<double> probabilities; for(int i=0;i<_size;i++){ double t=accumulate(fitness.begin(),fitness.begin()+i,0.00); probabilities.push_back(t); } for(int i=0;i<_size;i++){ probabilities[i]/=probabilities[_size-1]; //cout<<probabilities[i]<<","; } //cout<<endl; //Now let's perform the biased roulette wheel selection vector<individual> new_pop; uniform_real_distribution<> distribution(0,1); for(int j=0;j<_size;j++){ double r=distribution(mt); //cout<<r<<","; for(int k=0;k<_size-1;k++){ if(r> probabilities[k] && r<probabilities[k+1] ){ new_pop.push_back(_pop[k]); } } } cout<<endl; //Substitute the old generation with the new _pop=new_pop; //Evaluate the new population for(int i=0;i<_size;i++){ _pop[i].Evaluate(cities); } } void population::Elitism(map cities, int elite){ // Order the cities, and save the best candidates this-> Sort(cities); int n_elite=elite; vector<individual> new_pop; for(int i=0;i<n_elite;i++){ new_pop.push_back(_pop[i]); } //Then, generate the vector of probabilities, the probabilities are generated with respect to the longest possible path vector<double> fitness; for(int i=0;i<_size;i++){ fitness.push_back(_pop[i].Get_lenght()); } //double tot=accumulate(fitness.begin(),fitness.end(),0.00); double max=_pop[_size-1].Get_lenght(); for(int i=0;i<_size;i++){ //fitness[i]=1.0-fitness[i]/tot; fitness[i]=1.0-fitness[i]/max; } vector<double> probabilities; for(int i=0;i<_size;i++){ double t=accumulate(fitness.begin(),fitness.begin()+i,0.00); probabilities.push_back(t); } for(int i=0;i<_size;i++){ probabilities[i]/=probabilities[_size-1]; //cout<<probabilities[i]<<","; } //cout<<endl; //Now let's perform the biased roulette wheel selection uniform_real_distribution<> distribution(0,1); for(int j=0;j<_size-n_elite;j++){ double r=distribution(mt); //cout<<r<<","; for(int k=0;k<_size-1;k++){ if(r> probabilities[k] && r<probabilities[k+1] ){ new_pop.push_back(_pop[k]); } } } //Substitute the old generation with the new _pop=new_pop; //Evaluate the new population for(int i=0;i<_size;i++){ _pop[i].Evaluate(cities); } } void population:: Evolutive_step(map cities,string type){ if(type=="Roulette"){ cout<<"Performing roulette wheel selection..."<<endl; //Mutate the individuals with a probability m_p and crossover with a probability c_p double m_p1=0.03; double m_p2=0.09; double m_p3=0.10; double c_p=0.60; uniform_real_distribution<> dist(0,1); uniform_int_distribution<> int_dist(0,_size-1); for(int i=0;i<_size-1;i++){ double r1=dist(mt); if(r1<c_p){ int r_i=int_dist(mt); Crossover(&_pop[i],&_pop[r_i]); } } for(int i=0;i<_size;i++){ double r2=dist(mt); if(r2<m_p1){ this->Get_individual(i)->Swap_mutate(); } if(r2>m_p1 && r2<m_p2){ this->Get_individual(i)->Push_back_mutate(2); } if(r2>m_p2 && r2<m_p3){ this->Get_individual(i)->Multi_swap_mutate(3); } } //Now select the best individuals and take to the next generation this->Wheel_selection(cities); } else if(type=="Elitism"){ cout<<"Performing roulette wheel selection with elitism..."<<endl; //First, we have to save the best candidates vector<individual> elite; int n_elite=30; this->Sort(cities); for(int i=0;i<n_elite;i++){ elite.push_back(_pop[i]); } //Now perform mutations and crossovers double m_p1=0.05; double m_p2=0.10; double m_p3=0.12; double m_p4=0.15; double c_p=0.50; uniform_real_distribution<> dist(0,1); uniform_int_distribution<> int_dist(0,_size-1); for(int i=0;i<_size-1;i++){ double r1=dist(mt); if(r1<c_p){ int r_i=int_dist(mt); Crossover(&_pop[i],&_pop[r_i]); } } for(int i=0;i<_size;i++){ double r2=dist(mt); if(r2<m_p1){ this->Get_individual(i)->Swap_mutate(); } if(r2>m_p1 && r2<m_p2){ this->Get_individual(i)->Push_back_mutate(2); } if(r2>m_p2 && r2<m_p3){ this->Get_individual(i)->Multi_swap_mutate(3); } if(r2>m_p3 && r2<m_p4){ this->Get_individual(i)->Uniform_swap_mutate(0.1); } } this->Sort(cities); //Now re introduce the elite eliminating the longest paths for(int i=0;i<n_elite;i++){ _pop[_size-1-i]=elite[i]; } this->Sort(cities); //...and perform selection this->Elitism(cities,n_elite); } } ////////////// //Class city// ////////////// double city::Get_x(){ return _x; } double city::Get_y(){ return _y; } void city::Print(){ cout<<setw(10)<<_x<<setw(10)<<_y<<endl; } city:: ~city(){} ///////////// //Class map// ///////////// double map::Distance(int i,int j){ return _distances[i][j]; } double map:: Get_size(){ return _ncities; } void map:: Create_d_matrix(){ for(int i=0;i<_ncities;i++){ vector<double> row; for(int j=0;j<_ncities;j++){ double d= sqrt(pow(_cities[i].Get_x()-_cities[j].Get_x(),2)+pow(_cities[i].Get_y()-_cities[j].Get_y(),2)); row.push_back(d); } _distances.push_back(row); } } void map::Circle_initialize(){ double l=10.0; //random_device radm; //mt19937_64 mt(radm()); uniform_real_distribution<> distribution(0, 2*M_PI); for(int i=0;i<_ncities;i++){ double theta=distribution(mt); city new_city(l*cos(theta),l*sin(theta)); _cities.push_back(new_city); } } void map::Square_initialize(){ double l=10.0; uniform_real_distribution<> distribution(-l,l); for(int i=0;i<_ncities;i++){ double x=distribution(mt); double y=distribution(mt); city new_city(x,y); _cities.push_back(new_city); } } void map::File_initialize(istream & indata){ double x,y; while(!indata.eof()){ indata>>x>>y; city new_city(x,y); _cities.push_back(new_city); } _ncities=_cities.size(); } void map::Print_cities(){ for(int i=0;i<_ncities;i++){ _cities[i].Print(); } } void map::Print_d_matrix(){ int wd=10; for(int i=0;i<_ncities;i++){ for(int j=0;j<_ncities;j++){ cout<<setw(wd)<<_distances[i][j]; } cout<<endl; } } //Useful functions void Crossover(individual * t1,individual * t2){ vector<int> p1=t1->Get_genes(); vector<int> p2=t2->Get_genes(); int size=p1.size(); vector<int> s1; vector<int> s2; uniform_int_distribution<> dist(0,size-1); int r=dist(mt); //cout<<r<<endl; for(int i=0;i<r;i++){ s1.push_back(p1[i]); s2.push_back(p2[i]); } for(int i=0;i<size;i++){ int a=p1[i]; int b=p2[i]; if(any_of(p1.begin()+r,p1.end(),[b](int k){return k==b;})){ s1.push_back(p2[i]); } if(any_of(p2.begin()+r,p2.end(),[a](int k){return k==a;})){ s2.push_back(p1[i]); } } t1->Set_genes(s1); t2->Set_genes(s2); }
[ "stefano.barison@studenti.unimi.it" ]
stefano.barison@studenti.unimi.it
d766b35e937ca75d36d9c9b412de8ecda9314019
e723c865de2e53bc3181b3ad004a4a72dd089dc9
/Src/SurfaceTrimmer.cpp
41644305f0106ff7312da7d7f905490157c001b4
[]
no_license
mingminzhen/poisson-reconstruction
2b7b7a2ff5ef7b670735eee5b30a7135ba52df1e
036933165695cdc10266784ae809eb2ca0f1d5d5
refs/heads/master
2020-12-30T19:44:54.949387
2014-07-22T08:20:33
2014-07-22T13:44:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,539
cpp
/* Copyright (c) 2013, Michael Kazhdan 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 Johns Hopkins University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstdio> #include <cstdlib> #include <cfloat> #include <iostream> #ifndef NO_OMP #include <omp.h> #endif #include "CmdLineParser.h" #include "DumpOutput.h" #include "HashMap.h" #include "Geometry.h" #include "Ply.h" #include "MAT.h" #include "Time.h" #define FOR_RELEASE 1 cmdLine<std::string> In("in"); cmdLine<std::string> Out("out"); cmdLine<int> Smooth("smooth", 5); cmdLine<float> Trim("trim"); cmdLine<float> IslandAreaRatio("aRatio", 0.001f); cmdLine<std::pair<float, float> > ColorRange("color"); cmdLineReadable PolygonMesh("polygonMesh"); std::vector<cmdLineReadable*> params; void BuildParams() { cmdLineReadable* params_array[] = { &In , &Out , &Trim , &PolygonMesh , &ColorRange , &Smooth , &IslandAreaRatio, nullptr }; for(cmdLineReadable** p = params_array; *p; ++p) params.push_back(*p); } void ShowUsage(std::string const& executable) { printf( "Usage: %s\n" , executable.c_str() ); printf( "\t --%s <input polygon mesh>\n" , In.name() ); printf( "\t[--%s <ouput polygon mesh>]\n" , Out.name() ); printf( "\t[--%s <smoothing iterations>=%d]\n" , Smooth.name() , Smooth.value() ); printf( "\t[--%s <trimming value>]\n" , Trim.name() ); printf( "\t[--%s <relative area of islands>=%f]\n" , IslandAreaRatio.name() , IslandAreaRatio.value() ); printf( "\t[--%s]\n" , PolygonMesh.name() ); #if !FOR_RELEASE printf( "\t[--%s <color range>]\n" , ColorRange.name() ); #endif // !FOR_RELEASE } long long EdgeKey(long long key1, long long key2) { return key1 <= key2 ? (key1 << 32) | key2 : EdgeKey(key2, key1); } template<class Real> PlyValueVertex<Real> InterpolateVertices(PlyValueVertex<Real> const& v1, PlyValueVertex<Real> const& v2, float value) { if(v1.value == v2.value) return (v1 + v2) / (Real)2; Real dx = (v1.value - value) / (v1.value - v2.value); PlyValueVertex<Real> v; for(int i = 0; i != 3; ++i) v.point.coords[i] = v1.point.coords[i] * (1 - dx) + v2.point.coords[i] * dx; v.value = v1.value * (1 - dx) + v2.value * dx; return v; } template<class Real> std::vector<PlyColorVertex<Real> > ColorVertices(std::vector<PlyValueVertex<Real> > const& inVertices, float min, float max) { std::vector<PlyColorVertex<Real> > outVertices(inVertices.size()); for(size_t i = 0; i != inVertices.size(); ++i) { outVertices[i].point = inVertices[i].point; float temp = (inVertices[i].value - min) / (max - min); temp = std::max(0.f, std::min(1.f, temp)); temp *= 255; outVertices[i].color[0] = outVertices[i].color[1] = outVertices[i].color[2] = (int)lround(temp); } return outVertices; } template<class Real> void SmoothValues(std::vector<PlyValueVertex<Real> >& vertices, std::vector<std::vector<int> > const& polygons) { std::vector<int> count(vertices.size()); std::vector<Real> sums(vertices.size(), 0); for(size_t i = 0; i != polygons.size(); ++i) { size_t sz = polygons[i].size(); for(size_t j = 0; j != sz; ++j) { int v1 = polygons[i][j]; int v2 = polygons[i][(j + 1) % sz]; ++count[v1]; ++count[v2]; sums[v1] += vertices[v2].value; sums[v2] += vertices[v1].value; } } for(size_t i = 0; i != vertices.size(); ++i) vertices[i].value = (sums[i] + vertices[i].value) / (count[i] + 1); } template<class Real> void SplitPolygon(std::vector<int> const& polygon, std::vector<PlyValueVertex<Real> >& vertices, std::vector<std::vector<int> >& ltPolygons, std::vector<std::vector<int> >& gtPolygons, std::vector<bool>& ltFlags, std::vector<bool>& gtFlags, HashMap<long long, int>& vertexTable, Real trimValue) { int sz = polygon.size(); std::vector<bool> gt(sz); int gtCount = 0; for(int j = 0; j != sz; ++j) { gt[j] = vertices[polygon[j]].value > trimValue ; if(gt[j]) ++gtCount; } if(gtCount == sz) { gtPolygons.push_back(polygon); gtFlags.push_back(false); } else if(gtCount == 0) { ltPolygons.push_back(polygon); ltFlags.push_back(false); } else { int start; for(start = 0; start != sz; ++start) if(gt[start] && !gt[(start + sz - 1) % sz]) break; bool gtFlag = true; std::vector<int> poly; // Add the initial vertex { int v1 = polygon[(start + sz - 1) % sz]; int v2 = polygon[start]; int vIdx; HashMap<long long, int>::iterator iter = vertexTable.find(EdgeKey(v1, v2)); if(iter == vertexTable.end()) { vertexTable[EdgeKey(v1, v2)] = vIdx = vertices.size(); vertices.push_back(InterpolateVertices(vertices[v1], vertices[v2], trimValue)); } else vIdx = iter->second; poly.push_back(vIdx); } for(int _j = 0; _j <= sz; ++_j) { int j1 = (_j + start + sz - 1) % sz; int j2 = (_j + start) % sz; int v1 = polygon[j1]; int v2 = polygon[j2]; if(gt[j2] == gtFlag) poly.push_back(v2); else { int vIdx; HashMap<long long, int>::iterator iter = vertexTable.find(EdgeKey(v1, v2)); if(iter == vertexTable.end()) { vertexTable[EdgeKey(v1, v2)] = vIdx = vertices.size(); vertices.push_back(InterpolateVertices(vertices[v1], vertices[v2], trimValue)); } else vIdx = iter->second; poly.push_back(vIdx); if(gtFlag) { gtPolygons.push_back(poly); ltFlags.push_back(true); } else { ltPolygons.push_back(poly); gtFlags.push_back(true); } poly.clear(); poly.push_back(vIdx); poly.push_back(v2); gtFlag = !gtFlag; } } } } template<class Real> std::vector<std::vector<int> > Triangulate(std::vector<PlyValueVertex<Real> > const& vertices, std::vector<std::vector<int> > const& polygons) { std::vector<std::vector<int> > triangles; for(size_t i = 0; i != polygons.size(); ++i) { if(polygons.size() > 3) { MinimalAreaTriangulation<Real> mat; std::vector<Point3D<Real> > _vertices(polygons[i].size()); std::vector<TriangleIndex> _triangles; for(size_t j = 0; j != polygons[i].size(); ++j) _vertices[j] = vertices[polygons[i][j]].point; mat.GetTriangulation(_vertices, _triangles); // Add the triangles to the mesh size_t idx = triangles.size(); triangles.resize(idx + _triangles.size()); for(size_t j = 0; j != _triangles.size(); ++j) { triangles[idx + j].resize(3); for(int k = 0; k != 3; ++k) triangles[idx + j][k] = polygons[i][_triangles[j].idx[k]]; } } else if(polygons[i].size() == 3) triangles.push_back(polygons[i]); } return triangles; } template<class Vertex> void RemoveHangingVertices(std::vector<Vertex>& vertices, std::vector<std::vector<int> >& polygons) { HashMap<int, int> vMap; std::vector<bool> vertexFlags(vertices.size(), false); for(size_t i = 0; i != polygons.size(); ++i) for(size_t j = 0; j != polygons[i].size(); ++j) vertexFlags[polygons[i][j]] = true; int vCount = 0; for(size_t i = 0; i != vertices.size(); ++i) if(vertexFlags[i]) vMap[i] = vCount++; for(size_t i = 0; i != polygons.size(); ++i) for(size_t j = 0; j != polygons[i].size(); ++j) polygons[i][j] = vMap[polygons[i][j]]; std::vector<Vertex> _vertices(vCount); for(size_t i = 0; i != vertices.size(); ++i) if(vertexFlags[i]) _vertices[vMap[i]] = vertices[i]; vertices = _vertices; } std::vector<std::vector<int> > SetConnectedComponents(std::vector<std::vector<int> > const& polygons) { std::vector<std::vector<int> > components; std::vector<int> polygonRoots(polygons.size()); for(size_t i = 0; i != polygons.size(); ++i) polygonRoots[i] = i; HashMap<long long, int> edgeTable; for(size_t i = 0; i != polygons.size(); ++i) { int sz = polygons[i].size(); for(int j = 0; j != sz; ++j) { long long eKey = EdgeKey(polygons[i][j], polygons[i][(j + 1) % sz]); HashMap<long long, int>::iterator iter = edgeTable.find(eKey); if(iter == edgeTable.end()) edgeTable[eKey] = i; else { int p = iter->second; while(polygonRoots[p] != p) { int temp = polygonRoots[p]; polygonRoots[p] = i; p = temp; } polygonRoots[p] = i; } } } for(size_t i = 0; i != polygonRoots.size(); ++i) { int p = i; while(polygonRoots[p] != p) p = polygonRoots[p]; int root = p; p = i; while(polygonRoots[p] != p) { int temp = polygonRoots[p]; polygonRoots[p] = root; p = temp; } } int cCount = 0; HashMap<int, int> vMap; for(size_t i = 0; i != polygonRoots.size(); ++i) if(polygonRoots[i] == (int)i) vMap[i] = cCount++; components.resize(cCount); for(size_t i = 0; i != polygonRoots.size(); ++i) components[vMap[polygonRoots[i]]].push_back(i); return components; } template<class Real> double PolygonArea(std::vector<PlyValueVertex<Real> > const& vertices, std::vector<int> const& polygon) { if(polygon.size() < 3) return 0; else if(polygon.size() == 3) return TriangleArea(vertices[polygon[0]].point, vertices[polygon[1]].point, vertices[polygon[2]].point); else { Point3D<Real> center; for(size_t i = 0; i != polygon.size(); ++i) center += vertices[polygon[i]].point; center /= (Real)polygon.size(); double area = 0; for(size_t i = 0; i != polygon.size(); ++i) area += TriangleArea(center, vertices[polygon[i]].point, vertices[polygon[(i + 1) % polygon.size()]].point); return area; } } int main(int argc, char** argv) { BuildParams(); cmdLineParse(argc - 1, argv + 1, params , false); #if FOR_RELEASE if(!In.set() || !Trim.set()) { ShowUsage(argv[0]); return EXIT_FAILURE; } #else // !FOR_RELEASE if(!In.set()) { ShowUsage(argv[0]); return EXIT_FAILURE; } #endif // FOR_RELEASE std::vector<PlyValueVertex<float> > vertices; std::vector<std::vector<int> > polygons; int ft; std::vector<std::string> comments; bool readFlags[PlyValueVertex<float>::Components]; PlyReadPolygons(In.value(), vertices, polygons, ft, comments, readFlags); DumpOutput::instance().resetStrings(comments); if(!readFlags[3]) { std::cerr << "[ERROR] vertices do not have value flag" << std::endl; return EXIT_FAILURE; } for(int i = 0; i != Smooth.value(); ++i) SmoothValues(vertices, polygons); float min = vertices[0].value; float max = vertices[0].value; for(size_t i = 0; i != vertices.size(); ++i) { min = std::min(min, vertices[i].value); max = std::max(max, vertices[i].value); } std::cout << "Value Range: [" << min << ", " << max << "]" << std::endl; if(Trim.set()) { DumpOutput::instance()("Running Surface Trimmer (V5)"); for(std::vector<cmdLineReadable*>::iterator p = params.begin(); p != params.end(); ++p) if((*p)->set()) DumpOutput::instance()("\t--%s %s\n", (*p)->name(), (*p)->toString().c_str()); HashMap<long long, int> vertexTable; std::vector<std::vector<int> > ltPolygons; std::vector<std::vector<int> > gtPolygons; std::vector<bool> ltFlags; std::vector<bool> gtFlags; double t = Time(); for(size_t i = 0; i != polygons.size(); ++i) SplitPolygon(polygons[i], vertices, ltPolygons, gtPolygons, ltFlags, gtFlags, vertexTable, Trim.value()); if(IslandAreaRatio.value() > 0) { std::vector<std::vector<int> > _gtPolygons; std::vector<std::vector<int> > ltComponents = SetConnectedComponents(ltPolygons); std::vector<std::vector<int> > gtComponents = SetConnectedComponents(gtPolygons); std::vector<double> ltAreas(ltComponents.size(), 0); std::vector<double> gtAreas(gtComponents.size(), 0); std::vector<bool> ltComponentFlags(ltComponents.size(), false); std::vector<bool> gtComponentFlags(gtComponents.size(), false); double area = 0; for(size_t i = 0; i != ltComponents.size(); ++i) { for(size_t j = 0; j != ltComponents[i].size(); ++j) { ltAreas[i] += PolygonArea(vertices, ltPolygons[ltComponents[i][j]]); ltComponentFlags[i] = ltComponentFlags[i] || ltFlags[ltComponents[i][j]]; } area += ltAreas[i]; } for(size_t i = 0; i != gtComponents.size(); ++i) { for(size_t j = 0; j != gtComponents[i].size(); ++j) { gtAreas[i] += PolygonArea(vertices, gtPolygons[gtComponents[i][j]]); gtComponentFlags[i] = gtComponentFlags[i] || gtFlags[gtComponents[i][j]]; } area += gtAreas[i]; } for(size_t i = 0; i != ltComponents.size(); ++i) { if(ltAreas[i] < area * IslandAreaRatio.value() && ltComponentFlags[i]) { for(size_t j = 0; j != ltComponents[i].size(); ++j) _gtPolygons.push_back(ltPolygons[ltComponents[i][j]]); } } for(size_t i = 0; i != gtComponents.size(); ++i) { if(gtAreas[i] >= area * IslandAreaRatio.value() && gtComponentFlags[i]) { for(size_t j = 0; j != gtComponents[i].size(); ++j) _gtPolygons.push_back(gtPolygons[gtComponents[i][j]]); } } gtPolygons = _gtPolygons; } std::vector<std::vector<int> > polys = PolygonMesh.set() ? gtPolygons : Triangulate(vertices, gtPolygons); RemoveHangingVertices(vertices, polys); DumpOutput::instance()("#Trimmed In: %9.1f (s)", Time() - t); if(Out.set()) PlyWritePolygons(Out.value(), vertices, polys, ft, DumpOutput::instance().strings()); } else { if(ColorRange.set()) { min = ColorRange.value().first; max = ColorRange.value().second; } std::vector<PlyColorVertex<float> > outVertices = ColorVertices(vertices, min, max); if(Out.set()) PlyWritePolygons(Out.value(), outVertices, polygons, ft, DumpOutput::instance().strings()); } return EXIT_SUCCESS; }
[ "shabalyn.a@gmail.com" ]
shabalyn.a@gmail.com
f77b4c4cc99efbc9a426de2db12e1ee1123a3163
ef99ed6ec2bb6a74ab06743ac03c292afe60e79a
/app/include/app/bridge/escaped.hpp
eea10476b36622dfff710e66018d753350e93f42
[]
no_license
mkeeter/straylight
8b5ee57b5fc554b221ce373863464f3c4a6c9772
78ff7fb7d691705731088ee64e43ded4c162fb9c
refs/heads/master
2021-01-13T08:51:04.094836
2019-03-06T01:35:13
2019-03-06T01:35:13
71,898,245
5
1
null
null
null
null
UTF-8
C++
false
false
1,203
hpp
#pragma once #include <QVector3D> #include "graph/translator.hpp" #include "kernel/eval/evaluator.hpp" namespace App { namespace Bridge { //////////////////////////////////////////////////////////////////////////////// class EscapedHandle : public Graph::Escaped { public: EscapedHandle(const std::map<Kernel::Tree::Id, float>& vars) : vars(vars) {}; virtual int tag() const=0; std::map<Kernel::Tree::Id, float> vars; }; //////////////////////////////////////////////////////////////////////////////// class EscapedPointHandle : public EscapedHandle { public: EscapedPointHandle(Kernel::Tree xyz[3], const std::map<Kernel::Tree::Id, float>& vars); int tag() const override; QVector3D pos; Kernel::Tree xyz[3]; }; //////////////////////////////////////////////////////////////////////////////// class EscapedShape : public EscapedHandle { public: EscapedShape(Kernel::Tree tree, const std::map<Kernel::Tree::Id, float>& vars); int tag() const override; Kernel::Tree tree; }; //////////////////////////////////////////////////////////////////////////////// } // namespace Bridge } // namespace App
[ "matt.j.keeter@gmail.com" ]
matt.j.keeter@gmail.com
9938393259c54df846a703122be5c39b7f3ee800
4bdf559541d8520b02a92e7c3eeeb8bdc946d918
/src/stalker_base/src/stalker_base.cpp
efce8567bdba96ee0ce0d88e6a2a1e900039f9a0
[]
no_license
CMUBOOST/BOOST3
3089b97ac1e6b0c9651f7f8e1f3840eeb0e3005d
afc0e0981cc32357355748fbdd6e280ce5a34115
refs/heads/master
2021-01-20T20:28:30.874988
2017-07-30T16:52:56
2017-07-30T16:52:56
60,435,258
0
7
null
null
null
null
UTF-8
C++
false
false
4,559
cpp
#include "ros/ros.h" #include "std_msgs/Float32.h" #include "sensor_msgs/JointState.h" #include "sensor_msgs/Joy.h" #include <geometry_msgs/Twist.h> #include <urdf/model.h> #include "sensor_msgs/Imu.h" #include "stalker_hw_interface.h" #include "lookup.hpp" #include "group.hpp" #include "group_command.hpp" #include <sstream> #include <string> #include <vector> #include <math.h> #include "controller_manager/controller_manager.h" #include "ros/callback_queue.h" #include <boost/chrono.hpp> typedef boost::chrono::steady_clock time_source; /** * A function to publish an IMU msg */ void send_imu_message(const hebi::Feedback& fbk, const ros::Publisher& pub, const std::string &jointName) { // NOTE: We set first cov element to -1 if doesn't exist per message docs // ( http://docs.ros.org/api/sensor_msgs/html/msg/Imu.html ) sensor_msgs::Imu msg; msg.header.stamp = ros::Time::now(); msg.header.frame_id = jointName; // Accelerometers if (fbk.imu().accelerometer().has()) { hebi::Vector3f accel = fbk.imu().accelerometer().get(); msg.linear_acceleration.x = accel.getX(); msg.linear_acceleration.y = accel.getY(); msg.linear_acceleration.z = accel.getZ(); } else { msg.linear_acceleration_covariance[0] = -1; } // Gyros if (fbk.imu().gyro().has()) { hebi::Vector3f gyro = fbk.imu().gyro().get(); msg.angular_velocity.x = gyro.getX(); msg.angular_velocity.y = gyro.getY(); msg.angular_velocity.z = gyro.getZ(); } else { msg.angular_velocity_covariance[0] = -1; } // Orientation msg.orientation_covariance[0] = -1; // Publish pub.publish(msg); } // Global 'group' pointer so we can access this in a callback...ugly, but until // we class-ify the node this will work. hebi::Group* group_g = NULL; // hebi::Group* group_g = new hebi::Group(); /** * Control loop for Stalker, not realtime safe */ void controlLoop(stalker_base::StalkerHardware &stalker, controller_manager::ControllerManager &cm, time_source::time_point &last_time) { /* TODO: Test std::unique_ptr */ // std::cout << "Hello Tim." << std::endl; // // TODO: Quit program. // exit(EXIT_FAILURE); // Calculate monotonic time difference time_source::time_point this_time = time_source::now(); boost::chrono::duration<double> elapsed_duration = this_time - last_time; ros::Duration elapsed(elapsed_duration.count()); last_time = this_time; // Process control loop stalker.updateJointsFromHardware(); cm.update(ros::Time::now(), elapsed); std::cout << "got here in controlLoop!!" << std::endl; stalker.writeCommandsToHardware(); std::cout << "didn't get here in controlLoop!!" << std::endl; } int main(int argc, char *argv[]) { ros::init(argc, argv, "stalker_base"); ros::NodeHandle nh; // Initialize robot hardware and link to controller manager stalker_base::StalkerHardware stalker(nh); controller_manager::ControllerManager cm(&stalker, nh); // std::vector<std::string> joint_names = {"Front_Left_Drive", "Rear_Left_Drive", "Front_Right_Drive", "Rear_Right_Drive"}; // std::vector<std::string> family_names = {"BOOST", "BOOST", "BOOST", "BOOST"}; // // // Get the lookup and wait to populate (TODO: check for null?) // hebi::Lookup lookup; // sleep(2); // lookup.printTable(); // // // Get the group // for (int i = 0; i < joint_names.size(); i++) // { // std::cout << "looking for: " << std::endl; // std::cout << joint_names[i] << std::endl; // std::cout << family_names[i] << std::endl; // } // std::unique_ptr<hebi::Group> group(lookup.getGroupFromNames(joint_names, family_names, 1000)); // if (!group) // { // ROS_INFO("Could not find modules on network! Quitting!"); // return -1; // } // // THIS IS A HACK to get around limited callback options for ROS subscribe call and the lack of a class for this node. // group_g = group.get(); // // std::unique_ptr<hebi::Group> group_g(lookup.getGroupFromNames(joint_names, family_names, 1000)); // std::cout << "Found modules!" << std::endl; // ROS_INFO("Found modules!"); // hebi::GroupFeedback fbk(group->size()); double period_s = 0.04; while (ros::ok()) { time_source::time_point last_time = time_source::now(); controlLoop(stalker, cm, last_time); usleep(period_s * 1000000); ros::spinOnce(); } // Stop the async callback before returning and deleting objects. // group->clearFeedbackHandlers(); sleep(1); // prevent segfaults? (TODO: needed?) return 0; }
[ "tmuellersim@gmail.com" ]
tmuellersim@gmail.com
2c65b52b6bb260fb62d9c856d508fb84819511a9
cef972f9920741e161ca02e3819605715b4bd347
/topcoder/user.h
90935ccc7323a4346158272b54e67e27c6a5d30c
[]
no_license
nykh2010/topcoder
fe8540487b2fb06aa7f6d0ab09720134e05c9046
4afcb4a12b1be3fbc80064b19dfad5eded75c0b7
refs/heads/master
2020-03-19T05:49:43.066674
2018-06-08T09:39:42
2018-06-08T09:39:42
134,530,800
0
0
null
null
null
null
UTF-8
C++
false
false
479
h
#pragma once class user { public: user(CString id); virtual ~user(void); void setname(CString &name); CString getname(); void setcorporation(CString &name); CString getcorporation(); private: CString name; CString corporation; CString id; }; class CUser { public: CUser(void); ~CUser(void); void setname(CString &name); CString getname(); void setcorporation(CString &name); CString getcorporation(); public: CString name; CString corporation; CString id; };
[ "466721896@qq.com" ]
466721896@qq.com
91e4449fe8d8835248044b1639e9b9b97ee79da8
39a70eeb95fa5f0bf4df777cf1e91c7594be62d8
/1-year/33-io/6.cpp
b3db5d5ddb5ca89d077bdcfdb9cd4c02cccde667
[]
no_license
pharick/cpp
296f18ba060f8ef6d6302f9e7fdc8ea13cb155ff
1cf153dd703672f0f47bf50dc8fcea753025dd37
refs/heads/master
2021-03-24T12:36:10.871565
2019-05-15T09:07:40
2019-05-15T09:07:40
109,940,251
0
0
null
null
null
null
UTF-8
C++
false
false
157
cpp
#include <iostream> #include <iomanip> using namespace std; int main() { int n; cin >> n; cout << setfill('S') << setw(10) << n << endl; return 0; }
[ "pharick@localhost.localdomain" ]
pharick@localhost.localdomain
ffa52bda32e8d6d28200e0aaf1fe18660843982c
bac7267590c6267b489178c8717e42a1865bb46b
/WildMagic5/Tools/WmtfViewer/WmtfViewer.h
18c920a02ef6f5b60bf9ff16e3929d974876f7b8
[]
no_license
VB6Hobbyst7/GeometricTools-Apple
1e53f260e84f8942e12adf7591b83ba2dd46a7f1
07b9764871a9dbe1240b6181039dd703e118a628
refs/heads/master
2021-02-11T11:17:56.813941
2013-11-26T15:25:10
2013-11-26T15:25:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,282
h
// Geometric Tools, LLC // Copyright (c) 1998-2013 // 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.0 (2010/01/01) #ifndef WMTFVIEWER_H #define WMTFVIEWER_H #include "Wm5WindowApplication2.h" using namespace Wm5; class WmtfViewer : public WindowApplication2 { WM5_DECLARE_INITIALIZE; WM5_DECLARE_TERMINATE; public: WmtfViewer (); virtual bool OnPrecreate (); virtual bool OnInitialize (); virtual void OnTerminate (); virtual bool OnKeyDown (unsigned char key, int x, int y); virtual bool OnMouseClick (int button, int state, int x, int y, unsigned int modifiers); virtual bool OnMotion (int button, int x, int y, unsigned int modifiers); virtual void ScreenOverlay (); protected: void CopySliceToScreen (); void ReadPixelValue (int x, int y); void SetStrR5G6B5 (int x, int y); void SetStrA1R5G5B5 (int x, int y); void SetStrA4R4G4B4 (int x, int y); void SetStrA8 (int x, int y); void SetStrL8 (int x, int y); void SetStrA8L8 (int x, int y); void SetStrR8G8B8 (int x, int y); void SetStrA8R8G8B8 (int x, int y); void SetStrA8B8G8R8 (int x, int y); void SetStrL16 (int x, int y); void SetStrG16R16 (int x, int y); void SetStrA16B16G16R16 (int x, int y); void SetStrR16F (int x, int y); void SetStrG16R16F (int x, int y); void SetStrA16B16G16R16F (int x, int y); void SetStrR32F (int x, int y); void SetStrG32R32F (int x, int y); void SetStrA32B32G32R32F (int x, int y); Texture2DPtr mTexture; Texture::Format mFormat; int mNumTexels, mXDim, mYDim; char* mTexels; Float4* mImage; int mSliceIndex; float mRGBMin, mRGBMax, mInvRGBRange; float mAMin, mAMax, mInvARange; bool mAlphaActive, mMouseDown; Float4 mTextColor; enum { PIXEL_STRING_SIZE = 512 }; char mPixelString[PIXEL_STRING_SIZE]; typedef void (WmtfViewer::*SetStrFunction)(int,int); SetStrFunction mSFunction[Color::CF_QUANTITY]; }; WM5_REGISTER_INITIALIZE(WmtfViewer); WM5_REGISTER_TERMINATE(WmtfViewer); #endif
[ "tprepscius" ]
tprepscius
ad83edf42d8205525723d2a7f0067f4393dafe20
668d3f25fbf37c7bc4a6154892e323655a9cb043
/version_old/UIAnimation.h
0c8d3e09cce0f8ed4641d2206d303aef8bb2b429
[]
no_license
buerlang/CubeWorld
d168a581092a476d80ef53c22cd7407bb0d83638
0fd25c504e27df9c7f1e35afda7fb9f477726168
refs/heads/master
2016-09-13T13:57:44.543409
2016-05-22T04:42:47
2016-05-22T04:42:47
58,123,880
0
0
null
null
null
null
UTF-8
C++
false
false
5,413
h
#pragma once #ifndef UI_ANIMATION_H #define UI_ANIMATION_H //////////////////////////////////////////////////////////////////////// // // // File: UIAnimation.h // // Class: class UIAnimation : base // // class UITransAnimation : preset: Translate // // class UIWaitAnimation : preset: Waiting // // class UIScaleAnimation : preset: Scale // // class UIAlphaAnimation : preset: Opaque // // < Class Declaration > // // Description: UI Animations // // // //////////////////////////////////////////////////////////////////////// class UIObject; //-- Enum for modes that where should UI object be when its animation ends. enum AnimationStopEnum { STOP_AT_ORIGIN, STOP_AT_DESTINATION, STOP_AT_PATH }; //-- Class UIAnimation class UIAnimation { protected: //================================================= protected members ==========================================================// //-- The UI object this animation has effect on. UIObject* object; //-- How long this animation lasts in one loop cycle. (in seconds) float timeLast; //-- Whether this animation should be played in loop. bool isLoop; //-- Where should the UI object be when animation stops. AnimationStopEnum stopAt; //-- Has the UI object reaches animation destination. bool isReachDest = false; //-- Should this animation be over. bool isOver = false; //-- The Animation attached to this animation. //-- If not nullptr, attached animation should have effect when this animation ends. UIAnimation* attach = nullptr; //-- Callback function upon this animation ends void (*onStop)(); //================================================= protected virtual functions ====================================================// //-- How to interpolates its value from current to destination. //-- According to (timeLast) & (destination - origin) & (Time::getInstance()->delta). virtual void interpolate() {} //-- How to make the UI object return back to original state. virtual void mergeToOri() {} //-- How to make the UI object jump to destination. virtual void mergeToDest() {} //-- How to judge whether this animation would go over the destination in the next frame. virtual bool overDest() { return true; } public: //=============================================== Constructors & Destructor ======================================================// //-- Consructor. UIAnimation(UIObject* object, float timeLast, bool isLoop, AnimationStopEnum stopAt); //-- Destructor. ~UIAnimation(); //================================================= public functions =============================================================// //-- Return whether this animation should be over. bool getIsOver(); //-- Start this animation. void start(); //-- End this animation. void end(); //-- Update function. //-- Called in the UI object update(). //-- Effect between start() & end(). void update(); //-- Attach an animation to this animation. //-- It would be played when this animation ends. void setAttachedAnimation(UIAnimation* anim); //-- Start this animation after some delay. (time in seconds) void startAfter(float time); //-- Set its onStop function void setOnStop(void(*onStop)()); }; //-- Class UITransAniamtion class UITransAnimation : public UIAnimation { protected: int oriX, oriY; int destX, destY; float getInterpolateX(); float getInterpolateY(); void interpolate() override; void mergeToOri() override; void mergeToDest() override; bool overDest() override; public: UITransAnimation(UIObject* object, int oriX, int oriY, int destX, int destY, float timeLast, bool isLoop, AnimationStopEnum stopAt); }; //-- Class UIWaitAnimation class UIWaitAnimation : public UIAnimation { protected: float timePast = 0; float getInterpolation(); void interpolate() override; void mergeToOri() override; void mergeToDest() override; bool overDest() override; public: UIWaitAnimation(UIObject* object, float timeLast); }; //-- Class UIScaleAnimation class UIScaleAnimation : public UIAnimation { protected: float oriX, oriY; float destX, destY; float getInterpolateX(); float getInterpolateY(); void interpolate() override; void mergeToOri() override; void mergeToDest() override; bool overDest() override; public: UIScaleAnimation(UIObject* object, float oriX, float oriY, float destX, float destY, float timeLast, bool isLoop, AnimationStopEnum stopAt); }; //-- Class UIAlphaAnimation class UIAlphaAnimation : public UIAnimation { protected: float oriAlpha; float destAlpha; float getInterpolation(); void interpolate() override; void mergeToOri() override; void mergeToDest() override; bool overDest() override; public: UIAlphaAnimation(UIObject* object, float oriAlpha, float destAlpha, float timeLast, bool isLoop, AnimationStopEnum stopAt); }; #endif // ! UI_ANIMATION_H
[ "905479399@qq.com" ]
905479399@qq.com
58a36a922daf748a224f3be00c5c93e5fd8e054f
9542f1e34910ced36d7422944ace8fc126a1b645
/Datamodel/accent.cpp
dcb84f36e910ddc25db37eaeff3e5b521ca348a0
[]
no_license
johndpope/Counterpoint-project
eee0bad93057cd6a500c2c7377be9b58c09a8866
6b0e46b6830d38f03e5f84236bb8a350db90cfc3
refs/heads/master
2021-04-29T05:22:28.516769
2015-12-07T18:21:21
2015-12-07T18:21:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
221
cpp
#include "accent.h" Accent::Accent(accents accent) { this->accent = accent; } Accent::accents Accent::getAccent() const { return accent; } void Accent::setAccent(const accents &value) { accent = value; }
[ "kollgergo@gmail.com" ]
kollgergo@gmail.com
7678ab3145b30cb585d64f41754c0bbd93b9a691
b41d72d1091dcd6ff7d75542fb0e3ed66ee8234e
/压缩软件/压缩软件.cpp
6f4782493c4d1a6516c9976ddb9c4929460d6405
[]
no_license
wyf18/Compression-software-text
d8fc322a507cef13a31ba3a73588d5abb9d0684e
ce534bd1b9bd1170c7cf5ca2b0212155054975f0
refs/heads/master
2022-03-23T13:37:14.908714
2019-03-30T04:29:37
2019-03-30T04:29:37
178,411,076
5
0
null
null
null
null
UTF-8
C++
false
false
8,122
cpp
// 压缩软件.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <iostream> #include<fstream> #include<time.h> #include"huffmantree.h" using namespace std; const int MAX = 255; void Count(int *count, unsigned char *buf,int filelen);//计算频率 HuffmanTree BuildHuffTree(int *count,int filelen, unsigned char *buf);//建立huffman树 vector<vector<int>> GetandOutputcode(HuffmanTree tree1, int filelen,unsigned char*buf);//获得并输出编码 void Binarycode(int filelen,unsigned char *buf, vector<vector<int>>&code);//压缩编码 char Transinttochar(int *buffer);//将8位01序列转换为ASCII码 void Transchartoint(int x, int *a);//将数字转换为二进制 int Translate(HuffmanTree tree1);//对B1进行译码并写入文件C //void Write(HuffmanTree tree1, vector<int> &source);//直接对编码解码并写入D int main() { //读取文件名 cout << "请输入要压缩的文件名:"; char name[MAX]; cin.getline(name,MAX); //计算程序执行时间 clock_t start, finish; double totaltime; start = clock(); //读取文件中的字符 FILE *file1 = NULL; file1 = fopen(name, "rb");//只读方式打开文件 if (file1 == NULL) { cout << "文件打开失败!"; exit(1); } cout << "文件打开成功" << endl; //获得文件长度 fseek(file1, 0, SEEK_END); //文件指针移到末尾 int filelen = ftell(file1); //获得文件当前指针位置,即为文件长度 rewind(file1); //将文件指针移到开头,准备读取 unsigned char *buf = (unsigned char *)malloc(filelen); //新建缓冲区,存储读出的数据 for (int i = 0; i < filelen; i++)//将缓冲区的数据设置为0 buf[i] = 0; fread(buf, 1, filelen, file1);//读取文件 fclose(file1);//关闭文件 cout << "文件读取完毕" << endl; int count[MAX];//记录每个编码出现次数 Count(count,buf, filelen);//计算频率 HuffmanTree tree1 = BuildHuffTree(count, filelen, buf);//建立huffman树 cout << "huffman树已建立" << endl; vector<vector<int>>code(MAX);//获取编码 for (int i = 0; i < MAX; i++) code[i] = tree1.GetCode(i); //code= GetandOutputcode(tree1, filelen, buf);//获得并输出编码 //cout << "编码以01序列的形式储存在B1……" << endl; Binarycode(filelen, buf, code);//输出压缩编码 cout << "压缩编码已存入B" << endl; int filelenB=Translate(tree1);//对B1进行译码并写入文件C cout << "译码已存入文件C" << endl; double rate=(double)filelenB/filelen; cout << "压缩比为:"<<rate << endl; //Write(tree1, source);//直接对编码解码并写入D free(buf);//释放缓冲区 //输出程序运行时间 finish = clock(); totaltime = (double)(finish - start) / CLOCKS_PER_SEC; cout << "此程序的运行时间为" << totaltime << "秒!" << endl; return 0; } //计算频率 void Count(int *count,unsigned char *buf,int filelen) { for (int i = 0; i < MAX; i++) count[i] = 0; //记录每个8位二进制串出现次数 for (int i = 0; i < filelen; i++) count[buf[i]]++; } //建立huffman树 HuffmanTree BuildHuffTree(int *count,int filelen,unsigned char *buf) { for (int i = 0; i < MAX; i++) count[i] = 0; //记录每个8位二进制串出现次数 for (int i = 0; i < filelen; i++) count[buf[i]]++; //建立huffman树 vector< HuffmanNode> leafs(MAX);//对每个ASCII码进行huffman编码 for (int i = 0; i < 255; i++)//每个结点的符号 { leafs[i].data = i; } for (int i = 0; i < MAX; i++)//每个结点的权值,为其出现的频率 leafs[i].weight = count[i]; HuffmanTree tree1(leafs);//建立huffman树 return tree1; } //获得编码 vector<vector<int>> GetandOutputcode(HuffmanTree tree1,int filelen,unsigned char*buf) { //对文件中字符进行编码 vector<vector<int>> code(MAX); for (int i = 0; i < MAX; i++) { code[i] = tree1.GetCode(i); } //输出编码到文件B /*ofstream file2("B1.txt"); if (!file2.is_open()) { cout << "文件B1打开失败!"; exit(1); } //展示编码 for (int i = 0; i < filelen; i++) { int x;//code下标 x = buf[i]; for (unsigned int j = 0; j < code[x].size(); j++) { file2 << code[x][j]; //source.push_back(code[x][j]); } } file2.close();*/ return code; } //压缩编码 void Binarycode(int filelen,unsigned char *buf,vector<vector<int>>&code) { ofstream file4("B.txt"); if (!file4.is_open()) { cout << "文件B打开失败!"; exit(1); } int buffer[8];//用作缓冲区 for(int i=0;i<8;i++) buffer[i] = 0; int bufcount = 0;//缓冲字节数,初始为0 //输出编码到文件B for (int i = 0; i < filelen; i++) { int x;//code下标 x = buf[i]; for (unsigned int j = 0; j < code[x].size(); j++) { if (bufcount == 8) { file4 << Transinttochar(buffer); bufcount = 0; } buffer[bufcount] = code[x][j]; bufcount++; } } //最后一位 if (bufcount != 0) { file4 << Transinttochar(buffer); } char lackcount = bufcount;//缺位数,以char的形式放最后 file4 << lackcount; file4.close(); } //对B进行译码并写入文件C int Translate(HuffmanTree tree1) { //读出文件B的内容 FILE *file1 = NULL; file1 = fopen("B.txt", "rb");//只读方式打开文件 if (file1 == NULL) { cout << "文件B打开失败!"; exit(1); } //获得文件长度 fseek(file1, 0, SEEK_END); //文件指针移到末尾 int filelenB = ftell(file1); //获得文件当前指针位置,即为文件长度 //读取文件 rewind(file1); //将文件指针移到开头,准备读取 unsigned char *buf1 = (unsigned char *)malloc(filelenB); //新建缓冲区,存储读出的数据 for (int i = 0; i < filelenB; i++)//将缓冲区的数据设置为0 buf1[i] = 0; fread(buf1, 1, filelenB, file1);//读取文件 fclose(file1);//关闭文件 //对编码进行译码 vector<int>source1;//读出的编码 int a[8];//储存数字 for (int i = 0; i < 8; i++) a[i] = 0; for (int i = 0; i < filelenB-2; i++) { if (buf1[i] == 13 && buf1[i + 1] == 10)//如果遇到回车换行符就略过回车符 continue; Transchartoint(buf1[i],a); for (int j = 0; j < 8; j++) source1.push_back(a[j]); } //倒数第二位是一个字符,最后一位是缺位数,字符的二进制只读到缺位数 int lackcount = buf1[filelenB - 1]; Transchartoint(buf1[filelenB-2], a); for (int j = 0; j < lackcount; j++) source1.push_back(a[j]); //输入文件C ofstream file3("C.txt", ios::binary); if (!file3.is_open()) { cout << "文件C打开失败!"; exit(1); } vector<char> result; tree1.Decode(source1, result); for (unsigned int i = 0; i < result.size(); i++) { file3 << result[i]; } file3.close(); return filelenB; } //将8位01序列转换为ASCII码 char Transinttochar(int *buffer) { char x; x = buffer[0]*128+buffer[1] * 64 + buffer[2] * 32 + buffer[3] * 16 + buffer[4] * 8 + buffer[5] * 4 + buffer[6] * 2 + buffer[7] * 1; return x; } //将数字转换为二进制 void Transchartoint(int x,int *a) { for (int i = 7; i >= 0; i--) { a[i] = x % 2; x = x / 2; } } //直接对B编码解码并写入D /*void Write(HuffmanTree tree1, vector<int> &source) { //对编码进行译码并输入文件C ofstream file3("D.txt", ios::binary); if (!file3.is_open()) { cout << "文件D打开失败!"; exit(1); } vector<char> result; tree1.Decode(source, result); for (unsigned int i = 0; i < result.size(); i++) { file3 << result[i]; } file3.close(); }*/ // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门提示: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
[ "44402561+Aefile@users.noreply.github.com" ]
44402561+Aefile@users.noreply.github.com
9337f3b77fb05a44242c724f67b800281e4e8a62
49ee49ee34fa518b0df934081f5ea44a0faa3451
/Books/APUE/ch11/use_barrier.cpp
b2f027189409454453f912941dfd82609e50f96b
[ "MIT" ]
permissive
kingsamchen/Eureka
a9458fcc7d955910bf2cefad3a1561cec3559702
e38774cab5cf757ed858547780a8582951f117b4
refs/heads/master
2023-09-01T11:32:35.575951
2023-08-27T15:21:42
2023-08-27T15:22:31
42,903,588
28
16
MIT
2023-09-09T07:33:29
2015-09-22T01:27:05
C++
UTF-8
C++
false
false
934
cpp
/* @ 0xCCCCCCCC */ #include <iostream> #include <random> #include <pthread.h> int g_seq[2]; pthread_barrier_t barrier; void* ThreadFunc(void* arg) { std::random_device rd; auto seq = rd(); auto idx = reinterpret_cast<long>(arg); std::cout << "thread " << idx << " is done and ready to wait\n"; pthread_barrier_wait(&barrier); g_seq[idx] = seq; return reinterpret_cast<void*>(0); } int main() { pthread_barrier_init(&barrier, nullptr, 2); constexpr int kThreadNum = 2; pthread_t threads[kThreadNum]; for (int i = 0; i < kThreadNum; ++i) { pthread_create(&threads[i], nullptr, ThreadFunc, reinterpret_cast<void*>(i)); } for (int i = 0; i < kThreadNum; ++i) { pthread_join(threads[i], nullptr); } std::cout << "Generated seq are: " << g_seq[0] << "\t" << g_seq[1] << "\n"; pthread_barrier_destroy(&barrier); return 0; }
[ "kingsamchen@gmail.com" ]
kingsamchen@gmail.com
1687c7caabb33ecfa0b3589c4958a0016dcbcfda
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/inetcore/winhttp/v5/rockall/interface/smallheap.hpp
5573bead2c366a1b0674bff3ed41dc2c2dadd18b
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
2,880
hpp
#ifndef _SMALL_HEAP_HPP_ #define _SMALL_HEAP_HPP_ // Ruler // 1 2 3 4 5 6 7 8 //345678901234567890123456789012345678901234567890123456789012345678901234567890 /********************************************************************/ /* */ /* The standard layout. */ /* */ /* The standard layout for 'hpp' files for this code is as */ /* follows: */ /* */ /* 1. Include files. */ /* 2. Constants exported from the class. */ /* 3. Data structures exported from the class. */ /* 4. Forward references to other data structures. */ /* 5. Class specifications (including inline functions). */ /* 6. Additional large inline functions. */ /* */ /* Any portion that is not required is simply omitted. */ /* */ /********************************************************************/ #include "Rockall.hpp" /********************************************************************/ /* */ /* A small heap. */ /* */ /* A small heap tries to significantly reduce memory usage */ /* even if that comes at a significant cost in terms of */ /* performance. */ /* */ /********************************************************************/ class ROCKALL_DLL_LINKAGE SMALL_HEAP : public ROCKALL { public: // // Public functions. // SMALL_HEAP ( int MaxFreeSpace = 0, bool Recycle = false, bool SingleImage = false, bool ThreadSafe = true ); ~SMALL_HEAP( void ); private: // // Disabled operations. // // All copy constructors and class assignment // operations are disabled. // SMALL_HEAP( const SMALL_HEAP & Copy ); void operator=( const SMALL_HEAP & Copy ); }; #endif
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
f0e074455b1848830611b3a1cad8d208adca84f2
77c102f73d58b1e445ce5ed1efd868e5ec82b336
/Other PS/pivot/test.cpp
6ae1be09ac447060aa1affffee0c6e68cadb3f63
[]
no_license
XIA-LIYI/Algorithms
450fa94ca5f2d82d2d84e43dc7cfc2488edb27b8
4030c5ebd1b6700172c3e28f394aaa8cffd3b5f7
refs/heads/main
2023-04-02T16:27:25.654734
2021-03-26T07:33:33
2021-03-26T07:33:33
351,694,641
0
0
null
null
null
null
UTF-8
C++
false
false
617
cpp
#include<iostream> #include<vector> #include<list> using namespace std; int main(){ freopen("2.in","r",stdin); list<pair<int, int> > lst; long N; cin>>N; long max;cin>>max;lst.push_back(make_pair(max,1)); long min; for (long i = 0; i < N-1; ++i){ long a; cin>>a; if (a < max) lst.push_back(make_pair(a,0)); else{ lst.push_back(make_pair(a,1)); max=a; } } min=lst.end()->first; auto a=lst.end(); for (int i = 0; i < N+1; ++i){ if (a->first <= min){ min=a->first; a->second+=1; } a--; } long num=0; for (auto &a: lst){ if (a.second == 2) num+=1; } cout<<num; }
[ "xialiyi110@gmail.com" ]
xialiyi110@gmail.com
dc70064f46fa5cecf27d26df76b0c2777763a781
5870bb19b53c61508c2e57499ab6f10252200dee
/stroustroup/ch14/test0.cpp
92df106ec45edb26c0eb3c70384505509ba93f07
[]
no_license
blockspacer/test-cpp
40371c04864fd632e78e9e4da2dea6c80b307d2f
d70e8f77d1d8129266afd7e9a2c4c4c051068af1
refs/heads/master
2020-07-05T20:02:09.661427
2019-08-02T07:50:39
2019-08-02T07:50:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,438
cpp
#include <iostream> namespace Chrono { class Date {}; bool operator==(Date const&, std::string const&) { return true; } std::string format(Date const&) { return "abcd"; } } void f(Chrono::Date d, int i) { std::string s = format(d); // below causes an error // std::string t = format(i); } namespace N { struct S { int i; }; void f(S) {} void g(S) {} void h(int) {} } struct Base { void f(N::S) {}; }; struct D : Base { void g() { N::S x; f(x); // Argument Dependent Lookup rules prohibit h(1)! N::h(1); } }; namespace NNN { template<typename T> void f(T, int) { std::cout << "calling NNN::f" << std::endl; } class X {}; } namespace NNN2 { NNN::X x; void f(NNN::X, unsigned) { std::cout << "calling NNN2::f"<< std::endl; } void g() { f(x, 1); } } namespace XXX { int i = 0; } namespace YYY { using XXX::i; } namespace X { int i, j, k; } int k; void f1() { int i = 0; using namespace X; i++; j++; k++; //error: reference to 'k' is ambiguous ::k++; X::k++; } void f2() { int i = 0; using X::i; // error: target of using declaration conflicts with declaration already in using X::j; using X::k; i++; j++; k++; } namespace long_namespace_name { } int main() { NNN2::g(); std::cout << YYY::i << std::endl; namespace lnn = long_namespace_name; }
[ "vdkhristenko1991@gmail.com" ]
vdkhristenko1991@gmail.com
20e822cf3cedfa10a9e0883c8fad0796823854b7
bae76888e633874c1278a43bb5773aae8201c44d
/CPSeis/wrappers/src/org/cpseis/wrappers/CpseisOff2ang.cc
8c675b8560db82e9d7bd338a40a660b92ee585c9
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
Chen-Zhihui/SeismicPackage
a242f9324c92d03383b06f068c9d2f64a47c5c3f
255d2311bdbbacad2cb19aa3b91ceb84a733a194
refs/heads/master
2020-08-16T05:28:19.283337
2016-11-25T02:24:14
2016-11-25T02:24:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,509
cc
//////// DO NOT EDIT THIS FILE - it is machine generated //////// #include "CpseisOff2ang.hh" //------------------ fortran spelling adjustments --------------------// //------------------ fortran spelling adjustments --------------------// //------------------ fortran spelling adjustments --------------------// #if NEED_UNDERSCORE #define off2ang_wrap_create off2ang_wrap_create_ #define off2ang_wrap_delete off2ang_wrap_delete_ #define off2ang_wrap_update off2ang_wrap_update_ #define off2ang_wrap_wrapup off2ang_wrap_wrapup_ #define off2ang_wrap_oneset off2ang_wrap_oneset_ #define off2ang_wrap_twosets off2ang_wrap_twosets_ #elif NEED_CAPITALS #define off2ang_wrap_create OFF2ANG_WRAP_CREATE #define off2ang_wrap_delete OFF2ANG_WRAP_DELETE #define off2ang_wrap_update OFF2ANG_WRAP_UPDATE #define off2ang_wrap_wrapup OFF2ANG_WRAP_WRAPUP #define off2ang_wrap_oneset OFF2ANG_WRAP_ONESET #define off2ang_wrap_twosets OFF2ANG_WRAP_TWOSETS #endif //----------------------- fortran prototypes -------------------------// //----------------------- fortran prototypes -------------------------// //----------------------- fortran prototypes -------------------------// extern "C" { CpseisBase::ModuleCreate off2ang_wrap_create; CpseisBase::ModuleDestroy off2ang_wrap_delete; CpseisBase::ModuleUpdate off2ang_wrap_update; CpseisBase::ModuleWrapup off2ang_wrap_wrapup; CpseisBase::ModuleOneset off2ang_wrap_oneset; CpseisBase::ModuleTwosets off2ang_wrap_twosets; } //------------------------ constructor -------------------------------// //------------------------ constructor -------------------------------// //------------------------ constructor -------------------------------// CpseisOff2ang::CpseisOff2ang() : CpseisBase ("OFF2ANG", off2ang_wrap_create, off2ang_wrap_delete, off2ang_wrap_update, off2ang_wrap_wrapup, off2ang_wrap_oneset, off2ang_wrap_twosets) {} //------------------------------ end ---------------------------------// //------------------------------ end ---------------------------------// //------------------------------ end ---------------------------------//
[ "Uqer@d-i89-169-66.student.eduroam.uq.edu.au" ]
Uqer@d-i89-169-66.student.eduroam.uq.edu.au
7af4dc9bff398f11b95953709ce9d6a159c98167
1ac04ddeae434c64fc10e2194a65c249d02129de
/src/codechef/MSNG.cpp
05c5939be2c557f0586d5324803704e23347ad42
[]
no_license
VIPUL1306/cp_practice
f68de30c9d0af343d77ceda1397d14f22077b5d9
a439e8cdec79962be6a168cdd70bad848138d757
refs/heads/master
2023-09-03T01:49:54.492499
2020-10-01T05:03:22
2020-10-01T05:03:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,638
cpp
// https://www.codechef.com/OCT19B/problems/MSNG #include<bits/stdc++.h> #define ll long long int #define MAXVAL 1000000000000 #define MAXBASE 36 using namespace std; map<char,int> char_map; unordered_map<int,vector<string>> ump; map<ll,ll> mp; void create_mapping(){ char c = '0'; for(int i = 0;i<10;i++)char_map[c+i] = i; c = 'A'; for(int i = 0;i<26;i++) char_map[c+i] = i+10; } ll power(ll a, ll b){ ll res = 1; while(b){ if(b&1) res = res * a; if(res > MAXVAL) return -1; a = a * a; b >>= 1; } return res; } ll get_decimal(string str, ll base){ ll num = 0,p=0,f; for(int k = str.length()-1;k>=0;k--){ f = power(base,p); if(f == -1) return -1; num += char_map[str[k]]*f; if(num>MAXVAL) return -1; p++; } return num; } void generate_all_numbers(ll val){ if(ump[-1].size()==0) return; vector<string> v = ump[-1]; ll n = v.size(); for(int i = 0;i<n;i++){ string str = v[i]; int base = INT_MIN; map<ll,ll> temp_mp; for(int j = 0;j<str.length();j++){ if(base<char_map[str[j]]) base = char_map[str[j]]; } base = base + 1; for(int j = base;j<=MAXBASE;j++){ ll num = 0,p=0,f; for(int k = str.length()-1;k>=0;k--){ f = power(j,p); if(f==-1) {num = MAXVAL+4;break;} num += char_map[str[k]]*f; if(num>MAXVAL) break; p++; } if(num>=0&&num<=MAXVAL) temp_mp[num]++; } for(auto x : temp_mp){ if(x.second>0) mp[x.first]++; } } } int main(){ freopen("input.txt","r",stdin); ios_base::sync_with_stdio(false); cin.tie(nullptr); create_mapping(); ll t,n,a; string s; cin>>t; while(t--){ cin>>n; ll ans = 0; ump.clear(),mp.clear(); for(int i = 0;i<n;i++){ cin>>a>>s; if(a!=-1){ if(ump[a].size()==1){ if(ump[a][0]!=s) ump[a].push_back(s); }else ump[a].push_back(s); }else if(a==-1) ump[a].push_back(s); } n = ump.size() + (ump[-1].size()>0?ump[-1].size()-1:0); ll val = LONG_MIN,b; for(auto x: ump){ if(x.first!=-1 && x.second.size()==1){ b = get_decimal(x.second[0],x.first); if(b == -1){ ans = -1; break;} if(val==LONG_MIN) val = b; if(val!=b || b>MAXVAL){ans = -1;break;} mp[b]++; }else if(x.first!=-1 && x.second.size()>1){ ans = -1; break; } } if(ans != -1){ if(val == LONG_MIN) val = LONG_MAX; generate_all_numbers(val); ll min_val = LONG_MAX; for(auto x : mp){ // cout<<x.first<<" "<<x.second<<"\n"; if(x.second == n){ if(min_val>x.first) min_val = x.first; } } if(min_val == LONG_MAX) ans = -1; else ans = min_val; } if(ans>MAXVAL) ans = -1; cout<<ans<<"\n"; } return 0; }
[ "prakash.nath@students.iiit.ac.in" ]
prakash.nath@students.iiit.ac.in
23dff38b540582af0a9b41c7e913df2b4dc4742c
4758f6e0d4427ee8e88a2b7d562affec864ce1cf
/SimpleHammer.cpp
7df14a2cb70bf4c2e0080608d70da2c57bf8078a
[]
no_license
GWCangie/Assignment1
2160e232e6865cd18ec41caf801d85ac6ce4fccc
ba40a46d25959d63a49f272da8376767dcf1a162
refs/heads/master
2020-04-18T09:34:35.772245
2019-02-02T20:57:53
2019-02-02T20:57:53
167,439,056
0
0
null
2019-01-24T21:16:31
2019-01-24T21:16:31
null
UTF-8
C++
false
false
317
cpp
/* * File: SimpleHammer.cpp * Author: Angela <amd15t@my.fsu.esu> * */ #include "SimpleHammer.h" double SimpleHammer::hit(double armor){ double damage = 0; if (armor <30 ) damage = hitPoints; else damage = hitPoints - armor; if(damage < 0) return 0; return damage; }
[ "amd15t@my.fsu.edu" ]
amd15t@my.fsu.edu
5b94982f4710703938af71262fcea2bdf9548b27
1cd376c43e0c06f04585c2bd2b8a638d0213bdba
/src/prom_exporter/check_names.cc
1885eb8f22bdcb7f54047b9916557a9a26ce872e
[ "MIT" ]
permissive
HanixNicolas/app-mesh
4c7bf38467ccb74f0055ce0500e7fa645348d03b
8ee77a6adb1091b3a0afcbc34d271b4b9508840e
refs/heads/main
2023-09-01T10:46:59.218660
2021-09-26T09:39:11
2021-09-26T09:39:11
410,509,095
0
0
MIT
2021-09-26T09:34:43
2021-09-26T09:34:42
null
UTF-8
C++
false
false
1,953
cc
#include "check_names.h" #include <algorithm> #include <iterator> namespace prometheus { namespace { bool isLocaleIndependentAlphaNumeric(char c) { return ('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); } bool isLocaleIndependentDigit(char c) { return '0' <= c && c <= '9'; } bool nameStartsValid(const std::string& name) { // must not be empty if (name.empty()) { return false; } // must not start with a digit if (isLocaleIndependentDigit(name.front())) { return false; } // must not start with "__" auto reserved_for_internal_purposes = name.compare(0, 2, "__") == 0; if (reserved_for_internal_purposes) return false; return true; } } // anonymous namespace /// \brief Check if the metric name is valid /// /// The metric name regex is "[a-zA-Z_:][a-zA-Z0-9_:]*" /// /// \see https://prometheus.io/docs/concepts/data_model/ /// /// \param name metric name /// \return true is valid, false otherwise bool CheckMetricName(const std::string& name) { if (!nameStartsValid(name)) { return false; } auto validMetricCharacters = [](char c) { return isLocaleIndependentAlphaNumeric(c) || c == '_' || c == ':'; }; auto mismatch = std::find_if_not(std::begin(name), std::end(name), validMetricCharacters); return mismatch == std::end(name); } /// \brief Check if the label name is valid /// /// The label name regex is "[a-zA-Z_][a-zA-Z0-9_]*" /// /// \see https://prometheus.io/docs/concepts/data_model/ /// /// \param name label name /// \return true is valid, false otherwise bool CheckLabelName(const std::string& name) { if (!nameStartsValid(name)) { return false; } auto validLabelCharacters = [](char c) { return isLocaleIndependentAlphaNumeric(c) || c == '_'; }; auto mismatch = std::find_if_not(std::begin(name), std::end(name), validLabelCharacters); return mismatch == std::end(name); } } // namespace prometheus
[ "178029200@qq.com" ]
178029200@qq.com
95bb0dd305c1d9d405bdff220ae43a887f515257
082b4cde1fff6ac9085f4666b36fdaef4198e1f1
/molequeue/app/queues/uit/sslsetup.h
08d3dbe025a578a93b200d331f9d7962d378b2f5
[ "BSD-3-Clause" ]
permissive
CodeAnk2829/molequeue
89f54602bec12e32937b8ab2ad958095d51c0c82
9a2de9e1ad7322342392a68c739d62cc1805c6f8
refs/heads/master
2023-04-15T10:42:54.250490
2023-04-01T03:01:10
2023-04-01T03:01:10
621,857,294
0
0
BSD-3-Clause
2023-04-01T03:01:11
2023-03-31T14:35:17
null
UTF-8
C++
false
false
970
h
/****************************************************************************** This source file is part of the MoleQueue project. Copyright 2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 SSLSETUP_H_ #define SSLSETUP_H_ namespace MoleQueue { namespace Uit { /** * @brief class used to initalize SSL certificates for QSslSocket. */ class SslSetup { private: SslSetup(); static bool sslCertsLoaded; public: static void init(); }; } /* namespace Uit */ } /* namespace MoleQueue */ #endif /* SSLSETUP_H_ */
[ "chris.harris@kitware.com" ]
chris.harris@kitware.com
15cfda188d871569790d072da51504d3ece9ed79
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/boost/graph/bipartite.hpp
9d2323d6d4218422b1409cc91d59dc3ce6ec4edb
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,988
hpp
/** * * Copyright (c) 2010 Matthias Walter (xammy@xammy.homelinux.net) * * Authors: Matthias Walter * * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * */ #ifndef BOOST_GRAPH_BIPARTITE_HPP #define BOOST_GRAPH_BIPARTITE_HPP #include <utility> #include <vector> #include <exception> #include <sstd/boost/graph/properties.hpp> #include <sstd/boost/graph/adjacency_list.hpp> #include <sstd/boost/graph/depth_first_search.hpp> #include <sstd/boost/graph/one_bit_color_map.hpp> #include <sstd/boost/bind.hpp> namespace boost { namespace detail { /** * The bipartite_visitor_error is thrown if an edge cannot be colored. * The witnesses are the edges incident vertices. */ template <typename Vertex> struct bipartite_visitor_error: std::exception { std::pair <Vertex, Vertex> witnesses; bipartite_visitor_error (Vertex a, Vertex b) : witnesses (a, b) { } const char* what () const throw () { return "Graph is not bipartite."; } }; /** * Functor which colors edges to be non-monochromatic. */ template <typename PartitionMap> struct bipartition_colorize { typedef on_tree_edge event_filter; bipartition_colorize (PartitionMap partition_map) : partition_map_ (partition_map) { } template <typename Edge, typename Graph> void operator() (Edge e, const Graph& g) { typedef typename graph_traits <Graph>::vertex_descriptor vertex_descriptor_t; typedef color_traits <typename property_traits <PartitionMap>::value_type> color_traits; vertex_descriptor_t source_vertex = source (e, g); vertex_descriptor_t target_vertex = target (e, g); if (get (partition_map_, source_vertex) == color_traits::white ()) put (partition_map_, target_vertex, color_traits::black ()); else put (partition_map_, target_vertex, color_traits::white ()); } private: PartitionMap partition_map_; }; /** * Creates a bipartition_colorize functor which colors edges * to be non-monochromatic. * * @param partition_map Color map for the bipartition * @return The functor. */ template <typename PartitionMap> inline bipartition_colorize <PartitionMap> colorize_bipartition (PartitionMap partition_map) { return bipartition_colorize <PartitionMap> (partition_map); } /** * Functor which tests an edge to be monochromatic. */ template <typename PartitionMap> struct bipartition_check { typedef on_back_edge event_filter; bipartition_check (PartitionMap partition_map) : partition_map_ (partition_map) { } template <typename Edge, typename Graph> void operator() (Edge e, const Graph& g) { typedef typename graph_traits <Graph>::vertex_descriptor vertex_descriptor_t; vertex_descriptor_t source_vertex = source (e, g); vertex_descriptor_t target_vertex = target (e, g); if (get (partition_map_, source_vertex) == get (partition_map_, target_vertex)) throw bipartite_visitor_error <vertex_descriptor_t> (source_vertex, target_vertex); } private: PartitionMap partition_map_; }; /** * Creates a bipartition_check functor which raises an error if a * monochromatic edge is found. * * @param partition_map The map for a bipartition. * @return The functor. */ template <typename PartitionMap> inline bipartition_check <PartitionMap> check_bipartition (PartitionMap partition_map) { return bipartition_check <PartitionMap> (partition_map); } /** * Find the beginning of a common suffix of two sequences * * @param sequence1 Pair of bidirectional iterators defining the first sequence. * @param sequence2 Pair of bidirectional iterators defining the second sequence. * @return Pair of iterators pointing to the beginning of the common suffix. */ template <typename BiDirectionalIterator1, typename BiDirectionalIterator2> inline std::pair <BiDirectionalIterator1, BiDirectionalIterator2> reverse_mismatch (std::pair < BiDirectionalIterator1, BiDirectionalIterator1> sequence1, std::pair <BiDirectionalIterator2, BiDirectionalIterator2> sequence2) { if (sequence1.first == sequence1.second || sequence2.first == sequence2.second) return std::make_pair (sequence1.first, sequence2.first); BiDirectionalIterator1 iter1 = sequence1.second; BiDirectionalIterator2 iter2 = sequence2.second; while (true) { --iter1; --iter2; if (*iter1 != *iter2) { ++iter1; ++iter2; break; } if (iter1 == sequence1.first) break; if (iter2 == sequence2.first) break; } return std::make_pair (iter1, iter2); } } /** * Checks a given graph for bipartiteness and fills the given color map with * white and black according to the bipartition. If the graph is not * bipartite, the contents of the color map are undefined. Runs in linear * time in the size of the graph, if access to the property maps is in * constant time. * * @param graph The given graph. * @param index_map An index map associating vertices with an index. * @param partition_map A color map to fill with the bipartition. * @return true if and only if the given graph is bipartite. */ template <typename Graph, typename IndexMap, typename PartitionMap> bool is_bipartite (const Graph& graph, const IndexMap index_map, PartitionMap partition_map) { /// General types and variables typedef typename property_traits <PartitionMap>::value_type partition_color_t; typedef typename graph_traits <Graph>::vertex_descriptor vertex_descriptor_t; /// Declare dfs visitor // detail::empty_recorder recorder; // typedef detail::bipartite_visitor <PartitionMap, detail::empty_recorder> dfs_visitor_t; // dfs_visitor_t dfs_visitor (partition_map, recorder); /// Call dfs try { depth_first_search (graph, vertex_index_map (index_map).visitor (make_dfs_visitor (std::make_pair ( detail::colorize_bipartition (partition_map), std::make_pair (detail::check_bipartition (partition_map), put_property (partition_map, color_traits <partition_color_t>::white (), on_start_vertex ())))))); } catch (detail::bipartite_visitor_error <vertex_descriptor_t> error) { return false; } return true; } /** * Checks a given graph for bipartiteness. * * @param graph The given graph. * @param index_map An index map associating vertices with an index. * @return true if and only if the given graph is bipartite. */ template <typename Graph, typename IndexMap> bool is_bipartite (const Graph& graph, const IndexMap index_map) { typedef one_bit_color_map <IndexMap> partition_map_t; partition_map_t partition_map (num_vertices (graph), index_map); return is_bipartite (graph, index_map, partition_map); } /** * Checks a given graph for bipartiteness. The graph must * have an internal vertex_index property. Runs in linear time in the * size of the graph, if access to the property maps is in constant time. * * @param graph The given graph. * @return true if and only if the given graph is bipartite. */ template <typename Graph> bool is_bipartite (const Graph& graph) { return is_bipartite (graph, get (vertex_index, graph)); } /** * Checks a given graph for bipartiteness and fills a given color map with * white and black according to the bipartition. If the graph is not * bipartite, a sequence of vertices, producing an odd-cycle, is written to * the output iterator. The final iterator value is returned. Runs in linear * time in the size of the graph, if access to the property maps is in * constant time. * * @param graph The given graph. * @param index_map An index map associating vertices with an index. * @param partition_map A color map to fill with the bipartition. * @param result An iterator to write the odd-cycle vertices to. * @return The final iterator value after writing. */ template <typename Graph, typename IndexMap, typename PartitionMap, typename OutputIterator> OutputIterator find_odd_cycle (const Graph& graph, const IndexMap index_map, PartitionMap partition_map, OutputIterator result) { /// General types and variables typedef typename property_traits <PartitionMap>::value_type partition_color_t; typedef typename graph_traits <Graph>::vertex_descriptor vertex_descriptor_t; typedef typename graph_traits <Graph>::vertex_iterator vertex_iterator_t; vertex_iterator_t vertex_iter, vertex_end; /// Declare predecessor map typedef std::vector <vertex_descriptor_t> predecessors_t; typedef iterator_property_map <typename predecessors_t::iterator, IndexMap, vertex_descriptor_t, vertex_descriptor_t&> predecessor_map_t; predecessors_t predecessors (num_vertices (graph), graph_traits <Graph>::null_vertex ()); predecessor_map_t predecessor_map (predecessors.begin (), index_map); /// Initialize predecessor map for (boost::tie (vertex_iter, vertex_end) = vertices (graph); vertex_iter != vertex_end; ++vertex_iter) { put (predecessor_map, *vertex_iter, *vertex_iter); } /// Call dfs try { depth_first_search (graph, vertex_index_map (index_map).visitor (make_dfs_visitor (std::make_pair ( detail::colorize_bipartition (partition_map), std::make_pair (detail::check_bipartition (partition_map), std::make_pair (put_property (partition_map, color_traits <partition_color_t>::white (), on_start_vertex ()), record_predecessors (predecessor_map, on_tree_edge ()))))))); } catch (detail::bipartite_visitor_error <vertex_descriptor_t> error) { typedef std::vector <vertex_descriptor_t> path_t; path_t path1, path2; vertex_descriptor_t next, current; /// First path next = error.witnesses.first; do { current = next; path1.push_back (current); next = predecessor_map[current]; } while (current != next); /// Second path next = error.witnesses.second; do { current = next; path2.push_back (current); next = predecessor_map[current]; } while (current != next); /// Find beginning of common suffix std::pair <typename path_t::iterator, typename path_t::iterator> mismatch = detail::reverse_mismatch ( std::make_pair (path1.begin (), path1.end ()), std::make_pair (path2.begin (), path2.end ())); /// Copy the odd-length cycle result = std::copy (path1.begin (), mismatch.first + 1, result); return std::reverse_copy (path2.begin (), mismatch.second, result); } return result; } /** * Checks a given graph for bipartiteness. If the graph is not bipartite, a * sequence of vertices, producing an odd-cycle, is written to the output * iterator. The final iterator value is returned. Runs in linear time in the * size of the graph, if access to the property maps is in constant time. * * @param graph The given graph. * @param index_map An index map associating vertices with an index. * @param result An iterator to write the odd-cycle vertices to. * @return The final iterator value after writing. */ template <typename Graph, typename IndexMap, typename OutputIterator> OutputIterator find_odd_cycle (const Graph& graph, const IndexMap index_map, OutputIterator result) { typedef one_bit_color_map <IndexMap> partition_map_t; partition_map_t partition_map (num_vertices (graph), index_map); return find_odd_cycle (graph, index_map, partition_map, result); } /** * Checks a given graph for bipartiteness. If the graph is not bipartite, a * sequence of vertices, producing an odd-cycle, is written to the output * iterator. The final iterator value is returned. The graph must have an * internal vertex_index property. Runs in linear time in the size of the * graph, if access to the property maps is in constant time. * * @param graph The given graph. * @param result An iterator to write the odd-cycle vertices to. * @return The final iterator value after writing. */ template <typename Graph, typename OutputIterator> OutputIterator find_odd_cycle (const Graph& graph, OutputIterator result) { return find_odd_cycle (graph, get (vertex_index, graph), result); } } #endif /// BOOST_GRAPH_BIPARTITE_HPP
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
5408f5f28574735726263b3fddcd079dd1183961
370a0dde58adc575a7f7f81f2e158306f018f61f
/src/common/Camera.h
88b4f94acbeff55ed8270592f392ee47287d6af4
[]
no_license
konradsz/oglapp
981a7ca0ba6a2f01fe0b50462b2fc88a54901c7f
50291f8aab1940e4903974945e1b2831bef0daf5
refs/heads/master
2020-12-31T07:33:31.221676
2017-03-22T19:22:08
2017-03-22T19:22:08
80,544,162
0
0
null
null
null
null
UTF-8
C++
false
false
971
h
#pragma once #include <GL/glew.h> #include <glm/glm.hpp> namespace dummy { namespace common { class Camera { public: Camera(const glm::vec3& position, GLfloat pitch, GLfloat yaw); void translate(const glm::vec3& v); void yaw(GLfloat angle); void pitch(GLfloat angle); glm::mat4 getViewMatrix() const; glm::mat4 getProjectionMatrix() const; glm::vec3 getPosition() const; glm::vec3 getDirection() const; glm::vec3 getRight() const; private: void updateDirection(); private: float m_fov; float m_aspectRatio; float m_nearPlane; float m_farPlane; glm::vec3 m_position; glm::vec3 m_direction; glm::vec3 m_up; glm::vec3 m_right; GLfloat m_yaw; GLfloat m_pitch; }; } }
[ "szymoniak.konrad@gmail.com" ]
szymoniak.konrad@gmail.com
74a6ae8f2be4d13057ae227f30a4f639b3749119
96bce60d0fe213fdb2cdf5291d97a45c6c5921d6
/leveldb-master/include/leveldb/comparator.h
e518f142884a4038c5095834d73d62cd0ee6371e
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
AlkaidFlame/leveldb-comment
7a3a6c39c105372a32525b473b06a56f742540d7
4fe3ee388fcc052a8d5df5c821ded0d1c2f0cfed
refs/heads/master
2022-03-04T22:00:01.183453
2018-01-28T14:03:19
2018-01-28T14:03:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,480
h
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #ifndef STORAGE_LEVELDB_INCLUDE_COMPARATOR_H_ #define STORAGE_LEVELDB_INCLUDE_COMPARATOR_H_ #include <string> #include "leveldb/export.h" namespace leveldb { class Slice; // A Comparator object provides a total order across slices that are // used as keys in an sstable or a database. A Comparator implementation // must be thread-safe since leveldb may invoke its methods concurrently // from multiple threads. // Comparator类是一个抽象类,定义了比较器应该实现的接口。 class LEVELDB_EXPORT Comparator { public: virtual ~Comparator(); // Three-way comparison. Returns value: // < 0 iff "a" < "b", // == 0 iff "a" == "b", // > 0 iff "a" > "b" virtual int Compare(const Slice& a, const Slice& b) const = 0; // The name of the comparator. Used to check for comparator // mismatches (i.e., a DB created with one comparator is // accessed using a different comparator. // // The client of this package should switch to a new name whenever // the comparator implementation changes in a way that will cause // the relative ordering of any two keys to change. // // Names starting with "leveldb." are reserved and should not be used // by any clients of this package. virtual const char* Name() const = 0; // Advanced functions: these are used to reduce the space requirements // for internal data structures like index blocks. // If *start < limit, changes *start to a short string in [start,limit). // Simple comparator implementations may return with *start unchanged, // i.e., an implementation of this method that does nothing is correct. virtual void FindShortestSeparator( std::string* start, const Slice& limit) const = 0; // Changes *key to a short string >= *key. // Simple comparator implementations may return with *key unchanged, // i.e., an implementation of this method that does nothing is correct. virtual void FindShortSuccessor(std::string* key) const = 0; }; // Return a builtin comparator that uses lexicographic byte-wise // ordering. The result remains the property of this module and // must not be deleted. LEVELDB_EXPORT const Comparator* BytewiseComparator(); } // namespace leveldb #endif // STORAGE_LEVELDB_INCLUDE_COMPARATOR_H_
[ "TitenWang2013@hotmail.com" ]
TitenWang2013@hotmail.com
9813877e2687c994803d87aa3b12c6fe74b18f3a
06c50a42fb4c8ee0aaf8b8ffb3681c14873db01a
/src/Memory/double_frame_buffer.cpp
b7d0671555793f09c99c1f28aa0c30d0f395373d
[]
no_license
Toadsword/PokEngine
4e42f88ec781c23421db159129642657ad7ce56f
bbf4d68cc2bf96c34cb16a6c19d3c5b849c4d811
refs/heads/master
2022-11-16T08:04:33.947034
2020-07-07T20:49:12
2020-07-07T20:49:12
277,910,114
0
0
null
null
null
null
UTF-8
C++
false
false
117
cpp
#include <Memory/double_frame_buffer.h> namespace poke { namespace memory { } //namespace memory } //namespace poke
[ "bourquardduncan@gmail.com" ]
bourquardduncan@gmail.com
3220cab099ed25443ccc9b6f63ad0eb3399c70c7
869e45a3e5fad2189f9cb05fb01b0e5791ac094a
/Source/Museum/Museum.cpp
868929b8827b98df5716c2e166063b724eeb02a0
[]
no_license
ThePyrotechnic/unreal-software-history
418c9e18f54011bbd25bf0c09ffb6fbb80a7bc68
711a9773824c2b82b7cf87489a99f96a829e482d
refs/heads/master
2020-09-05T09:30:19.540041
2019-12-02T18:11:48
2019-12-02T18:11:48
220,057,412
0
0
null
null
null
null
UTF-8
C++
false
false
217
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Museum.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Museum, "Museum" );
[ "michaelmanis@tutanota.com" ]
michaelmanis@tutanota.com
5ff64d23bd86156f17fdeca736efc5951b9e7d31
e972c781e52ab268ecafd155a5ce063fc6fddf20
/1028.cc
6c46514208852e54b7394eb4b7f4bce64d282373
[]
no_license
zakilo/pat2
d4e98f99446119d565b918a0ed96403bae10fa3e
68f3f8c17afca4e048be8714999e608ee2b5dd2b
refs/heads/master
2021-01-20T04:29:57.986314
2015-04-03T15:59:05
2015-04-03T15:59:05
31,764,614
1
0
null
null
null
null
UTF-8
C++
false
false
954
cc
#include <iostream> #include <cstdio> #include <fstream> #include <algorithm> #include <cstring> #include <vector> using namespace std; struct Stud { int id, sc; char nm[10]; }; bool cmpid(const Stud &s1, const Stud &s2) { return s1.id < s2.id; } bool cmpsc(const Stud &s1, const Stud &s2) { if(s1.sc != s2.sc) return s1.sc < s2.sc; else return s1.id < s2.id; } bool cmpnm(const Stud &s1, const Stud &s2) { int res = strcmp(s1.nm, s2.nm); if(res != 0) return res < 0; else return s1.id < s2.id; } typedef bool (*CmpFun)(const Stud &, const Stud &); int main(void) { #ifdef DEBUG freopen("1028.txt", "r", stdin); #endif CmpFun cmp[3] = {cmpid, cmpnm, cmpsc}; int n, c; scanf("%d%d", &n, &c); vector<Stud> vs; while(n--) { Stud ts; scanf("%d%s%d", &ts.id, ts.nm, &ts.sc); vs.push_back(ts); } sort(vs.begin(), vs.end(), cmp[c-1]); for(const auto &vsm : vs) printf("%06d %s %d\n", vsm.id, vsm.nm, vsm.sc); return 0; }
[ "h@h.com" ]
h@h.com
12a26a0872d3c848d5aadd61ece160c761a43a98
b28dc051483461e0dd55a19d0eeb8dbed539ff59
/Lab4/lab4.cpp
ca38a98c170012e858291b94fd8e735c013d12a3
[]
no_license
sajantanand/CSC112
8941d887c66f0b3b3d989134b66d4a8e378eb049
e50bbdd734ea7cf185baa1cb179b93d5ba8bf01f
refs/heads/master
2021-03-27T14:45:15.105903
2016-11-19T16:47:50
2016-11-19T16:47:50
43,750,367
0
0
null
null
null
null
UTF-8
C++
false
false
8,484
cpp
/** * @file lab4.cpp * @author Sajant Anand (anans14) Section A * @date 2/17/2015 * @version 1.0 * * @brief CSC 112, Lab 4, simulates drunken dancing of a sailor * * @section DESCRIPTION * * This program simulates the drunken dancing of a sailor. The user inputs * number of ex's present at dance, maximum number of steps to be taken by * sailor, and a random seed that is used to generaate random numbers. * */ #include<iostream> #include<cstdlib> #include<unistd.h> #define MAX_SIZE 10 using namespace std; void getExperimentData(int& exes, int& moves, double& seedValue); void setupDanceFloor(int exes, int floorBoard[][MAX_SIZE]); void displayGameBoard(int floorBoard[][MAX_SIZE], int positionX, int positionY); int simulateGame(int floorBoard[][MAX_SIZE], int moves, int& positionX, int& positionY, int& drama); void displayGameResults(int positionX, int positionY, int current, int status); void clearScreen(); int randStep(); /** * @brief main fuction of program, controlls execution * * @param void * @return int - used as a status indicator */ int main() { int floor[MAX_SIZE][MAX_SIZE] = {}; ///<Array that represents dance floor int numEx; ///<Number of ex's at dance int maxMoves; ///<Max number of steps by sailor double seed; ///<Number used to seed ran. numb. gen. int sailorX = 5; ///<Initial x-position of sailor int sailorY = 5; ///<Initial y-position of sailor int currentMoves; ///<Moves taken to find date or ex int result; ///<Whether sailor finds date, ex, or sleep clearScreen(); getExperimentData(numEx, maxMoves, seed); srand(seed); ///<Seeds generator with user inputted number setupDanceFloor(numEx, floor); currentMoves = simulateGame(floor, maxMoves, sailorX, sailorY, result); displayGameResults(sailorX, sailorY, currentMoves, result); return 0; } /** * @brief Gets input from user (number of ex's, maximum steps taken by * sailor, and number used to seed random number generator * * @param exes is an reference integer variable used to hold number of exes * present at the dance * @param moves is an reference integer variable used to hold max numbers of * steps to be taken by sailor * @param seedValue is an reference double variable used to hold a number * used to seed random number generator. * @return void */ void getExperimentData(int& exes, int& moves, double& seedValue) { cout << "Enter the number of ex's, max number of moves, and random seed -> "; cin >> exes >> moves >> seedValue; } /** * @brief Gets input from user (number of ex's, maximum steps taken by * sailor, and number used to seed random number generator * * @param exes is an integer variable used to hold number of exes * present at the dance * @param floorBoard is an (reference - by default) 2-D integer array used * to represent the dance floor * @return void */ void setupDanceFloor(int exes, int floorBoard[][MAX_SIZE]) { int row; ///<Holds row for placing exs and date int column; ///<Holds column for placing exs and date int i; ///<Loop counter variable for(i = 0; i < MAX_SIZE; i ++) { for(int j = 0; j < MAX_SIZE; j++) floorBoard[i][j]=0; } floorBoard[5][5] = 1; row = rand() % MAX_SIZE; column = rand() % MAX_SIZE; floorBoard[row][column] = -1; for(i = 0; i < exes; i++) { row = rand() % MAX_SIZE; column = rand() % MAX_SIZE; floorBoard[row][column] = -2; } } /** * @brief Simulates the movement of a sailor, tracks the sports that he has * visited, and determines if he encounters a date or ex. * * @param floorBoard is an (reference - by default) 2-D integer array used * to represent the dance floor * @param moves is an reference integer variable used to hold max numbers of * steps to be taken by sailor * @param positionX is an reference integer variable used to hold x-position * of the sailor * @param positionY is an reference integer variable used to hold y-position * of the sailor * @return int - status of dance; 0 = sleep, 1 = date; 2 = ex */ int simulateGame(int floorBoard[][MAX_SIZE], int moves, int& positionX, int& positionY, int& drama) { int current = 0; ///<Number of steps taken by sailor drama = 0; ///<Status of simulation; 0 = sleep, 1 = date; 2 = ex unsigned int microseconds = 500000; while (current < moves && drama == 0) { positionX += randStep(); positionY += randStep(); if (positionX < 0) positionX = 0; else if (positionX > 9) positionX = 9; if (positionY < 0) positionY = 0; else if (positionY > 9) positionY = 9; if (floorBoard[positionX][positionY] == -1) drama = 1; //Found DATE else if (floorBoard[positionX][positionY] == -2) drama = 2; //Found EX else floorBoard[positionX][positionY] ++; clearScreen(); displayGameBoard(floorBoard, positionX, positionY); current++; usleep(microseconds); } return current; } /** * @brief Displays the floor board, where the sailor is, where the exs are * where the date is, and how many times the sailor has visited each square * * @param floorBoard is an (reference - by default) 2-D integer array used * to represent the dance floor * @param positionX is an integer variable used to hold x-position * of the sailor * @param positionY is an integer variable used to hold y-position * of the sailor * @return void */ void displayGameBoard(int floorBoard[][MAX_SIZE], int positionX, int positionY) { static int i = 0; ///<loop counter variable for rows static int j = 0; ///<loop counter variable for columns int characters = 0; ///<number of charters displayed for entry in array cout << "----------------------" << endl; for (i = 0; i < MAX_SIZE; i++) { cout << "|"; for (j = 0; j < MAX_SIZE; j++) { characters = 0; if (i == positionX && j == positionY) { cout << "*"; characters ++; } if (floorBoard[i][j] == -1) { cout << "$"; characters++; } else if (floorBoard[i][j] == -2) { cout << "X"; characters++; } else if (floorBoard[i][j] == 1) { cout << "."; characters++; } else if (floorBoard[i][j] == 2) { cout << ":"; characters++; } else if (floorBoard[i][j] > 2) { cout << "@"; characters++; } else { cout << " "; characters++; } if (characters == 1) cout << " "; } cout << "|" << endl; } cout << "----------------------" << endl; } /** * @brief displays the result of the simulation: whether the sailor finds * date/ex/loneliness, how many moves it take, and where the final position * of the sailor is * * @param positionX is an integer variable used to hold x-position * of the sailor * @param positionY is an integer variable used to hold y-position * of the sailor * @param current is an integer variable used to represent the number * of steps taken by the sailor when the simulation ends * @param status is an integer variable used to hold result of simulation; * 2 = Ex, 1 = Date, 0 (default) = Falls asleep * @return void */ void displayGameResults(int positionX, int positionY, int current, int status) { std::string s0 (""); ///<String that holds the result of simulation switch(status) { case (2): s0 = "TEARS and DRAMA (ex)"; break; case (1): s0 = "TRUE LOVE (date)"; break; default: s0 = "LONELINESS and UNCONSCIOUSNESS (no one)"; } cout << "Found " << s0 << " at (" << positionX << ", " << positionY << ") after " << current << " moves." << endl; } /** * @brief uses random number generator to return either 1 or -1 * * @param void * @return int - random number (1 or -1) */ int randStep() { return (rand()%2 ? -1 : 1); //return ((rand() % 3)-1); } /** * @brief clears an Xterm window * * @param void * @return void */ void clearScreen() { cout << char(27) << "[;H" << char(27) << "[2J" << '\n'; }
[ "sajantanand@aol.com" ]
sajantanand@aol.com
0cfb7e5b94b6f36968f8b037aefa97ac759e4f2f
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/09_25281_99.cpp
ba7421bcfe7b288779a76393167d855cba3d20af
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
cpp
#include <fstream> //#include <iostream> #include <algorithm> #include <map> #include <math.h> #include <queue> #include<string> #include <set> #pragma comment(linker, "/STACK:64000000") using namespace std; ifstream cin("input.txt"); ofstream cout("output.txt"); int main(){ int l,d,n; bool b[50010]; cin>>l>>d>>n; char dic[5010][20]; cin.getline(dic[0], 1000); for(int i=0; i<d; i++){ cin.getline(dic[i], 1000); } char str[50005]; set <char> st; for(int k=0; k<n; k++){ cin.getline(str, 50000); memset(b,1,sizeof(b)); int len=strlen(str); int num=0; for(int i=0; i<len; i++){ if(str[i]=='('){ i++; while(str[i]!=')'){ st.insert(str[i]); i++; } }else{ st.insert(str[i]); } for(int j=0; j<d; j++){ b[j]=b[j]&&(st.find(dic[j][num])!=st.end()); } num++; st.erase(st.begin(),st.end()); } int count=0; for(int i=0; i<d; i++) if(b[i]) count++; cout<<"Case #"<<k+1<<": "<<count<<endl; } return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
4b9cd6c0a7634e938c714389ea9ccb88ad1844c4
734882ee191fd388ee7c368c6dca2f72ec11d8a0
/src/Blank12.cpp
b43458e5a89819c62d58062631fae770f0f69d94
[ "MIT", "BSD-3-Clause" ]
permissive
ALEVOLDON/vcv-gratrix
312eb83fe5cc4552448d5c8162e7effc51378293
26edbd8d1852037f6fffec2c3290a884e049ff46
refs/heads/master
2021-08-19T16:37:20.576553
2017-11-27T00:00:16
2017-11-27T00:00:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,363
cpp
//============================================================================================================ //! //! \file Blank12.cpp //! //! \brief Blank 12 is a simple do nothing 12-hole high quality blank. //! //============================================================================================================ #include "Gratrix.hpp" namespace GTX { namespace Blank_12 { //============================================================================================================ //! \brief The implementation. struct Impl : Module { Impl() : Module(0, 0, 0) {} }; //============================================================================================================ //! \brief The widget. Widget::Widget() { GTX__WIDGET(); Impl *module = new Impl(); setModule(module); box.size = Vec(12*15, 380); #if GTX__SAVE_SVG { PanelGen pg(assetPlugin(plugin, "build/res/Blank12.svg"), box.size); } #endif { SVGPanel *panel = new SVGPanel(); panel->box.size = box.size; panel->setBackground(SVG::load(assetPlugin(plugin, "res/Blank12.svg"))); addChild(panel); } addChild(createScrew<ScrewSilver>(Vec(15, 0))); addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 0))); addChild(createScrew<ScrewSilver>(Vec(15, 365))); addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 365))); } } // Blank_12 } // GTX
[ "sam@gratrix.net" ]
sam@gratrix.net
06be367e29eb2236403f23d50c417965b2b252c5
9cdaa57909d844446eee11d0892af0c9d620a1c2
/11_9/TowDayPackage.h
34e7217c58d72fa1c24e86a26ee4bbac693cd5e9
[]
no_license
Maximengi/ma_ximeng
663acf35cd68716d8db190934542c892f1f8c01b
63ae75abd7e18a22dafd678d41dd2b82c4560ea4
refs/heads/master
2020-04-02T09:37:52.080753
2019-04-22T05:14:42
2019-04-22T05:14:42
154,301,730
0
0
null
null
null
null
UTF-8
C++
false
false
432
h
#ifndef TWODAY_H #define TWODAY_H #include "Package.h" class TwoDayPackage : public Package { public: TwoDayPackage( const string &, const string &, const string &, const string &, int, const string &, const string &, const string &, const string &, int, double, double, double ); void setFlatFee( double ); double getFlatFee() const; double calculateCost() const; private: double flatFee; }; #endif
[ "840155495@qq.com" ]
840155495@qq.com
884119e077243eb8bbfca484458aa025c2f798ae
eb5d15764ed4d88512d849461abbd1515b47c24c
/cryptonote/src/P2p/P2pNodeConfig.h
627186373f8c593b9b62f8a022f3076f2a4be500
[ "LGPL-3.0-only", "GPL-3.0-only" ]
permissive
theboldtoken/bold
4e74e2ef43f103ad8795892450918399030b32db
3015bc90fedebec106ff28f0d49ea72d147a98fe
refs/heads/master
2020-03-22T00:01:22.499231
2019-09-29T05:48:10
2019-09-29T05:48:10
117,006,837
0
1
MIT
2018-01-10T22:47:39
2018-01-10T20:24:35
null
UTF-8
C++
false
false
2,281
h
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers // // This file is part of Bytecoin. // // Bytecoin is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Bytecoin is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with Bytecoin. If not, see <http://www.gnu.org/licenses/>. #pragma once #include <chrono> #include "NetNodeConfig.h" namespace CryptoNote { class P2pNodeConfig : public NetNodeConfig { public: P2pNodeConfig(); // getters std::chrono::nanoseconds getTimedSyncInterval() const; std::chrono::nanoseconds getHandshakeTimeout() const; std::chrono::nanoseconds getConnectInterval() const; std::chrono::nanoseconds getConnectTimeout() const; size_t getExpectedOutgoingConnectionsCount() const; size_t getWhiteListConnectionsPercent() const; boost::uuids::uuid getNetworkId() const; size_t getPeerListConnectRange() const; size_t getPeerListGetTryCount() const; // setters void setTimedSyncInterval(std::chrono::nanoseconds interval); void setHandshakeTimeout(std::chrono::nanoseconds timeout); void setConnectInterval(std::chrono::nanoseconds interval); void setConnectTimeout(std::chrono::nanoseconds timeout); void setExpectedOutgoingConnectionsCount(size_t count); void setWhiteListConnectionsPercent(size_t percent); void setNetworkId(const boost::uuids::uuid& id); void setPeerListConnectRange(size_t range); void setPeerListGetTryCount(size_t count); private: std::chrono::nanoseconds timedSyncInterval; std::chrono::nanoseconds handshakeTimeout; std::chrono::nanoseconds connectInterval; std::chrono::nanoseconds connectTimeout; boost::uuids::uuid networkId; size_t expectedOutgoingConnectionsCount; size_t whiteListConnectionsPercent; size_t peerListConnectRange; size_t peerListGetTryCount; }; }
[ "dev1@boldtoken.io" ]
dev1@boldtoken.io
216af063f3541825f41e9350e23a3ceec30df576
ea401c3e792a50364fe11f7cea0f35f99e8f4bde
/hackathon/PengXie/NeuronStructNavigator/cmake-3.6.2/Source/cmInstallProgramsCommand.h
b104c6916281605e4cbcabb5cec13e9dd5a5506c
[ "BSD-3-Clause", "MIT" ]
permissive
Vaa3D/vaa3d_tools
edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9
e6974d5223ae70474efaa85e1253f5df1814fae8
refs/heads/master
2023-08-03T06:12:01.013752
2023-08-02T07:26:01
2023-08-02T07:26:01
50,527,925
107
86
MIT
2023-05-22T23:43:48
2016-01-27T18:19:17
C++
UTF-8
C++
false
false
1,981
h
/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #ifndef cmInstallProgramsCommand_h #define cmInstallProgramsCommand_h #include "cmCommand.h" /** \class cmInstallProgramsCommand * \brief Specifies where to install some programs * * cmInstallProgramsCommand specifies the relative path where a list of * programs should be installed. */ class cmInstallProgramsCommand : public cmCommand { public: /** * This is a virtual constructor for the command. */ virtual cmCommand* Clone() { return new cmInstallProgramsCommand; } /** * This is called when the command is first encountered in * the CMakeLists.txt file. */ virtual bool InitialPass(std::vector<std::string> const& args, cmExecutionStatus& status); /** * The name of the command as specified in CMakeList.txt. */ virtual std::string GetName() const { return "install_programs"; } /** * This is called at the end after all the information * specified by the command is accumulated. Most commands do * not implement this method. At this point, reading and * writing to the cache can be done. */ virtual void FinalPass(); virtual bool HasFinalPass() const { return true; } cmTypeMacro(cmInstallProgramsCommand, cmCommand); protected: std::string FindInstallSource(const char* name) const; private: std::vector<std::string> FinalArgs; std::string Destination; std::vector<std::string> Files; }; #endif
[ "peng.xie@utdallas.edu" ]
peng.xie@utdallas.edu
7b2e5b3aec01ecb27a281db7dfe532a38b9920f1
9c2801868c4abc0aa5c33488017bbaba2efb739f
/holyday or equality.cpp
ffce6d50e47c2b5ecc7bb3afb7edd36e96c0efab
[]
no_license
TasFIa003/codeforces
92638d99dc1d8ae30f89cc1932b5d9b9b431ea40
dfd655ced01b673cf76e8443dc139eb9b892d237
refs/heads/master
2023-02-22T11:52:55.409735
2021-01-25T18:04:56
2021-01-25T18:04:56
332,835,392
0
0
null
null
null
null
UTF-8
C++
false
false
307
cpp
#include<bits/stdc++.h> #define ll long long using namespace std; int main() { ll a[100000],res,sum=0; int n; cin>>n; for(int i=0;i<n;i++) { cin>>a[i]; } res=*max_element(a,a+n); for(int i=0;i<n;i++) { sum+=fabs(res-a[i]); } cout<<sum<<endl; }
[ "noortasfia7@gmail.com" ]
noortasfia7@gmail.com
1b11755bc5710c9a38156db0eb5df8fbc178d4fa
3ba238faa08788408b8f3e8a292074c67a2523e3
/MacOSX10.15.sdk/System/Library/Frameworks/DriverKit.framework/Versions/A/Headers/IODispatchSource.h
7103c381a834c10d5be65385b78d11429b12a3bf
[]
no_license
vmtrandev/macos-sdk
5c1f3474534eff4766f764a340503f6df5895e2f
fb2a69b436cb205574bd1aa7bc875fb948d55b02
refs/heads/master
2022-03-27T19:51:41.410382
2019-12-14T10:20:50
2019-12-14T10:20:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,598
h
/* iig(DriverKit-73.40.3) generated from IODispatchSource.iig */ /* IODispatchSource.iig:1-43 */ /* * Copyright (c) 2019-2019 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #ifndef _IOKIT_UIODISPATCHSOURCE_H #define _IOKIT_UIODISPATCHSOURCE_H #include <DriverKit/OSObject.h> /* .iig include */ typedef void (^IODispatchSourceCancelHandler)(void); /*! * @class IODispatchSource * @abstract * IODispatchSource common base class for dispatch sources. */ /* class IODispatchSource IODispatchSource.iig:44-66 */ #define IODispatchSource_Cancel_ID 0xd963bb196f70bb93ULL #define IODispatchSource_SetEnableWithCompletion_ID 0xbb42c489fe4dee8eULL #define IODispatchSource_CheckForWork_ID 0xef19d38d4f945fd0ULL #define IODispatchSource_SetEnable_ID 0xbbc036b4c2a26c45ULL #define IODispatchSource_Cancel_Args \ IODispatchSourceCancelHandler handler #define IODispatchSource_SetEnableWithCompletion_Args \ bool enable, \ IODispatchSourceCancelHandler handler #define IODispatchSource_CheckForWork_Args \ const IORPC rpc, \ bool synchronous #define IODispatchSource_SetEnable_Args \ bool enable #define IODispatchSource_Methods \ \ public:\ \ virtual kern_return_t\ Dispatch(const IORPC rpc) APPLE_KEXT_OVERRIDE;\ \ static kern_return_t\ _Dispatch(IODispatchSource * self, const IORPC rpc);\ \ kern_return_t\ Cancel(\ IODispatchSourceCancelHandler handler,\ OSDispatchMethod supermethod = NULL);\ \ kern_return_t\ SetEnableWithCompletion(\ bool enable,\ IODispatchSourceCancelHandler handler,\ OSDispatchMethod supermethod = NULL);\ \ kern_return_t\ CheckForWork(\ bool synchronous,\ OSDispatchMethod supermethod = NULL);\ \ kern_return_t\ SetEnable(\ bool enable,\ OSDispatchMethod supermethod = NULL);\ \ \ protected:\ /* _Impl methods */\ \ kern_return_t\ SetEnable_Impl(IODispatchSource_SetEnable_Args);\ \ \ public:\ /* _Invoke methods */\ \ typedef kern_return_t (*Cancel_Handler)(OSMetaClassBase * target, IODispatchSource_Cancel_Args);\ static kern_return_t\ Cancel_Invoke(const IORPC rpc,\ OSMetaClassBase * target,\ Cancel_Handler func);\ \ typedef kern_return_t (*SetEnableWithCompletion_Handler)(OSMetaClassBase * target, IODispatchSource_SetEnableWithCompletion_Args);\ static kern_return_t\ SetEnableWithCompletion_Invoke(const IORPC rpc,\ OSMetaClassBase * target,\ SetEnableWithCompletion_Handler func);\ \ typedef kern_return_t (*CheckForWork_Handler)(OSMetaClassBase * target, IODispatchSource_CheckForWork_Args);\ static kern_return_t\ CheckForWork_Invoke(const IORPC rpc,\ OSMetaClassBase * target,\ CheckForWork_Handler func);\ \ typedef kern_return_t (*SetEnable_Handler)(OSMetaClassBase * target, IODispatchSource_SetEnable_Args);\ static kern_return_t\ SetEnable_Invoke(const IORPC rpc,\ OSMetaClassBase * target,\ SetEnable_Handler func);\ \ #define IODispatchSource_KernelMethods \ \ protected:\ /* _Impl methods */\ \ #define IODispatchSource_VirtualMethods \ \ public:\ \ virtual bool\ init(\ ) APPLE_KEXT_OVERRIDE;\ \ virtual void\ free(\ ) APPLE_KEXT_OVERRIDE;\ \ extern OSMetaClass * gIODispatchSourceMetaClass; extern const OSClassLoadInformation IODispatchSource_Class; class IODispatchSourceMetaClass : public OSMetaClass { public: virtual kern_return_t New(OSObject * instance) override; virtual kern_return_t Dispatch(const IORPC rpc) override; }; class IODispatchSourceInterface : public OSInterface { public: }; struct IODispatchSource_IVars; struct IODispatchSource_LocalIVars; class IODispatchSource : public OSObject, public IODispatchSourceInterface { friend class IODispatchSourceMetaClass; public: union { IODispatchSource_IVars * ivars; IODispatchSource_LocalIVars * lvars; }; virtual const OSMetaClass * getMetaClass() const APPLE_KEXT_OVERRIDE { return OSTypeID(IODispatchSource); }; using super = OSObject; IODispatchSource_Methods IODispatchSource_VirtualMethods }; /* IODispatchSource.iig:68- */ #endif /* ! _IOKIT_UIODISPATCHSOURCE_H */
[ "alexey.lysiuk@gmail.com" ]
alexey.lysiuk@gmail.com
62915a2a0cab0c7a530779683e09327d32d93dff
5a4cf5f8f4e7d87e0d9f4f664c66febd0120ac9e
/collision.cpp
d4695c49283ea1d5dc2033f97bb0bc8eaf8f3b63
[ "Apache-2.0" ]
permissive
dakoner/diamondwars
c855313cf251d9fd3a6ce9894706afeb0f810fa1
4e678807c4932e87b91372b91b50d9b210f05a61
refs/heads/master
2020-04-05T23:29:54.250542
2014-07-14T00:46:18
2014-07-14T00:46:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,439
cpp
#include "vec2.h" #include "moving_object.h" Vec2 closest_point_on_seg(Vec2 seg_a, Vec2 seg_b, Vec2 circ_pos) { Vec2 seg_v = seg_b - seg_a; Vec2 pt_v = circ_pos - seg_a; if (seg_v.length() <= 0) return Vec2(0, 0); Vec2 seg_v_unit = seg_v; seg_v_unit.normalize(); float proj = pt_v.dot(seg_v_unit); if (proj <= 0) return seg_a; if (proj >= seg_v.length()) return seg_b; Vec2 proj_v = seg_v_unit * proj; Vec2 closest = proj_v + seg_a; return closest; } Vec2 segment_circle(Vec2 seg_a, Vec2 seg_b, float circ_rad, Vec2 circ_pos) { Vec2 closest = closest_point_on_seg(seg_a, seg_b, circ_pos); Vec2 dist_v = circ_pos - closest; if (dist_v.length() > circ_rad) return Vec2(0, 0); if (dist_v.length() <= 0) return Vec2(0, 0); Vec2 offset = dist_v; offset.normalize(); offset = offset * (circ_rad - dist_v.length()); return offset; } // TODO(dek): compute offset from repulsion bool collide(MovingObject* a, MovingObject* b) { Vec2 dist_v = a->position() - b->position(); if (dist_v.length() < (a->size() + b->size())) return true; return false; } bool collide(const Vec2& a, const Vec2& b, MovingObject* object) { Vec2 offset = segment_circle(a, b, object->size(), object->position()); if (offset.x() != 0 && offset.y() != 0) { object->mutable_velocity()->set_x( object->velocity().x() +offset.x()); object->mutable_velocity()->set_y( object->velocity().y() +offset.y()); Vec2 midpt((a+b)*0.5); ui->line(midpt.x(), midpt.y(), midpt.x() + offset.x(), midpt.y() + offset.y()); return true; } return false; } // Vec2 q; // for (int i = 0; i < stalagtites.size() - 1; ++i) { // Vec2 v(i * 20 + position().x(), stalagtites[i]); // Vec2 w((i + 1) * 20 + position().x(), stalagtites[i + 1]); // float d = DistanceFromLineSegmentToPoint(v, w, enemy, &q); // if (d < 50) { // Vec2 tmp(w-v); // Vec2 n(tmp.normal()); // n.normalize(); // EsploraTFT.stroke(255, 0, 0); // EsploraTFT.line(q.x(), q.y(), q.x() + n.x() * 10, q.y() + n.y() * 10); // EsploraTFT.stroke(0, 255, 0); // EsploraTFT.line(enemy.x(), enemy.y(), q.x(), q.y()); // } // } /* Vec2 tmp(w-v); Vec2 n(tmp.normal()); float x = v.x() + tmp.x()/2.; float y = v.y() + tmp.y()/2.; float nx = x + n.x(); float ny = y + n.y(); EsploraTFT.line(x + position().x(), y , nx + position().x(), ny); */
[ "dakoner@gmail.com" ]
dakoner@gmail.com
c9365e5275b5c1bc8a53ed635e4d6751fe80e775
68d954709d7884ff4220c9228affd4e5a7abd5f6
/pracadomowa/pracadomowa/List1d.cpp
1c27028471c8206f8d945647459549b20a778ed6
[]
no_license
owieckowicz/lista1
5bc8ee5e77a3e206358253210b387786c073de1c
2c02f06a9d4a450f1a0021aa010887c2b04d7bb2
refs/heads/master
2022-05-07T07:57:29.949032
2019-04-02T14:42:01
2019-04-02T14:42:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,947
cpp
#include "pch.h" #include "List1d.h" #include <iostream> using namespace std; List1d::List1d() { head = nullptr; tail = nullptr; length = 0; } List1d::~List1d() { } void List1d::pushback(int element) { length++; Nodle *added = new Nodle; added->liczba = element; added->next = nullptr; if (head == nullptr) { head = added; tail = added; } else { tail->next = added; tail = tail->next; } } void List1d::popback() { if (isempty()) { cout << "pusta"; } else { length--; Nodle *current = new Nodle; Nodle *previous = new Nodle; current = head; while (current->next != nullptr) { previous = current; current = current->next; } tail = previous; previous->next = nullptr; delete current; } } void List1d::pushfront(int element) { length++; Nodle *added = new Nodle; added->liczba = element; added->next = nullptr; if (head == nullptr) { head = added; tail = added; } else { added->next = head; head = added; } } void List1d::popfront() { if (isempty()) { cout << "Lista jest pusta" << endl; } else { length--; Nodle *temp = new Nodle; temp = head; head = head->next; delete temp; } } bool List1d::isempty() { if (length==0) { return true; } else { return false; } } int List1d::size() { return length; } int List1d::front() { if (head == nullptr) { cout << "Lista jest pusta" << endl; } else return head->liczba; } int List1d::back() { return tail->liczba; } void List1d::clear() { Nodle *current = new Nodle; Nodle *previous = new Nodle; current = head; while (current->next != nullptr) { current = current->next; delete previous; previous = current; length--; } current->next = nullptr; delete current; head = nullptr; tail = nullptr; length--; } void List1d::display() { Nodle *temp = new Nodle; temp = head; while (temp != nullptr) { cout << temp->liczba << endl; temp = temp->next; } }
[ "podgrzyb123@gmail.com" ]
podgrzyb123@gmail.com
ffc5c9e5b6663c5f90cca5f1d444c30555e00b50
e1fb942808cf741510eddd8c654ae47217cdd797
/hello_world.cpp
a5602847f3c7d19f6d4fedf03a2f93d9b1cfef26
[]
no_license
vriddhi1203/GitLearningRepo
2c67be0fe9ac9b51e88b9331c2fed8d317e9fa46
a70199c1a3e12d478e19384ed683bdf3d8b5ab1f
refs/heads/master
2022-11-24T04:48:54.454838
2020-07-21T12:05:30
2020-07-21T12:05:30
279,700,770
0
1
null
2020-07-21T12:05:32
2020-07-14T21:52:29
C++
UTF-8
C++
false
false
45
cpp
printf("hello_world"); cout<<"In dev branch";
[ "bhardwaj.vriddhi2000@gmail.com" ]
bhardwaj.vriddhi2000@gmail.com
f08b298a7b6b0b96ad2b4bf008dc7607065e548f
0f8a33d172ee3367c1b5a1987ee58cddfa3eef40
/include/rcommon.h
efc91972ce3d06b0281ae93d81463ae7d1a7f70e
[]
no_license
RaymonSHan/solution
fe88bd4a5a02495645fe1e8888fa62121d964907
f3a578ec4f159f548301d2167730986b4e9d2843
refs/heads/master
2021-01-17T12:53:24.494170
2016-12-15T08:06:28
2016-12-15T08:06:28
55,968,779
0
0
null
null
null
null
UTF-8
C++
false
false
10,894
h
#pragma once #include "windows.h" #ifdef WIN64 #define MYINT __int64 #define RESULT __int64 #define InterExgAdd InterlockedExchangeAdd64 #define InterCmpExg InterlockedCompareExchange64 #define InterExg InterlockedExchange64 #define InterDec InterlockedDecrement64 #define InterInc InterlockedIncrement64 #else WIN64 #define MYINT long #define RESULT long #define InterExgAdd InterlockedExchangeAdd #define InterCmpExg InterlockedCompareExchange #define InterExg InterlockedExchange #define InterDec InterlockedDecrement #define InterInc InterlockedIncrement #endif WIN64 #define RESULT_OK 0 #define RESULT_FREE 1 #define RESULT_CONTINUE 2 // packet have NOT complete #define RESULT_NULL 3 // no user data, system use only #define RESULT_NOT_SUPPORT 4 #define RESULT_NOT_EQUAL 5 #define RESULT_MAYBE 10 #define RESULT_ERR 11 #define RESULT_BUSY 12 #define RESULT_WSA_ERROR 1001 #define RESULT_DLLLOAD_ERROR 2001 #define RESULT_THREAD_ERROR 3001 #define RESULT_FILE_ERROR 4001 #define RESULT_PARA_ERROR 5001 #define RESULT_EMPTY 200001 #define MARK_NOT_IN_PROCESS (MYINT)0xa0 #define MARK_IN_PROCESS (MYINT)0xa1 #define MARK_UNDEFINE (MYINT)0xcccccccc #define DEFINE_LOCK(lock) \ static volatile MYINT lock = MARK_NOT_IN_PROCESS; #define DECLARE_CLASS_LOCK(lock) \ static volatile MYINT lock; #define DEFINE_CLASS_LOCK(cla, lock) \ volatile MYINT cla::lock = MARK_NOT_IN_PROCESS; #define LOCK(lock) \ while ( InterCmpExg(&lock, MARK_IN_PROCESS, MARK_NOT_IN_PROCESS) == MARK_IN_PROCESS ); #define UNLOCK(lock) \ lock = MARK_NOT_IN_PROCESS; #define DECLARE_SEMA(lock) \ HANDLE lock #define DEFINE_SEMA(lock, start, max) \ lock = CreateSemaphore(NULL, start, max, NULL); #define LOCK_SEMA(lock) \ WaitForSingleObject(lock, INFINITE); #define UNLOCK_SEMA(lock) \ ReleaseSemaphore(lock, 1, NULL); #define FREE_SEMA(lock) \ CloseHandle(lock) #define DECLARE_CRIT(lock) \ CRITICAL_SECTION lock; #define DEFINE_CRIT(lock) \ InitializeCriticalSection(&lock); #define LOCK_CRIT(lock) \ EnterCriticalSection(&lock); #define UNLOCK_CRIT(lock) \ LeaveCriticalSection(&lock); #define FREE_CRIT(lock) \ DeleteCriticalSection(&lock); #define IntoClassFunction(claname, func) \ unsigned int __stdcall func(PVOID pM) \ { \ claname* pMr = (claname*) pM; \ pMr->func(); \ return 0; \ } #define MAX_STEP 16 #define MAX_PARA 16 #define STEP_START (-1) #define STEP_END (-2) #ifndef MAX #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif class ThreadStep { private: MYINT status; DECLARE_SEMA(Lock)[MAX_STEP]; public: ThreadStep(void) { status = RESULT_OK; for (int i = 0; i < MAX_STEP; i++ ) DEFINE_SEMA(Lock[i], 0, MAX_PARA); }; void LockStep(MYINT step) { if (status == RESULT_FREE || step >= MAX_STEP) return; if (step != STEP_START) { LOCK_SEMA(Lock[step]); } }; void UnlockStep(MYINT step) { if (step != STEP_END && step < MAX_STEP) { UNLOCK_SEMA(Lock[step]); } else { for (int i = 0; i < MAX_STEP; i++ ) FREE_SEMA(Lock[i]); status = RESULT_FREE; } } }; #define DECLARE_STEP(lock) \ ThreadStep lock; #define LOCK_STEP(lock, step) \ lock.LockStep(step); #define UNLOCK_STEP(lock, step) \ lock.UnlockStep(step); #define WAIT_STEP(lock, lstep, ustep) \ lock.LockStep(lstep); \ lock.UnlockStep(ustep); #define FREE_STEP(lock) \ lock.UnlockStep(STEP_END); template<class T> inline void SWAP(T& left, T& right) { T temp; temp = left; left = right; right = temp; } #define DEFINE_COUNT(count) static volatile MYINT count = 0; #define INC(count) InterInc(&count); #define DEC(count) InterDec(&count); #define _TOSTRING(x) #x #define TOSTRING(x) _TOSTRING(x) #define _JOIN(x,y) x ## y #define JOIN(x,y) _JOIN(x,y) #define _TO_MARK(x) _rm_ ## x #define _rm_MarkMax 0xffffffff #define BEGINCALL #define ENDCALL #define SETLINE #define __TRY \ RESULT ret_err = __LINE__; \ BEGINCALL #define __MARK(x) \ static RESULT _TO_MARK(x) = ret_err = __LINE__; \ SETLINE #define DEF_MARK(x) \ static RESULT _TO_MARK(x); #define __MARK_(x) \ _TO_MARK(x) = ret_err = __LINE__; \ SETLINE #define __CATCH_BEGIN \ ENDCALL \ return RESULT_OK; \ error_stop: \ ENDCALL \ if (ret_err == RESULT_OK) return RESULT_OK; #define __BETWEEN(x,y) \ if (ret_err >= _TO_MARK(x) && ret_err <= _TO_MARK(y)) #define __BEFORE(x) \ if (ret_err < _TO_MARK(x)) #define __AFTER(x) \ if (ret_err >= _TO_MARK(x)) #define __CATCH_END \ return ret_err; #define __CATCH \ ENDCALL \ return RESULT_OK; \ error_stop: \ ENDCALL \ return ret_err; #define __CATCH_(ret) \ ENDCALL \ return ret; \ error_stop: \ ENDCALL \ return RESULT_OK; #define __TRY__ \ BEGINCALL #define __CATCH__ \ ENDCALL \ return RESULT_OK; #define __RETURN_(ret) \ ENDCALL \ return ret; #define __BREAK \ { goto error_stop; } #define __BREAK_OK \ { ret_err = RESULT_OK; goto error_stop; } #define MESSAGE_INFO (1 << 0) #define MESSAGE_DEBUG (1 << 1) #define MESSAGE_ERROR (1 << 2) #define MESSAGE_HALT (1 << 3) // void __MESSAGE_(INT level, const char * _Format, ...); // void __MESSAGE (INT level); // void __TRACE(); #define __MESSAGE_ // lazy for ignore #define __MESSAGE // lazy for ignore // #define TRACE __TRACE(); #define __INFO(level, _Format,...) { \ __MESSAGE_(level, _Format,##__VA_ARGS__); \ }; #define __DO1(val, func) { \ SETLINE \ val = func; \ if (val == NEGONE) { \ WSASetLastError(errno); \ __BREAK; \ } \ }; #define __DOc_(func, _Format,...) { \ SETLINE \ if (func) \ __INFO(MESSAGE_INFO, _Format,##__VA_ARGS__); \ }; #define __DOc(func) { \ SETLINE \ func; \ }; #define __DO(func) { \ SETLINE \ if (func) { \ __MESSAGE(MESSAGE_DEBUG); \ __BREAK; \ } \ }; #define __DOb(func) { \ SETLINE \ func; \ __BREAK; \ }; #define __DOe(func, err) { \ SETLINE \ if (func) { \ ERROR(err); \ __MESSAGE(MESSAGE_DEBUG); \ __BREAK; \ } \ };
[ "quickhorse77@gmail.com" ]
quickhorse77@gmail.com
e3cfae26edcd5cddb2cd1d3f0bfb5be64f2e0d3b
ad35ce269951b0f5d7ee40602ac9d9e897ad8f4f
/Behavioral_Patterns/Command/main.cpp
00636192bb08c45f7fa88a0026adc3faa2daaa72
[]
no_license
BartVandewoestyne/Design-Patterns-GoF
2ba3aca8021f7eb7083e1b5d89e29528d9e2dd59
77b81a3abd4abd1304d591e2c0245773ff7387be
refs/heads/master
2023-08-23T00:48:51.172593
2023-01-09T21:47:34
2023-01-09T21:47:34
32,483,239
260
122
null
null
null
null
UTF-8
C++
false
false
261
cpp
#include "Command.h" #include "SimpleCommand.h" #include "MyClass.h" int main() { MyClass* receiver = new MyClass; // ... Command* aCommand = new SimpleCommand<MyClass>(receiver, &MyClass::Action); // ... aCommand->Execute(); }
[ "Bart.Vandewoestyne@telenet.be" ]
Bart.Vandewoestyne@telenet.be
c2a4e7339fd99ee303305b2e5433979f4f1d8302
9f67c9336524a4cea8c20b802d18eddf68fae59c
/src/Wallet/WalletSerialization.cpp
c44f2b581b0b091470c6b347d7d8f4f982097b69
[]
no_license
micronotecoin/micronotecoin
8f58c666e8e04d9f5b4a07519037c7e03dcda2d6
8eea7d9b44b07c01d7e03e98b758153193cc0e28
refs/heads/master
2021-06-24T13:43:38.934531
2017-09-15T14:36:42
2017-09-15T14:36:42
103,281,411
0
1
null
null
null
null
UTF-8
C++
false
false
29,715
cpp
// Copyright (c) 2011-2016 The Cryptonote developers // Copyright (c) 2017 MicroNote Coin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "WalletSerialization.h" #include <string> #include <sstream> #include <type_traits> #include "Common/MemoryInputStream.h" #include "Common/StdInputStream.h" #include "Common/StdOutputStream.h" #include "CryptoNoteCore/CryptoNoteSerialization.h" #include "CryptoNoteCore/CryptoNoteTools.h" #include "Serialization/BinaryOutputStreamSerializer.h" #include "Serialization/BinaryInputStreamSerializer.h" #include "Serialization/SerializationOverloads.h" #include "Wallet/WalletErrors.h" #include "WalletLegacy/KeysStorage.h" #include "WalletLegacy/WalletLegacySerialization.h" using namespace Common; using namespace Crypto; namespace { //DO NOT CHANGE IT struct WalletRecordDto { PublicKey spendPublicKey; SecretKey spendSecretKey; uint64_t pendingBalance = 0; uint64_t actualBalance = 0; uint64_t creationTimestamp = 0; }; //DO NOT CHANGE IT struct ObsoleteSpentOutputDto { uint64_t amount; Hash transactionHash; uint32_t outputInTransaction; uint64_t walletIndex; Crypto::Hash spendingTransactionHash; }; //DO NOT CHANGE IT struct ObsoleteChangeDto { Hash txHash; uint64_t amount; }; //DO NOT CHANGE IT struct UnlockTransactionJobDto { uint32_t blockHeight; Hash transactionHash; uint64_t walletIndex; }; //DO NOT CHANGE IT struct WalletTransactionDto { WalletTransactionDto() {} WalletTransactionDto(const CryptoNote::WalletTransaction& wallet) { state = wallet.state; timestamp = wallet.timestamp; blockHeight = wallet.blockHeight; hash = wallet.hash; totalAmount = wallet.totalAmount; fee = wallet.fee; creationTime = wallet.creationTime; unlockTime = wallet.unlockTime; extra = wallet.extra; } CryptoNote::WalletTransactionState state; uint64_t timestamp; uint32_t blockHeight; Hash hash; int64_t totalAmount; uint64_t fee; uint64_t creationTime; uint64_t unlockTime; std::string extra; }; //DO NOT CHANGE IT struct WalletTransferDto { WalletTransferDto(uint32_t version) : version(version) {} WalletTransferDto(const CryptoNote::WalletTransfer& tr, uint32_t version) : WalletTransferDto(version) { address = tr.address; amount = tr.amount; type = static_cast<uint8_t>(tr.type); } std::string address; uint64_t amount; uint8_t type; uint32_t version; }; void serialize(WalletRecordDto& value, CryptoNote::ISerializer& serializer) { serializer(value.spendPublicKey, "spend_public_key"); serializer(value.spendSecretKey, "spend_secret_key"); serializer(value.pendingBalance, "pending_balance"); serializer(value.actualBalance, "actual_balance"); serializer(value.creationTimestamp, "creation_timestamp"); } void serialize(ObsoleteSpentOutputDto& value, CryptoNote::ISerializer& serializer) { serializer(value.amount, "amount"); serializer(value.transactionHash, "transaction_hash"); serializer(value.outputInTransaction, "output_in_transaction"); serializer(value.walletIndex, "wallet_index"); serializer(value.spendingTransactionHash, "spending_transaction_hash"); } void serialize(ObsoleteChangeDto& value, CryptoNote::ISerializer& serializer) { serializer(value.txHash, "transaction_hash"); serializer(value.amount, "amount"); } void serialize(UnlockTransactionJobDto& value, CryptoNote::ISerializer& serializer) { serializer(value.blockHeight, "block_height"); serializer(value.transactionHash, "transaction_hash"); serializer(value.walletIndex, "wallet_index"); } void serialize(WalletTransactionDto& value, CryptoNote::ISerializer& serializer) { typedef std::underlying_type<CryptoNote::WalletTransactionState>::type StateType; StateType state = static_cast<StateType>(value.state); serializer(state, "state"); value.state = static_cast<CryptoNote::WalletTransactionState>(state); serializer(value.timestamp, "timestamp"); CryptoNote::serializeBlockHeight(serializer, value.blockHeight, "block_height"); serializer(value.hash, "hash"); serializer(value.totalAmount, "total_amount"); serializer(value.fee, "fee"); serializer(value.creationTime, "creation_time"); serializer(value.unlockTime, "unlock_time"); serializer(value.extra, "extra"); } void serialize(WalletTransferDto& value, CryptoNote::ISerializer& serializer) { serializer(value.address, "address"); serializer(value.amount, "amount"); if (value.version > 2) { serializer(value.type, "type"); } } template <typename Object> std::string serialize(Object& obj, const std::string& name) { std::stringstream stream; StdOutputStream output(stream); CryptoNote::BinaryOutputStreamSerializer s(output); s(obj, Common::StringView(name)); stream.flush(); return stream.str(); } std::string encrypt(const std::string& plain, CryptoNote::CryptoContext& cryptoContext) { std::string cipher; cipher.resize(plain.size()); Crypto::chacha8(plain.data(), plain.size(), cryptoContext.key, cryptoContext.iv, &cipher[0]); return cipher; } void addToStream(const std::string& cipher, const std::string& name, Common::IOutputStream& destination) { CryptoNote::BinaryOutputStreamSerializer s(destination); s(const_cast<std::string& >(cipher), name); } template<typename Object> void serializeEncrypted(Object& obj, const std::string& name, CryptoNote::CryptoContext& cryptoContext, Common::IOutputStream& destination) { std::string plain = serialize(obj, name); std::string cipher = encrypt(plain, cryptoContext); addToStream(cipher, name, destination); } std::string readCipher(Common::IInputStream& source, const std::string& name) { std::string cipher; CryptoNote::BinaryInputStreamSerializer s(source); s(cipher, name); return cipher; } std::string decrypt(const std::string& cipher, CryptoNote::CryptoContext& cryptoContext) { std::string plain; plain.resize(cipher.size()); Crypto::chacha8(cipher.data(), cipher.size(), cryptoContext.key, cryptoContext.iv, &plain[0]); return plain; } template<typename Object> void deserialize(Object& obj, const std::string& name, const std::string& plain) { MemoryInputStream stream(plain.data(), plain.size()); CryptoNote::BinaryInputStreamSerializer s(stream); s(obj, Common::StringView(name)); } template<typename Object> void deserializeEncrypted(Object& obj, const std::string& name, CryptoNote::CryptoContext& cryptoContext, Common::IInputStream& source) { std::string cipher = readCipher(source, name); std::string plain = decrypt(cipher, cryptoContext); deserialize(obj, name, plain); } bool verifyKeys(const SecretKey& sec, const PublicKey& expected_pub) { PublicKey pub; bool r = Crypto::secret_key_to_public_key(sec, pub); return r && expected_pub == pub; } void throwIfKeysMissmatch(const SecretKey& sec, const PublicKey& expected_pub) { if (!verifyKeys(sec, expected_pub)) throw std::system_error(make_error_code(CryptoNote::error::WRONG_PASSWORD)); } CryptoNote::WalletTransaction convert(const CryptoNote::WalletLegacyTransaction& tx) { CryptoNote::WalletTransaction mtx; mtx.state = CryptoNote::WalletTransactionState::SUCCEEDED; mtx.timestamp = tx.timestamp; mtx.blockHeight = tx.blockHeight; mtx.hash = tx.hash; mtx.totalAmount = tx.totalAmount; mtx.fee = tx.fee; mtx.creationTime = tx.sentTime; mtx.unlockTime = tx.unlockTime; mtx.extra = tx.extra; mtx.isBase = tx.isCoinbase; return mtx; } CryptoNote::WalletTransfer convert(const CryptoNote::WalletLegacyTransfer& tr) { CryptoNote::WalletTransfer mtr; mtr.address = tr.address; mtr.amount = tr.amount; return mtr; } } namespace CryptoNote { const uint32_t WalletSerializer::SERIALIZATION_VERSION = 5; void CryptoContext::incIv() { uint64_t * i = reinterpret_cast<uint64_t *>(&iv.data[0]); (*i)++; } WalletSerializer::WalletSerializer( ITransfersObserver& transfersObserver, PublicKey& viewPublicKey, SecretKey& viewSecretKey, uint64_t& actualBalance, uint64_t& pendingBalance, WalletsContainer& walletsContainer, TransfersSyncronizer& synchronizer, UnlockTransactionJobs& unlockTransactions, WalletTransactions& transactions, WalletTransfers& transfers, uint32_t transactionSoftLockTime, UncommitedTransactions& uncommitedTransactions ) : m_transfersObserver(transfersObserver), m_viewPublicKey(viewPublicKey), m_viewSecretKey(viewSecretKey), m_actualBalance(actualBalance), m_pendingBalance(pendingBalance), m_walletsContainer(walletsContainer), m_synchronizer(synchronizer), m_unlockTransactions(unlockTransactions), m_transactions(transactions), m_transfers(transfers), m_transactionSoftLockTime(transactionSoftLockTime), uncommitedTransactions(uncommitedTransactions) { } void WalletSerializer::save(const std::string& password, Common::IOutputStream& destination, bool saveDetails, bool saveCache) { CryptoContext cryptoContext = generateCryptoContext(password); CryptoNote::BinaryOutputStreamSerializer s(destination); s.beginObject("wallet"); saveVersion(destination); saveIv(destination, cryptoContext.iv); saveKeys(destination, cryptoContext); saveWallets(destination, saveCache, cryptoContext); saveFlags(saveDetails, saveCache, destination, cryptoContext); if (saveDetails) { saveTransactions(destination, cryptoContext); saveTransfers(destination, cryptoContext); } if (saveCache) { saveBalances(destination, saveCache, cryptoContext); saveTransfersSynchronizer(destination, cryptoContext); saveUnlockTransactionsJobs(destination, cryptoContext); saveUncommitedTransactions(destination, cryptoContext); } s.endObject(); } CryptoContext WalletSerializer::generateCryptoContext(const std::string& password) { CryptoContext context; Crypto::cn_context c; Crypto::generate_chacha8_key(c, password, context.key); context.iv = Crypto::rand<Crypto::chacha8_iv>(); return context; } void WalletSerializer::saveVersion(Common::IOutputStream& destination) { uint32_t version = SERIALIZATION_VERSION; BinaryOutputStreamSerializer s(destination); s(version, "version"); } void WalletSerializer::saveIv(Common::IOutputStream& destination, Crypto::chacha8_iv& iv) { BinaryOutputStreamSerializer s(destination); s.binary(reinterpret_cast<void *>(&iv.data), sizeof(iv.data), "chacha_iv"); } void WalletSerializer::saveKeys(Common::IOutputStream& destination, CryptoContext& cryptoContext) { savePublicKey(destination, cryptoContext); saveSecretKey(destination, cryptoContext); } void WalletSerializer::savePublicKey(Common::IOutputStream& destination, CryptoContext& cryptoContext) { serializeEncrypted(m_viewPublicKey, "public_key", cryptoContext, destination); cryptoContext.incIv(); } void WalletSerializer::saveSecretKey(Common::IOutputStream& destination, CryptoContext& cryptoContext) { serializeEncrypted(m_viewSecretKey, "secret_key", cryptoContext, destination); cryptoContext.incIv(); } void WalletSerializer::saveFlags(bool saveDetails, bool saveCache, Common::IOutputStream& destination, CryptoContext& cryptoContext) { serializeEncrypted(saveDetails, "details", cryptoContext, destination); cryptoContext.incIv(); serializeEncrypted(saveCache, "cache", cryptoContext, destination); cryptoContext.incIv(); } void WalletSerializer::saveWallets(Common::IOutputStream& destination, bool saveCache, CryptoContext& cryptoContext) { auto& index = m_walletsContainer.get<RandomAccessIndex>(); uint64_t count = index.size(); serializeEncrypted(count, "wallets_count", cryptoContext, destination); cryptoContext.incIv(); for (const auto& w: index) { WalletRecordDto dto; dto.spendPublicKey = w.spendPublicKey; dto.spendSecretKey = w.spendSecretKey; dto.pendingBalance = saveCache ? w.pendingBalance : 0; dto.actualBalance = saveCache ? w.actualBalance : 0; dto.creationTimestamp = static_cast<uint64_t>(w.creationTimestamp); serializeEncrypted(dto, "", cryptoContext, destination); cryptoContext.incIv(); } } void WalletSerializer::saveBalances(Common::IOutputStream& destination, bool saveCache, CryptoContext& cryptoContext) { uint64_t actual = saveCache ? m_actualBalance : 0; uint64_t pending = saveCache ? m_pendingBalance : 0; serializeEncrypted(actual, "actual_balance", cryptoContext, destination); cryptoContext.incIv(); serializeEncrypted(pending, "pending_balance", cryptoContext, destination); cryptoContext.incIv(); } void WalletSerializer::saveTransfersSynchronizer(Common::IOutputStream& destination, CryptoContext& cryptoContext) { std::stringstream stream; m_synchronizer.save(stream); stream.flush(); std::string plain = stream.str(); serializeEncrypted(plain, "transfers_synchronizer", cryptoContext, destination); cryptoContext.incIv(); } void WalletSerializer::saveUnlockTransactionsJobs(Common::IOutputStream& destination, CryptoContext& cryptoContext) { auto& index = m_unlockTransactions.get<TransactionHashIndex>(); auto& wallets = m_walletsContainer.get<TransfersContainerIndex>(); uint64_t jobsCount = index.size(); serializeEncrypted(jobsCount, "unlock_transactions_jobs_count", cryptoContext, destination); cryptoContext.incIv(); for (const auto& j: index) { auto containerIt = wallets.find(j.container); assert(containerIt != wallets.end()); auto rndIt = m_walletsContainer.project<RandomAccessIndex>(containerIt); assert(rndIt != m_walletsContainer.get<RandomAccessIndex>().end()); uint64_t walletIndex = std::distance(m_walletsContainer.get<RandomAccessIndex>().begin(), rndIt); UnlockTransactionJobDto dto; dto.blockHeight = j.blockHeight; dto.transactionHash = j.transactionHash; dto.walletIndex = walletIndex; serializeEncrypted(dto, "", cryptoContext, destination); cryptoContext.incIv(); } } void WalletSerializer::saveUncommitedTransactions(Common::IOutputStream& destination, CryptoContext& cryptoContext) { serializeEncrypted(uncommitedTransactions, "uncommited_transactions", cryptoContext, destination); } void WalletSerializer::saveTransactions(Common::IOutputStream& destination, CryptoContext& cryptoContext) { uint64_t count = m_transactions.size(); serializeEncrypted(count, "transactions_count", cryptoContext, destination); cryptoContext.incIv(); for (const auto& tx: m_transactions) { WalletTransactionDto dto(tx); serializeEncrypted(dto, "", cryptoContext, destination); cryptoContext.incIv(); } } void WalletSerializer::saveTransfers(Common::IOutputStream& destination, CryptoContext& cryptoContext) { uint64_t count = m_transfers.size(); serializeEncrypted(count, "transfers_count", cryptoContext, destination); cryptoContext.incIv(); for (const auto& kv: m_transfers) { uint64_t txId = kv.first; WalletTransferDto tr(kv.second, SERIALIZATION_VERSION); serializeEncrypted(txId, "transaction_id", cryptoContext, destination); cryptoContext.incIv(); serializeEncrypted(tr, "transfer", cryptoContext, destination); cryptoContext.incIv(); } } void WalletSerializer::load(const std::string& password, Common::IInputStream& source) { CryptoNote::BinaryInputStreamSerializer s(source); s.beginObject("wallet"); uint32_t version = loadVersion(source); if (version > SERIALIZATION_VERSION) { throw std::system_error(make_error_code(error::WRONG_VERSION)); } else if (version != 1) { loadWallet(source, password, version); } else { loadWalletV1(source, password); } s.endObject(); } void WalletSerializer::loadWallet(Common::IInputStream& source, const std::string& password, uint32_t version) { CryptoNote::CryptoContext cryptoContext; bool details = false; bool cache = false; loadIv(source, cryptoContext.iv); generateKey(password, cryptoContext.key); loadKeys(source, cryptoContext); checkKeys(); loadWallets(source, cryptoContext); subscribeWallets(); loadFlags(details, cache, source, cryptoContext); if (details) { loadTransactions(source, cryptoContext); loadTransfers(source, cryptoContext, version); } if (version < 5) { updateTransfersSign(); cache = false; } if (cache) { loadBalances(source, cryptoContext); loadTransfersSynchronizer(source, cryptoContext); if (version < 5) { loadObsoleteSpentOutputs(source, cryptoContext); } loadUnlockTransactionsJobs(source, cryptoContext); if (version < 5) { loadObsoleteChange(source, cryptoContext); } if (version > 3) { loadUncommitedTransactions(source, cryptoContext); if (version >= 5) { initTransactionPool(); } } } else { resetCachedBalance(); } if (details && cache) { updateTransactionsBaseStatus(); } } void WalletSerializer::loadWalletV1(Common::IInputStream& source, const std::string& password) { CryptoNote::CryptoContext cryptoContext; CryptoNote::BinaryInputStreamSerializer encrypted(source); encrypted(cryptoContext.iv, "iv"); generateKey(password, cryptoContext.key); std::string cipher; encrypted(cipher, "data"); std::string plain = decrypt(cipher, cryptoContext); MemoryInputStream decryptedStream(plain.data(), plain.size()); CryptoNote::BinaryInputStreamSerializer serializer(decryptedStream); loadWalletV1Keys(serializer); checkKeys(); subscribeWallets(); bool detailsSaved; serializer(detailsSaved, "has_details"); if (detailsSaved) { loadWalletV1Details(serializer); } } void WalletSerializer::loadWalletV1Keys(CryptoNote::BinaryInputStreamSerializer& serializer) { CryptoNote::KeysStorage keys; keys.serialize(serializer, "keys"); m_viewPublicKey = keys.viewPublicKey; m_viewSecretKey = keys.viewSecretKey; WalletRecord wallet; wallet.spendPublicKey = keys.spendPublicKey; wallet.spendSecretKey = keys.spendSecretKey; wallet.actualBalance = 0; wallet.pendingBalance = 0; wallet.creationTimestamp = static_cast<time_t>(keys.creationTimestamp); m_walletsContainer.get<RandomAccessIndex>().push_back(wallet); } void WalletSerializer::loadWalletV1Details(CryptoNote::BinaryInputStreamSerializer& serializer) { std::vector<WalletLegacyTransaction> txs; std::vector<WalletLegacyTransfer> trs; serializer(txs, "transactions"); serializer(trs, "transfers"); addWalletV1Details(txs, trs); } uint32_t WalletSerializer::loadVersion(Common::IInputStream& source) { CryptoNote::BinaryInputStreamSerializer s(source); uint32_t version = std::numeric_limits<uint32_t>::max(); s(version, "version"); return version; } void WalletSerializer::loadIv(Common::IInputStream& source, Crypto::chacha8_iv& iv) { CryptoNote::BinaryInputStreamSerializer s(source); s.binary(static_cast<void *>(&iv.data), sizeof(iv.data), "chacha_iv"); } void WalletSerializer::generateKey(const std::string& password, Crypto::chacha8_key& key) { Crypto::cn_context context; Crypto::generate_chacha8_key(context, password, key); } void WalletSerializer::loadKeys(Common::IInputStream& source, CryptoContext& cryptoContext) { loadPublicKey(source, cryptoContext); loadSecretKey(source, cryptoContext); } void WalletSerializer::loadPublicKey(Common::IInputStream& source, CryptoContext& cryptoContext) { deserializeEncrypted(m_viewPublicKey, "public_key", cryptoContext, source); cryptoContext.incIv(); } void WalletSerializer::loadSecretKey(Common::IInputStream& source, CryptoContext& cryptoContext) { deserializeEncrypted(m_viewSecretKey, "secret_key", cryptoContext, source); cryptoContext.incIv(); } void WalletSerializer::checkKeys() { throwIfKeysMissmatch(m_viewSecretKey, m_viewPublicKey); } void WalletSerializer::loadFlags(bool& details, bool& cache, Common::IInputStream& source, CryptoContext& cryptoContext) { deserializeEncrypted(details, "details", cryptoContext, source); cryptoContext.incIv(); deserializeEncrypted(cache, "cache", cryptoContext, source); cryptoContext.incIv(); } void WalletSerializer::loadWallets(Common::IInputStream& source, CryptoContext& cryptoContext) { auto& index = m_walletsContainer.get<RandomAccessIndex>(); uint64_t count = 0; deserializeEncrypted(count, "wallets_count", cryptoContext, source); cryptoContext.incIv(); bool isTrackingMode; for (uint64_t i = 0; i < count; ++i) { WalletRecordDto dto; deserializeEncrypted(dto, "", cryptoContext, source); cryptoContext.incIv(); if (i == 0) { isTrackingMode = dto.spendSecretKey == NULL_SECRET_KEY; } else if ((isTrackingMode && dto.spendSecretKey != NULL_SECRET_KEY) || (!isTrackingMode && dto.spendSecretKey == NULL_SECRET_KEY)) { throw std::system_error(make_error_code(error::BAD_ADDRESS), "All addresses must be whether tracking or not"); } if (dto.spendSecretKey != NULL_SECRET_KEY) { Crypto::PublicKey restoredPublicKey; bool r = Crypto::secret_key_to_public_key(dto.spendSecretKey, restoredPublicKey); if (!r || dto.spendPublicKey != restoredPublicKey) { throw std::system_error(make_error_code(error::WRONG_PASSWORD), "Restored spend public key doesn't correspond to secret key"); } } else { if (!Crypto::check_key(dto.spendPublicKey)) { throw std::system_error(make_error_code(error::WRONG_PASSWORD), "Public spend key is incorrect"); } } WalletRecord wallet; wallet.spendPublicKey = dto.spendPublicKey; wallet.spendSecretKey = dto.spendSecretKey; wallet.actualBalance = dto.actualBalance; wallet.pendingBalance = dto.pendingBalance; wallet.creationTimestamp = static_cast<time_t>(dto.creationTimestamp); wallet.container = reinterpret_cast<CryptoNote::ITransfersContainer*>(i); //dirty hack. container field must be unique index.push_back(wallet); } } void WalletSerializer::subscribeWallets() { auto& index = m_walletsContainer.get<RandomAccessIndex>(); for (auto it = index.begin(); it != index.end(); ++it) { const auto& wallet = *it; AccountSubscription sub; sub.keys.address.viewPublicKey = m_viewPublicKey; sub.keys.address.spendPublicKey = wallet.spendPublicKey; sub.keys.viewSecretKey = m_viewSecretKey; sub.keys.spendSecretKey = wallet.spendSecretKey; sub.transactionSpendableAge = m_transactionSoftLockTime; sub.syncStart.height = 0; sub.syncStart.timestamp = std::max(static_cast<uint64_t>(wallet.creationTimestamp), ACCOUNT_CREATE_TIME_ACCURACY) - ACCOUNT_CREATE_TIME_ACCURACY; auto& subscription = m_synchronizer.addSubscription(sub); bool r = index.modify(it, [&subscription] (WalletRecord& rec) { rec.container = &subscription.getContainer(); }); assert(r); subscription.addObserver(&m_transfersObserver); } } void WalletSerializer::loadBalances(Common::IInputStream& source, CryptoContext& cryptoContext) { deserializeEncrypted(m_actualBalance, "actual_balance", cryptoContext, source); cryptoContext.incIv(); deserializeEncrypted(m_pendingBalance, "pending_balance", cryptoContext, source); cryptoContext.incIv(); } void WalletSerializer::loadTransfersSynchronizer(Common::IInputStream& source, CryptoContext& cryptoContext) { std::string deciphered; deserializeEncrypted(deciphered, "transfers_synchronizer", cryptoContext, source); cryptoContext.incIv(); std::stringstream stream(deciphered); deciphered.clear(); m_synchronizer.load(stream); } void WalletSerializer::loadObsoleteSpentOutputs(Common::IInputStream& source, CryptoContext& cryptoContext) { uint64_t count = 0; deserializeEncrypted(count, "spent_outputs_count", cryptoContext, source); cryptoContext.incIv(); for (uint64_t i = 0; i < count; ++i) { ObsoleteSpentOutputDto dto; deserializeEncrypted(dto, "", cryptoContext, source); cryptoContext.incIv(); } } void WalletSerializer::loadUnlockTransactionsJobs(Common::IInputStream& source, CryptoContext& cryptoContext) { auto& index = m_unlockTransactions.get<TransactionHashIndex>(); auto& walletsIndex = m_walletsContainer.get<RandomAccessIndex>(); const uint64_t walletsSize = walletsIndex.size(); uint64_t jobsCount = 0; deserializeEncrypted(jobsCount, "unlock_transactions_jobs_count", cryptoContext, source); cryptoContext.incIv(); for (uint64_t i = 0; i < jobsCount; ++i) { UnlockTransactionJobDto dto; deserializeEncrypted(dto, "", cryptoContext, source); cryptoContext.incIv(); assert(dto.walletIndex < walletsSize); UnlockTransactionJob job; job.blockHeight = dto.blockHeight; job.transactionHash = dto.transactionHash; job.container = walletsIndex[dto.walletIndex].container; index.insert(std::move(job)); } } void WalletSerializer::loadObsoleteChange(Common::IInputStream& source, CryptoContext& cryptoContext) { uint64_t count = 0; deserializeEncrypted(count, "changes_count", cryptoContext, source); cryptoContext.incIv(); for (uint64_t i = 0; i < count; i++) { ObsoleteChangeDto dto; deserializeEncrypted(dto, "", cryptoContext, source); cryptoContext.incIv(); } } void WalletSerializer::loadUncommitedTransactions(Common::IInputStream& source, CryptoContext& cryptoContext) { deserializeEncrypted(uncommitedTransactions, "uncommited_transactions", cryptoContext, source); } void WalletSerializer::initTransactionPool() { std::unordered_set<Crypto::Hash> uncommitedTransactionsSet; std::transform(uncommitedTransactions.begin(), uncommitedTransactions.end(), std::inserter(uncommitedTransactionsSet, uncommitedTransactionsSet.end()), [](const UncommitedTransactions::value_type& pair) { return getObjectHash(pair.second); }); m_synchronizer.initTransactionPool(uncommitedTransactionsSet); } void WalletSerializer::resetCachedBalance() { for (auto it = m_walletsContainer.begin(); it != m_walletsContainer.end(); ++it) { m_walletsContainer.modify(it, [](WalletRecord& wallet) { wallet.actualBalance = 0; wallet.pendingBalance = 0; }); } } // can't do it in loadTransactions, TransfersContainer is not yet loaded void WalletSerializer::updateTransactionsBaseStatus() { auto& transactions = m_transactions.get<RandomAccessIndex>(); auto begin = std::begin(transactions); auto end = std::end(transactions); for (; begin != end; ++begin) { transactions.modify(begin, [this](WalletTransaction& tx) { auto& wallets = m_walletsContainer.get<RandomAccessIndex>(); TransactionInformation txInfo; auto it = std::find_if(std::begin(wallets), std::end(wallets), [&](const WalletRecord& rec) { assert(rec.container != nullptr); return rec.container->getTransactionInformation(tx.hash, txInfo); }); tx.isBase = it != std::end(wallets) && txInfo.totalAmountIn == 0; }); } } void WalletSerializer::updateTransfersSign() { auto it = m_transfers.begin(); while (it != m_transfers.end()) { if (it->second.amount < 0) { it->second.amount = -it->second.amount; ++it; } else { it = m_transfers.erase(it); } } } void WalletSerializer::loadTransactions(Common::IInputStream& source, CryptoContext& cryptoContext) { uint64_t count = 0; deserializeEncrypted(count, "transactions_count", cryptoContext, source); cryptoContext.incIv(); m_transactions.get<RandomAccessIndex>().reserve(count); for (uint64_t i = 0; i < count; ++i) { WalletTransactionDto dto; deserializeEncrypted(dto, "", cryptoContext, source); cryptoContext.incIv(); WalletTransaction tx; tx.state = dto.state; tx.timestamp = dto.timestamp; tx.blockHeight = dto.blockHeight; tx.hash = dto.hash; tx.totalAmount = dto.totalAmount; tx.fee = dto.fee; tx.creationTime = dto.creationTime; tx.unlockTime = dto.unlockTime; tx.extra = dto.extra; tx.isBase = false; m_transactions.get<RandomAccessIndex>().push_back(std::move(tx)); } } void WalletSerializer::loadTransfers(Common::IInputStream& source, CryptoContext& cryptoContext, uint32_t version) { uint64_t count = 0; deserializeEncrypted(count, "transfers_count", cryptoContext, source); cryptoContext.incIv(); m_transfers.reserve(count); for (uint64_t i = 0; i < count; ++i) { uint64_t txId = 0; deserializeEncrypted(txId, "transaction_id", cryptoContext, source); cryptoContext.incIv(); WalletTransferDto dto(version); deserializeEncrypted(dto, "transfer", cryptoContext, source); cryptoContext.incIv(); WalletTransfer tr; tr.address = dto.address; tr.amount = dto.amount; if (version > 2) { tr.type = static_cast<WalletTransferType>(dto.type); } else { tr.type = WalletTransferType::USUAL; } m_transfers.push_back(std::make_pair(txId, tr)); } } void WalletSerializer::addWalletV1Details(const std::vector<WalletLegacyTransaction>& txs, const std::vector<WalletLegacyTransfer>& trs) { size_t txId = 0; m_transfers.reserve(trs.size()); for (const auto& tx: txs) { WalletTransaction mtx = convert(tx); m_transactions.get<RandomAccessIndex>().push_back(std::move(mtx)); if (tx.firstTransferId != WALLET_LEGACY_INVALID_TRANSFER_ID && tx.transferCount != 0) { size_t firstTr = tx.firstTransferId; size_t lastTr = firstTr + tx.transferCount; if (lastTr > trs.size()) { throw std::system_error(make_error_code(error::INTERNAL_WALLET_ERROR)); } for (; firstTr < lastTr; firstTr++) { WalletTransfer tr = convert(trs[firstTr]); m_transfers.push_back(std::make_pair(txId, tr)); } } txId++; } } } //namespace CryptoNote
[ "rpghill@gmail.com" ]
rpghill@gmail.com
5e1dc47a28ab90576438b5cb7f8cb5770da2a22f
6629f18d84dc8d5a310b95fedbf5be178b00da92
/FooBarMircP.cpp
fd88d0b503341daeeb9d5e2d2f39fd3e8da9acd1
[]
no_license
thenfour/WMircP
317f7b36526ebf8061753469b10f164838a0a045
ad6f4d1599fade2ae4e25656a95211e1ca70db31
refs/heads/master
2021-01-01T17:42:20.670266
2008-07-11T03:10:48
2008-07-11T03:10:48
16,931,152
3
0
null
null
null
null
UTF-8
C++
false
false
14,286
cpp
#include "stdafx.h" #ifdef TARGET_FOOBAR #include "0811 wmp2mirc.h" #include "SDK-2008-05-27\foobar2000\SDK\foobar2000.h" #include <comutil.h> #pragma comment(lib, "SDK-2008-05-27\\foobar2000\\shared\\shared.lib") #pragma comment(lib, "comsuppw.lib") // {865DCA0D-4493-4392-9B52-09D2986008EF} static const IID IID_FooBarMirc = { 0x865dca0d, 0x4493, 0x4392, { 0x9b, 0x52, 0x09, 0xd2, 0x98, 0x60, 0x08, 0xef } }; DECLARE_COMPONENT_VERSION ( "foobarMircP", "0.0", "foobarMircP, by tenfour" ); // exposes foobar media as IWMPMedia. struct FooBarMedia : public IWMPMedia { ULONG m_refcount; std::wstring m_url; std::vector<std::pair<std::wstring, std::wstring> > m_attributes; FooBarMedia() : m_refcount(1) { } HRESULT __stdcall QueryInterface(const IID &iid, void ** out) { if(iid == __uuidof(IWMPMedia)) { *((IWMPMedia**)out) = this; return S_OK; } return E_NOINTERFACE; } ULONG __stdcall AddRef(void) { return ++ m_refcount; } ULONG __stdcall Release(void) { m_refcount --; if(m_refcount > 0) return m_refcount; delete this; return 0; } // IDispatch HRESULT __stdcall GetTypeInfoCount(UINT *){ return E_NOTIMPL; } HRESULT __stdcall GetTypeInfo(UINT,LCID,ITypeInfo **){ return E_NOTIMPL; } HRESULT __stdcall GetIDsOfNames(const IID &,LPOLESTR *,UINT,LCID,DISPID *){ return E_NOTIMPL; } HRESULT __stdcall Invoke(DISPID,const IID &,LCID,WORD,DISPPARAMS *,VARIANT *,EXCEPINFO *,UINT *){ return E_NOTIMPL; } // IWMPMedia HRESULT __stdcall get_isIdentical(IWMPMedia *,VARIANT_BOOL *){ return E_NOTIMPL; } HRESULT __stdcall get_sourceURL(BSTR * out)// REQUIRED { *out = SysAllocString(m_url.c_str()); return S_OK; } HRESULT __stdcall get_name(BSTR *){ return E_NOTIMPL; } HRESULT __stdcall put_name(BSTR){ return E_NOTIMPL; } HRESULT __stdcall get_imageSourceWidth(long *){ return E_NOTIMPL; } HRESULT __stdcall get_imageSourceHeight(long *){ return E_NOTIMPL; } HRESULT __stdcall get_markerCount(long *){ return E_NOTIMPL; } HRESULT __stdcall getMarkerTime(long,double *){ return E_NOTIMPL; } HRESULT __stdcall getMarkerName(long,BSTR *){ return E_NOTIMPL; } HRESULT __stdcall get_duration(double *){ return E_NOTIMPL; } HRESULT __stdcall get_durationString(BSTR *){ return E_NOTIMPL; } HRESULT __stdcall get_attributeCount(long * out)// REQUIRED { *out = (long)m_attributes.size(); return S_OK; } HRESULT __stdcall getAttributeName(long i,BSTR * out)// REQUIRED { *out = SysAllocString(m_attributes[i].first.c_str()); return S_OK; } HRESULT __stdcall getItemInfo(BSTR attrName, BSTR * out)// REQUIRED { _bstr_t name(attrName, true); for(std::vector<std::pair<std::wstring, std::wstring> >::iterator it = m_attributes.begin(); it != m_attributes.end(); ++ it) { if(LibCC::StringEqualsI(it->first, static_cast<PCWSTR>(name))) { // found it. *out = SysAllocString(it->second.c_str()); return S_OK; } } return E_FAIL; } HRESULT __stdcall setItemInfo(BSTR,BSTR){ return E_NOTIMPL; } HRESULT __stdcall getItemInfoByAtom(long,BSTR *){ return E_NOTIMPL; } HRESULT __stdcall isMemberOf(IWMPPlaylist *,VARIANT_BOOL *){ return E_NOTIMPL; } HRESULT __stdcall isReadOnlyItem(BSTR,VARIANT_BOOL *){ return E_NOTIMPL; } }; // this exposes foobar's core somewhat like WMP exposes it's core struct FooBarCore : public IFooBarMirc, public IWMPCore, private play_callback { LibCC::LogReference m_log; FooBarMedia m; FooBarCore() : m_events(0) { #ifdef _DEBUG bool debug = true; #else bool debug = false; #endif m_log.Create(L"foobarMircP.log", core_api::get_my_instance(), debug, debug, true, true, false, true); static_api_ptr_t<play_callback_manager>()->register_callback(this, flag_on_playback_new_track | flag_on_playback_dynamic_info_track | flag_on_playback_stop, false); } ~FooBarCore() { static_api_ptr_t<play_callback_manager>()->unregister_callback(this); } HRESULT __stdcall QueryInterface(const IID &iid, void ** out) { if(iid == IID_FooBarMirc) { *((IFooBarMirc**)out) = this; return S_OK; } return E_NOINTERFACE; } ULONG __stdcall AddRef(void) { return 1; } ULONG __stdcall Release(void) { return 1; } HRESULT __stdcall GetTypeInfoCount(UINT *) { return E_NOTIMPL; } HRESULT __stdcall GetTypeInfo(UINT,LCID,ITypeInfo **) { return E_NOTIMPL; } HRESULT __stdcall GetIDsOfNames(const IID &,LPOLESTR *,UINT,LCID,DISPID *) { return E_NOTIMPL; } HRESULT __stdcall Invoke(DISPID,const IID &,LCID,WORD,DISPPARAMS *,VARIANT *,EXCEPINFO *,UINT *) { return E_NOTIMPL; } HRESULT __stdcall close(void) { return E_NOTIMPL; } HRESULT __stdcall get_URL(BSTR *) { return E_NOTIMPL; } HRESULT __stdcall put_URL(BSTR) { return E_NOTIMPL; } HRESULT __stdcall get_openState(WMPOpenState *) { return E_NOTIMPL; } HRESULT __stdcall get_playState(WMPPlayState *) { return E_NOTIMPL; } HRESULT __stdcall get_controls(IWMPControls **) { return E_NOTIMPL; } HRESULT __stdcall get_settings(IWMPSettings **) { return E_NOTIMPL; } void HandleAliases(FooBarMedia* n, const std::wstring& originalName, const std::wstring& val) { if(LibCC::StringEqualsI(originalName, "artist")) { n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"WM/AlbumArtist", val)); n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"DisplayArtist", val)); } else if(LibCC::StringEqualsI(originalName, "composer")) { n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"Author", val)); n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"WM/Composer", val)); } else if(LibCC::StringEqualsI(originalName, "comment")) { n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"Description", val)); } else if(LibCC::StringEqualsI(originalName, "album")) { n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"HMEAlbumTitle", val)); n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"WM/AlbumTitle", val)); } else if(LibCC::StringEqualsI(originalName, "genre")) { n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"WM/Genre", val)); } else if(LibCC::StringEqualsI(originalName, "genre")) { n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"WM/Genre", val)); } else if(LibCC::StringEqualsI(originalName, "publisher")) { n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"WM/Publisher", val)); } else if(LibCC::StringEqualsI(originalName, "tracknumber")) { n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"WM/Track", val)); n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"WM/TrackNumber", val)); } else if(LibCC::StringEqualsI(originalName, "date")) { n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"WM/Year", val)); } } // Return whether first element is greater than the second static bool AttributeLT(const std::pair<std::wstring, std::wstring>& lhs, const std::pair<std::wstring, std::wstring>& rhs) { return lhs.first < rhs.first; } HRESULT __stdcall get_currentMedia(IWMPMedia ** out) { FooBarMedia* n = new FooBarMedia(); *out = n; static_api_ptr_t<play_control> pc; metadb_handle_ptr handle; if(!pc->get_now_playing(handle)) { m_log->Message("get_now_playing failed."); } else { file_info_impl info; if(!handle->get_info(info)) { m_log->Message("get_info failed."); } else { LibCC::StringConvert(handle->get_path(), n->m_url); n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"SourceURL", n->m_url)); n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"Duration", LibCC::FormatW("")(info.get_length()).Str())); n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(L"FileSize", LibCC::FormatW("")(handle->get_filestats().m_size).Str())); t_size count = info.info_get_count(); for(t_size i = 0; i < count; i ++) { std::wstring name = LibCC::ToUTF16(info.info_enum_name(i)); std::wstring value = LibCC::ToUTF16(info.info_enum_value(i)); n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(name, value)); HandleAliases(n, name, value); } count = info.meta_get_count(); for(t_size i = 0; i < count; i ++) { std::wstring name = LibCC::ToUTF16(info.meta_enum_name(i)); t_size valueCount = info.meta_enum_value_count(i); std::vector<std::wstring> values; for(t_size ival = 0; ival < valueCount; ++ ival) { values.push_back(LibCC::ToUTF16(info.meta_enum_value(i, ival))); } std::wstring value = LibCC::StringJoin(values.begin(), values.end(), L", "); n->m_attributes.push_back(std::pair<std::wstring, std::wstring>(name, value)); HandleAliases(n, name, value); } std::sort(n->m_attributes.begin(), n->m_attributes.end(), AttributeLT); } } return S_OK; } HRESULT __stdcall put_currentMedia(IWMPMedia *) { return E_NOTIMPL; } HRESULT __stdcall get_mediaCollection(IWMPMediaCollection **) { return E_NOTIMPL; } HRESULT __stdcall get_playlistCollection(IWMPPlaylistCollection **) { return E_NOTIMPL; } HRESULT __stdcall get_versionInfo(BSTR *) { return E_NOTIMPL; } HRESULT __stdcall launchURL(BSTR) { return E_NOTIMPL; } HRESULT __stdcall get_network(IWMPNetwork **) { return E_NOTIMPL; } HRESULT __stdcall get_currentPlaylist(IWMPPlaylist **) { return E_NOTIMPL; } HRESULT __stdcall put_currentPlaylist(IWMPPlaylist *) { return E_NOTIMPL; } HRESULT __stdcall get_cdromCollection(IWMPCdromCollection **) { return E_NOTIMPL; } HRESULT __stdcall get_closedCaption(IWMPClosedCaption **) { return E_NOTIMPL; } HRESULT __stdcall get_isOnline(VARIANT_BOOL *) { return E_NOTIMPL; } HRESULT __stdcall get_error(IWMPError **) { return E_NOTIMPL; } HRESULT __stdcall get_status(BSTR *) { return E_NOTIMPL; } // IFooBarMirc IWMPEvents * m_events; void SetEventHandler(IWMPEvents * p) { m_events = p; } // playback_events void on_playback_starting(playback_control::t_track_command,bool) { if(m_events) { m_events->PlayStateChange(wmppsPlaying); } LibCC::g_pLog->Message(L"on_playback_starting"); } void on_playback_new_track(metadb_handle_ptr) { if(m_events) { m_events->PlayStateChange(wmppsPlaying); } LibCC::g_pLog->Message(L"on_playback_new_track"); } void on_playback_stop(playback_control::t_stop_reason) { LibCC::g_pLog->Message(L"on_playback_stop"); } void on_playback_seek(double) { LibCC::g_pLog->Message(L"on_playback_seek"); } void on_playback_pause(bool) { LibCC::g_pLog->Message(L"on_playback_pause"); } void on_playback_edited(metadb_handle_ptr) { LibCC::g_pLog->Message(L"on_playback_edited"); } void on_playback_dynamic_info(const file_info &) { LibCC::g_pLog->Message(L"on_playback_dynamic_info"); } void on_playback_dynamic_info_track(const file_info &) { LibCC::g_pLog->Message(L"on_playback_dynamic_info_track"); } void on_playback_time(double) { LibCC::g_pLog->Message(L"on_playback_time"); } void on_volume_change(float) { LibCC::g_pLog->Message(L"on_volume_change"); } }; struct FooBarMircApp { FooBarMircApp() { CoInitialize(0); //CoCreateInstance(CLSID_Wmp2mirc, 0, CLSCTX_INPROC_SERVER, __uuidof(IWMPPluginUI), (VOID**)&plugin); plugin.SetCore(&adapter); } ~FooBarMircApp() { CoUninitialize(); } CComObject<CWmp2mirc> plugin; FooBarCore adapter; }; FooBarMircApp* g_instance = 0; class initquit_tutorial1 : public initquit { virtual void on_init() { g_instance = new FooBarMircApp(); } virtual void on_quit() { delete g_instance; } }; static initquit_factory_t< initquit_tutorial1 > foo_initquit; class mainmenu_commands_tutorial1 : public mainmenu_commands { // Return the number of commands we provide. virtual t_uint32 get_command_count() { return 1; } // All commands are identified by a GUID. virtual GUID get_command(t_uint32 p_index) { // {C818DE52-3F2C-459B-811D-D104C60C9384} static const GUID guid_main_tutorial1 = { 0xc818de52, 0x3f2c, 0x459b, { 0x81, 0x1d, 0xd1, 0x04, 0xc6, 0x0c, 0x93, 0x84 } }; if (p_index == 0) return guid_main_tutorial1; return pfc::guid_null; } // Set p_out to the name of the n-th command. // This name is used to identify the command and determines // the default position of the command in the menu. virtual void get_name(t_uint32 p_index, pfc::string_base & p_out) { if (p_index == 0) p_out = "Show foobarMircP"; } // Set p_out to the description for the n-th command. virtual bool get_description(t_uint32 p_index, pfc::string_base & p_out) { if (p_index == 0) p_out = "Show foobarMircP"; else return false; return true; } // Every set of commands needs to declare which group it belongs to. virtual GUID get_parent() { return mainmenu_groups::view; } // Execute n-th command. // p_callback is reserved for future use. virtual void execute(t_uint32 p_index, service_ptr_t<service_base> p_callback) { if (p_index == 0 && core_api::assert_main_thread()) { g_instance->plugin.DisplayPropertyPage(core_api::get_main_window()); } } // The standard version of this command does not support checked or disabled // commands, so we use our own version. virtual bool get_display(t_uint32 p_index, pfc::string_base & p_text, t_uint32 & p_flags) { p_flags = 0; get_name(p_index,p_text); return true; } }; // We need to create a service factory for our menu item class, // otherwise the menu commands won't be known to the system. static mainmenu_commands_factory_t< mainmenu_commands_tutorial1 > foo_menu; #endif
[ "carl@72871cd9-16e1-0310-933f-800000000000" ]
carl@72871cd9-16e1-0310-933f-800000000000
deffc89284259af74c7b1beb57add344a0b1252d
611dfda5d7dd68f76ad92f505e1f3a2bf6fa55a9
/Cxx/GeometricObjects/ParametricObjects.cxx
f98c44a8ce8c950ed6b161bcc9ab1b1396f2a9a0
[]
no_license
sandylovesa/VTKWikiExamples
acdbf47ebe01d082a96a291549c0f1cd45c12135
b8a5d4336527fa24b768a1bd3fb5004d2b5e79ac
refs/heads/master
2020-12-25T02:10:38.460642
2016-06-30T00:22:48
2016-06-30T00:22:48
62,450,904
1
0
null
2016-07-02T12:59:15
2016-07-02T12:59:15
null
UTF-8
C++
false
false
3,804
cxx
#include <vtkSmartPointer.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <vtkParametricFunctionSource.h> // Select one of the following: #include <vtkParametricTorus.h> //#include <vtkParametricBoy.h> //#include <vtkParametricConicSpiral.h> //#include <vtkParametricCrossCap.h> //#include <vtkParametricDini.h> //#include <vtkParametricEllipsoid.h> //#include <vtkParametricEnneper.h> //#include <vtkParametricFigure8Klein.h> //#include <vtkParametricKlein.h> //#include <vtkParametricMobius.h> //#include <vtkParametricRandomHills.h> //#include <vtkParametricRoman.h> //#include <vtkParametricSpline.h> //#include <vtkParametricSuperEllipsoid.h> //#include <vtkParametricSuperToroid.h> //#include <vtkParametricTorus.h> int main(int, char *[]) { // Select one of the following (matching the selection above) vtkSmartPointer<vtkParametricTorus> parametricObject = vtkSmartPointer<vtkParametricTorus>::New(); //vtkSmartPointer<vtkParametricBoy> parametricObject = vtkSmartPointer<vtkParametricBoy>::New(); //vtkSmartPointer<vtkParametricConicSpiral> parametricObject = vtkSmartPointer<vtkParametricConicSpiral>::New(); //vtkSmartPointer<vtkParametricCrossCap> parametricObject = vtkSmartPointer<vtkParametricCrossCap>::New(); //vtkSmartPointer<vtkParametricDini> parametricObject = vtkSmartPointer<vtkParametricDini>::New(); //vtkSmartPointer<vtkParametricEllipsoid> parametricObject = vtkSmartPointer<vtkParametricEllipsoid>::New(); //vtkSmartPointer<vtkParametricEnneper> parametricObject = vtkSmartPointer<vtkParametricEnneper>::New(); //vtkSmartPointer<vtkParametricFigure8Klein> parametricObject = vtkSmartPointer<vtkParametricFigure8Klein>::New(); //vtkSmartPointer<vtkParametricKlein> parametricObject = vtkSmartPointer<vtkParametricKlein>::New(); //vtkSmartPointer<vtkParametricMobius> parametricObject = vtkSmartPointer<vtkParametricMobius>::New(); //vtkSmartPointer<vtkParametricRandomHills> parametricObject = vtkSmartPointer<vtkParametricRandomHills>::New(); //vtkSmartPointer<vtkParametricRoman> parametricObject = vtkSmartPointer<vtkParametricRoman>::New(); //vtkSmartPointer<vtkParametricSpline> parametricObject = vtkSmartPointer<vtkParametricSpline>::New(); //vtkSmartPointer<vtkParametricSuperEllipsoid> parametricObject = vtkSmartPointer<vtkParametricSuperEllipsoid>::New(); //vtkSmartPointer<vtkParametricSuperToroid> parametricObject = vtkSmartPointer<vtkParametricSuperToroid>::New(); //vtkSmartPointer<vtkParametricTorus> parametricObject = vtkSmartPointer<vtkParametricTorus>::New(); vtkSmartPointer<vtkParametricFunctionSource> parametricFunctionSource = vtkSmartPointer<vtkParametricFunctionSource>::New(); parametricFunctionSource->SetParametricFunction(parametricObject); parametricFunctionSource->Update(); // Visualize vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputConnection(parametricFunctionSource->GetOutputPort()); // Create an actor for the contours vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> interactor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); interactor->SetRenderWindow(renderWindow); renderer->AddActor(actor); renderer->SetBackground(1,1,1); // Background color white renderWindow->Render(); interactor->Start(); return EXIT_SUCCESS; }
[ "bill.lorensen@gmail.com" ]
bill.lorensen@gmail.com
6550eb520324f284c3364f52397ec707712928e2
90fcec73f1705397329576bbb0edcc67a68ac478
/EBON/ShaderFade.cpp
ba62b1ca83e09e1c6ff6d027efed68d0e23b0d63
[]
no_license
wernut/EBON
e61759c3f96f830b68f3130a07616b831dc0539a
824757487a5f73c583dc3c82310f08a2382667a1
refs/heads/master
2021-12-14T17:43:07.702828
2021-12-02T04:36:28
2021-12-02T04:36:28
237,874,654
0
0
null
null
null
null
UTF-8
C++
false
false
3,068
cpp
/*============================================================================= * Project: EBON Engine * Version: 1.0 * * Class: ShaderFade.h & ShaderFade.cpp * Purpose: Serves as an effect shader, made to help understand shaders a * a bit better. * * Author: Lachlan Wernert *===========================================================================*/ #include "ShaderFade.h" #include "GameManager.h" // Loading the shader from the effects folder: ShaderFade::ShaderFade() : ShaderProgram("..\\Shaders\\Effects\\fade_vertex.glsl", "..\\Shaders\\Effects\\fade_fragment.glsl") { // Setting the default values: m_defaultSpeed = 3.5f; m_defaultMax = 10.0f; m_defaultMin = -1.0f; // Setting all timer values to default: ResetEffect(); } ShaderFade::~ShaderFade() {} void ShaderFade::Update(float deltaTime) { // Getting the application instance to get the time value: Application* application = GameManager::getInstance()->getApplication(); float time = (float) application->getTime(); // Binding the shader and setting the uniform values inside: bind(); setBool("isRunning", m_effectStatus); setBool("hasFaded", m_hasFaded); setFloat("timer", m_timer); setFloat("appTime", time); if (m_effectStatus) { // If the object isn't showing. (Timer > the height of the object). if (m_hasFaded) { // If the timer is greater than the min value: if (m_timer > m_timerMin) { // Negating the timer value by the timer speed: m_timer -= m_timerSpeed * deltaTime; } else { // If the effect has successfully faded: StopEffect(); m_hasFaded = false; } } else { // Doing the opposite of above to get a fade in effect: if (m_timer < m_timerMax) { m_timer += m_timerSpeed * deltaTime; } else { StopEffect(); m_hasFaded = true; } } } } void ShaderFade::ToggleEffect(float speed, float maxTime, float minTime) { // Sets the speed if parameter > 0: if (speed > 0.0f) m_defaultSpeed = speed; // Sets the min time if parameter > 0: if (maxTime > 0.0f) m_defaultMax = maxTime; // Sets the max time if parameter > 0: if (minTime > 0.0f) m_defaultMin = minTime; // Toggles the effect status: m_effectStatus = !m_effectStatus; } void ShaderFade::StartEffect() { // Setting the effect status to true: m_effectStatus = true; } void ShaderFade::StopEffect() { // Setting the effect status to false: m_effectStatus = false; } void ShaderFade::ResetEffect() { // Setting all the timer values back to default: m_timerSpeed = m_defaultSpeed; m_timerMax = m_defaultMax; m_timerMin = m_defaultMin; m_timer = m_timerMax; m_hasFaded = true; }
[ "wernert97@live.com" ]
wernert97@live.com
12fb12404f8a38b3547551ba38b3b6c98cb60c9c
328aa43cffe647ed2d971cbf8a4f864d54635643
/210. Course Schedule II/solution1.cpp
87adfb6bc785c8292536b391d9f5316573cdc2b1
[]
no_license
diwujiahao/leetcode
24fa5990af640fcab6c8ca2f20e61db8058e7968
58f49db3fd532eee4630c86f62786d36fcb1f9d2
refs/heads/master
2021-05-08T22:31:20.014373
2019-06-17T15:27:28
2019-06-17T15:27:28
119,675,284
2
0
null
null
null
null
UTF-8
C++
false
false
1,318
cpp
// 拓扑搜索 class Solution { public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<int> in_count(numCourses, 0); // 每个节点的入度 vector<vector<int>> graph(numCourses, vector<int>()); // 记录每个节点指向的节点 queue<int> temp; // 记录当前出度为0的节点 vector<int> result; for (auto p : prerequisites){ graph[p.second].push_back(p.first); in_count[p.first]++; } // 获取当前出度为0的节点 for (int i = 0; i < in_count.size(); i++){ if (in_count[i] == 0){ temp.push(i); } } // 每次出栈一个出度为0的节点 while (!temp.empty()){ int node = temp.front(); result.push_back(node); temp.pop(); in_count[node]--; for (auto i : graph[node]){ if (--in_count[i] == 0){ temp.push(i); } } } // 根据其余节点的出度判断是否遍历完全 for (int i = 0; i < in_count.size(); i++){ if (in_count[i] > 0){ return vector<int>(); } } return result;; } };
[ "" ]
f224f093a4dfb00ab52debd5510e7163d3272bb1
914c61d58282b9e00e8d2426c367eba67512f169
/Projects/Project3/tree.cpp
564535cb7f1a1dfec3dfea416df3eec9fbfd08de
[]
no_license
Zachary-Rust/Zachary-Rust-CSCI-21
ab8d6c7b39cf74f826b70055d91408823051a1b9
23ea9cf0165f2b3d64656526b861575ac37a1fec
refs/heads/master
2021-05-09T20:43:40.145431
2018-05-20T04:27:35
2018-05-20T04:27:35
118,703,609
0
0
null
null
null
null
UTF-8
C++
false
false
4,568
cpp
#include "tree.h" bool Tree::LoadWords(string file) { ifstream inFS; inFS.open(file.c_str()); if (!inFS.is_open()) { return false; } int word_count = 0; int weight = 0; string word = ""; string temp = ""; getline(inFS, temp); stringstream ss; ss << temp; ss >> word_count; ss.clear(); for (int i = 0; i < word_count; i++) { //Load whole line getline(inFS, word); //Extract numbers from line, leaving just the city bool separate = false; stringstream num; stringstream wor; for (int i = 0; i < word.length(); i++) { if (!separate) { if (isalnum(word.at(i)) || isalpha(word.at(i))) { num << word.at(i); } else { separate = true; } } else { if (word.at(i) != ' ') { wor << word.at(i); } } } //cout << "NUM " << weight << endl; num >> weight; word = ""; wor >> word; //Add Node to tree Insert(word, weight); num.clear(); wor.clear(); } } int Tree::Size() { return size_; } void Tree::InOrder(Node *node) { if (node->GetLeft() != NULL) { InOrder(node->GetLeft()); } cout << node->GetWeight() << " " << node->GetWord() << endl; if (node->GetRight() != NULL) { InOrder(node->GetRight()); } } void Tree::Insert(string word, int weight) { if (root_ == NULL) { Node *temp = new Node; temp->SetWord(word); temp->SetWeight(weight); root_ = temp; size_++; } else { Insert(root_, word, weight); size_++; } } void Tree::Insert(Node *node, string word, int weight) { if (weight <= node->GetWeight()) { if (node->GetLeft() == NULL) { Node *temp = new Node; temp->SetWord(word); temp->SetWeight(weight); node->SetLeft(temp); } else { Insert(node->GetLeft(), word, weight); } } else { if (node->GetRight() == NULL) { Node *temp = new Node; temp->SetWord(word); temp->SetWeight(weight); node->SetRight(temp); } else { Insert(node->GetRight(), word, weight); } } } int Tree::WordWeight(string key) { return WordWeight(root_, key); } int Tree::WordWeight(Node *node, string key) { if (node->GetWord() == key) { return node->GetWeight(); } if (node->GetLeft() != NULL) { WordWeight(node->GetLeft(), key); } if (node->GetRight() != NULL) { WordWeight(node->GetRight(), key); } } string Tree::AutoComplete(Node *node,string prefix, string result) { if(node->GetRight() != NULL) { result = AutoComplete(node->GetRight(), prefix, result); } stringstream ss; if(node->GetWord().size() >= prefix.size()) { if (prefix == node->GetWord().substr(0, prefix.size())) { ss << node->GetWord(); string temp = ""; ss >> temp; result += temp; result += "\n"; } else if(node->GetWord().substr(0, prefix.size()) == prefix.substr(0, node->GetWord().size())) { ss << node->GetWord(); string temp = ""; ss >> temp; result += temp; result += "\n"; } } if (node->GetLeft() != NULL) { result = AutoComplete(node->GetLeft(), prefix, result); } return result; } string Tree::AutoComplete(string prefix) { string word = ""; return AutoComplete(root_, prefix, word); } void Tree::Clear() { if (root_ == NULL) { size_ = 0; return; } else { Clear(root_); root_ = NULL; } size_ = 0; } void Tree::Clear(Node *node) { if (node->GetLeft() != NULL) { Clear(node->GetLeft()); } if (node->GetRight() != NULL) { Clear(node->GetRight()); } delete node; } Node* Tree::GetRoot() { return root_; }
[ "zrust001@student.butte.edu" ]
zrust001@student.butte.edu
557353229467fe6ae9f2752f0ae560bb48a4b4d6
7a9f509fbd2b3e28ef3fdd642c820d915843320a
/leetcodeseptember1.cpp
49d6930e204c051e2e4565afaf46a844cf5a0467
[]
no_license
ap9891/Leetcode-Practice
e02692b555c41eeb7e8a3c28f03be39aa55cb6c2
681b6ba974a9e119cdcfbbb96bb41f2bf7f35bfb
refs/heads/master
2023-07-02T11:27:06.092531
2021-08-02T17:14:50
2021-08-02T17:14:50
392,031,241
1
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
class Solution { public: bool static comparator(int a,int b) { return a>b; } string largestTimeFromDigits(vector<int>& A) { string arr = ""; sort(A.begin(),A.end(),comparator); do { string hour = to_string(A[0]) + to_string(A[1]); string min = to_string(A[2])+to_string(A[3]); if(hour < "24" && min < "60") { return hour+":"+min; } }while(prev_permutation(A.begin(),A.end())); return ""; } };
[ "areeshaparveen711@gmail.com" ]
areeshaparveen711@gmail.com
3a6c5562a0d898da0a5e0be9b7fdc3788c833bc3
933b9f928512deea626867ca3ff75b75439e897e
/WindowsForms/MfcWinFormsHost/anotherMfcTest/ChildFrm.cpp
6a69b9def3c907d51d62de2f2b9d51aec4c865c3
[]
no_license
KallunWillock/Plantillas-VB6
d51a313f7c9c2aa38b1944c546eb2211a371daaa
0b81034525b8233007a78c73aef331a9c47f1ceb
refs/heads/master
2022-01-25T23:07:53.897857
2018-08-25T14:26:53
2018-08-25T14:26:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
974
cpp
// ChildFrm.cpp : implementation of the CChildFrame class // #include "stdafx.h" #include "anotherMfcTest.h" #include "ChildFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CChildFrame IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd) BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWnd) END_MESSAGE_MAP() // CChildFrame construction/destruction CChildFrame::CChildFrame() { // TODO: add member initialization code here } CChildFrame::~CChildFrame() { } BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying the CREATESTRUCT cs if( !CMDIChildWnd::PreCreateWindow(cs) ) return FALSE; return TRUE; } // CChildFrame diagnostics #ifdef _DEBUG void CChildFrame::AssertValid() const { CMDIChildWnd::AssertValid(); } void CChildFrame::Dump(CDumpContext& dc) const { CMDIChildWnd::Dump(dc); } #endif //_DEBUG // CChildFrame message handlers
[ "noreply@github.com" ]
noreply@github.com
4e7aa4a661bde1255b2219dff3aa4cd21538ca00
57653d6f4845c1b5f00df5d6eb07fdf78af6358b
/libs/gltfio/src/MaterialGenerator.cpp
b0d8f1040ae8d3d2ec65cbfc865483c03ce6d1e3
[ "LicenseRef-scancode-unknown-license-reference", "CC0-1.0", "Apache-2.0" ]
permissive
ryanmccombe/filament
d559efdbb5611f8d2fab9b42b85a68e827fc63d1
dcc17b9b7ef022205bd3a6bfd6af03c95e6edcc2
refs/heads/master
2020-05-06T15:51:44.018953
2019-04-08T18:43:01
2019-04-08T18:43:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,318
cpp
/* * Copyright (C) 2019 The Android Open Source Project * * 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 <gltfio/MaterialProvider.h> #include <filamat/MaterialBuilder.h> #include <utils/Log.h> #include <utils/Hash.h> #include <tsl/robin_map.h> #include <string> using namespace filamat; using namespace filament; using namespace gltfio; using namespace utils; namespace { class MaterialGenerator : public MaterialProvider { public: MaterialGenerator(filament::Engine* engine); ~MaterialGenerator(); filament::MaterialInstance* createMaterialInstance(MaterialKey* config, UvMap* uvmap, const char* label) override; size_t getMaterialsCount() const noexcept override; const filament::Material* const* getMaterials() const noexcept override; void destroyMaterials() override; using HashFn = utils::hash::MurmurHashFn<MaterialKey>; tsl::robin_map<MaterialKey, filament::Material*, HashFn> mCache; std::vector<filament::Material*> mMaterials; filament::Engine* mEngine; }; MaterialGenerator::MaterialGenerator(Engine* engine) : mEngine(engine) { MaterialBuilder::init(); } MaterialGenerator::~MaterialGenerator() { MaterialBuilder::shutdown(); } size_t MaterialGenerator::getMaterialsCount() const noexcept { return mMaterials.size(); } const Material* const* MaterialGenerator::getMaterials() const noexcept { return mMaterials.data(); } void MaterialGenerator::destroyMaterials() { for (auto& iter : mCache) { mEngine->destroy(iter.second); } mMaterials.clear(); mCache.clear(); } static std::string shaderFromKey(const MaterialKey& config) { std::string shader = "void material(inout MaterialInputs material) {\n"; if (config.hasNormalTexture && !config.unlit) { shader += "float2 normalUV = ${normal};\n"; if (config.hasTextureTransforms) { shader += "normalUV = (vec3(normalUV, 1.0) * materialParams.normalUvMatrix).xy;\n"; } shader += R"SHADER( material.normal = texture(materialParams_normalMap, normalUV).xyz * 2.0 - 1.0; material.normal.xy *= materialParams.normalScale; )SHADER"; } shader += R"SHADER( prepareMaterial(material); material.baseColor = materialParams.baseColorFactor; )SHADER"; if (config.hasBaseColorTexture) { shader += "float2 baseColorUV = ${color};\n"; if (config.hasTextureTransforms) { shader += "baseColorUV = (vec3(baseColorUV, 1.0) * " "materialParams.baseColorUvMatrix).xy;\n"; } shader += R"SHADER( material.baseColor *= texture(materialParams_baseColorMap, baseColorUV); )SHADER"; } if (config.alphaMode == AlphaMode::BLEND) { shader += R"SHADER( material.baseColor.rgb *= material.baseColor.a; )SHADER"; } if (config.hasVertexColors) { shader += "material.baseColor *= getColor();\n"; } if (!config.unlit) { shader += R"SHADER( material.roughness = materialParams.roughnessFactor; material.metallic = materialParams.metallicFactor; material.emissive.rgb = materialParams.emissiveFactor.rgb; )SHADER"; if (config.hasMetallicRoughnessTexture) { shader += "float2 metallicRoughnessUV = ${metallic};\n"; if (config.hasTextureTransforms) { shader += "metallicRoughnessUV = (vec3(metallicRoughnessUV, 1.0) * " "materialParams.metallicRoughnessUvMatrix).xy;\n"; } shader += R"SHADER( vec4 roughness = texture(materialParams_metallicRoughnessMap, metallicRoughnessUV); material.roughness *= roughness.g; material.metallic *= roughness.b; )SHADER"; } if (config.hasOcclusionTexture) { shader += "float2 aoUV = ${ao};\n"; if (config.hasTextureTransforms) { shader += "aoUV = (vec3(aoUV, 1.0) * materialParams.occlusionUvMatrix).xy;\n"; } shader += R"SHADER( material.ambientOcclusion = texture(materialParams_occlusionMap, aoUV).r * materialParams.aoStrength; )SHADER"; } if (config.hasEmissiveTexture) { shader += "float2 emissiveUV = ${emissive};\n"; if (config.hasTextureTransforms) { shader += "emissiveUV = (vec3(emissiveUV, 1.0) * " "materialParams.emissiveUvMatrix).xy;\n"; } shader += R"SHADER( material.emissive.rgb *= texture(materialParams_emissiveMap, emissiveUV).rgb; material.emissive.a = 3.0; )SHADER"; } } shader += "}\n"; return shader; } static Material* createMaterial(Engine* engine, const MaterialKey& config, const UvMap& uvmap, const char* name) { std::string shader = shaderFromKey(config); gltfio::details::processShaderString(&shader, uvmap, config); MaterialBuilder builder = MaterialBuilder() .name(name) .flipUV(false) .material(shader.c_str()) .doubleSided(config.doubleSided); switch (engine->getBackend()) { case Engine::Backend::OPENGL: builder.targetApi(MaterialBuilder::TargetApi::OPENGL); break; case Engine::Backend::VULKAN: builder.targetApi(MaterialBuilder::TargetApi::VULKAN); break; case Engine::Backend::METAL: builder.targetApi(MaterialBuilder::TargetApi::METAL); break; default: slog.e << "Unresolved backend, unable to use filamat." << io::endl; return nullptr; } static_assert(std::tuple_size<UvMap>::value == 8, "Badly sized uvset."); int numTextures = std::max({ uvmap[0], uvmap[1], uvmap[2], uvmap[3], uvmap[4], uvmap[5], uvmap[6], uvmap[7], }); if (numTextures > 0) { builder.require(VertexAttribute::UV0); } if (numTextures > 1) { builder.require(VertexAttribute::UV1); } // BASE COLOR builder.parameter(MaterialBuilder::UniformType::FLOAT4, "baseColorFactor"); if (config.hasBaseColorTexture) { builder.parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "baseColorMap"); if (config.hasTextureTransforms) { builder.parameter(MaterialBuilder::UniformType::MAT3, "baseColorUvMatrix"); } } if (config.hasVertexColors) { builder.require(VertexAttribute::COLOR); } // METALLIC-ROUGHNESS builder.parameter(MaterialBuilder::UniformType::FLOAT, "metallicFactor"); builder.parameter(MaterialBuilder::UniformType::FLOAT, "roughnessFactor"); if (config.hasMetallicRoughnessTexture) { builder.parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "metallicRoughnessMap"); if (config.hasTextureTransforms) { builder.parameter(MaterialBuilder::UniformType::MAT3, "metallicRoughnessUvMatrix"); } } // NORMAL MAP // In the glTF spec normalScale is in normalTextureInfo; in cgltf it is part of texture_view. builder.parameter(MaterialBuilder::UniformType::FLOAT, "normalScale"); if (config.hasNormalTexture) { builder.parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "normalMap"); if (config.hasTextureTransforms) { builder.parameter(MaterialBuilder::UniformType::MAT3, "normalUvMatrix"); } } // AMBIENT OCCLUSION // In the glTF spec aoStrength is in occlusionTextureInfo; in cgltf it is part of texture_view. builder.parameter(MaterialBuilder::UniformType::FLOAT, "aoStrength"); if (config.hasOcclusionTexture) { builder.parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "occlusionMap"); if (config.hasTextureTransforms) { builder.parameter(MaterialBuilder::UniformType::MAT3, "occlusionUvMatrix"); } } // EMISSIVE builder.parameter(MaterialBuilder::UniformType::FLOAT3, "emissiveFactor"); if (config.hasEmissiveTexture) { builder.parameter(MaterialBuilder::SamplerType::SAMPLER_2D, "emissiveMap"); if (config.hasTextureTransforms) { builder.parameter(MaterialBuilder::UniformType::MAT3, "emissiveUvMatrix"); } } switch(config.alphaMode) { case AlphaMode::OPAQUE: builder.blending(MaterialBuilder::BlendingMode::OPAQUE); break; case AlphaMode::MASK: builder.blending(MaterialBuilder::BlendingMode::MASKED); builder.maskThreshold(config.alphaMaskThreshold); break; case AlphaMode::BLEND: builder.blending(MaterialBuilder::BlendingMode::TRANSPARENT); builder.depthWrite(true); } builder.shading(config.unlit ? Shading::UNLIT : Shading::LIT); Package pkg = builder.build(); return Material::Builder().package(pkg.getData(), pkg.getSize()).build(*engine); } MaterialInstance* MaterialGenerator::createMaterialInstance(MaterialKey* config, UvMap* uvmap, const char* label) { gltfio::details::constrainMaterial(config, uvmap); auto iter = mCache.find(*config); if (iter == mCache.end()) { Material* mat = createMaterial(mEngine, *config, *uvmap, label); mCache.emplace(std::make_pair(*config, mat)); mMaterials.push_back(mat); return mat->createInstance(); } return iter->second->createInstance(); } } // anonymous namespace namespace gltfio { MaterialProvider* MaterialProvider::createMaterialGenerator(filament::Engine* engine) { return new MaterialGenerator(engine); } } // namespace gltfio
[ "philiprideout@gmail.com" ]
philiprideout@gmail.com
a2302e98f378170cf26d00c025870ad309cb1304
fd7caf6aedfefb3967f2f2c4732c5dd02c1f07ab
/planner/planner_project/login_data/LoginData.cpp
0ae80f7293de6851416aa315f00f90fd0d477ba5
[]
no_license
beata-d/planner
c3e2ea73e7127699f9326a6b3d7d5119bc9c2c25
d2ff00c5c4af42abc593b1fac54e464287cd4cc4
refs/heads/master
2020-12-13T18:38:21.277298
2020-01-17T07:44:08
2020-01-17T07:44:08
225,801,232
0
0
null
null
null
null
UTF-8
C++
false
false
389
cpp
#include <iostream> #include "LoginData.h" void LoginData::open_file() { file.open("login_data.txt"); } void LoginData::close_file() { file.close(); } std::string LoginData::read_login() { std::string login; getline(file, login); return login; } std::string LoginData::read_password() { std::string password; getline(file, password); return password; }
[ "beata.danil@protonmail.com" ]
beata.danil@protonmail.com
2876df9117c30f4681ff77bb59524aba8725cb0f
8d8338ac350faec07b05834c32714ded606fdd03
/Hackerrank/pangrams.cpp
b527c2b9276bc8ee90ef5192801a9c7821d0e1cd
[]
no_license
rohitbakoliya/Competitive-Programming--Solution
c8f5cee280dce23baf5a5a13bba54a2bbd95d702
bc60a05dac7d129eed174dc480a5e16d7dd5d256
refs/heads/master
2022-12-26T10:45:37.908419
2020-10-01T16:24:56
2020-10-01T16:24:56
212,259,742
0
1
null
2019-10-10T14:03:46
2019-10-02T05:08:23
C++
UTF-8
C++
false
false
744
cpp
//https://www.hackerrank.com/challenges/pangrams/problem #include <bits/stdc++.h> using namespace std; // Complete the pangrams function below. string pangrams(string str) { vector<bool> check(26, false); int index,len = str.length(); for (int i = 0; i < len; i++){ if (str[i] >= 'A' && str[i] <= 'Z')index = str[i] - 'A'; else if(str[i] >= 'a' && str[i] <= 'z')index = str[i] - 'a'; check[index] = true; } for (int i = 0; i <= 25; i++) if (!check[i])return ("not pangram"); return ("pangram"); } int main() { ofstream fout(getenv("OUTPUT_PATH")); string s; getline(cin, s); string result = pangrams(s); fout << result << "\n"; fout.close(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
bdc34f7f74a4a8fc87e5833e615366c242c4d0da
690b60a57f85bdce71e614676c305e2492fb7608
/KernelSDK/src/kernel/KernelBase/cComplexRect.cpp
7e78ddc30c1264ba5cb590508bf52adfc80ef60d
[ "Apache-2.0" ]
permissive
rodrigomr/VFS
b07886c0a97bf08c2853fa3182e90eba6ff6ff4e
6b68b00df8cb668106c2d0841cbcd46138298717
refs/heads/master
2020-03-30T13:54:59.627030
2018-10-02T12:06:43
2018-10-02T12:06:43
151,293,022
0
0
NOASSERTION
2018-10-02T17:12:38
2018-10-02T17:12:46
null
UTF-8
C++
false
false
53,180
cpp
// Copyright 2018 Grass Valley, A Belden Brand // 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 "stdafx.h" #include "cComplexRectImpl.h" #include "fatal.h" using namespace vfs; // ======================================================================================= // === getReadImpl/getWriteImpl ========================================================== // ======================================================================================= #if IS_COMPLEXRECT_COW #define getReadImpl(IT) static_cast<const cComplexRectImpl &>((IT).m_Pimpl.read()) #define getWriteImpl(IT) static_cast<cComplexRectImpl &>((IT).m_Pimpl.write()) #else #define getReadImpl(IT) reinterpret_cast<const cComplexRectImpl &>((IT).m_Pimpl[0]) #define getWriteImpl(IT) reinterpret_cast<cComplexRectImpl &>((IT).m_Pimpl[0]) #endif // ======================================================================================= // === ADD =============================================================================== // ======================================================================================= #define ADD(__X, __Y, __W, __H) NewFragmentsPimpl.append(cRect(__X, __Y, __W, __H)) // ======================================================================================= // === Construction ====================================================================== // ======================================================================================= cComplexRect::cComplexRect() #if IS_COMPLEXRECT_COW : m_Pimpl(new cComplexRectImpl) #endif { #if !IS_COMPLEXRECT_COW new (m_Pimpl /* dst */, sizeof(m_Pimpl)) cComplexRectImpl(); #endif } // --------------------------------------------------------------------------------------- cComplexRect::cComplexRect(const cRect & InitialFragment) #if IS_COMPLEXRECT_COW : m_Pimpl(new cComplexRectImpl(InitialFragment)) #endif { #if !IS_COMPLEXRECT_COW new (m_Pimpl /* dst */, sizeof(m_Pimpl)) cComplexRectImpl(InitialFragment); #endif } // --------------------------------------------------------------------------------------- cComplexRect::cComplexRect(const std::vector<cRect> & InitialFragments) #if IS_COMPLEXRECT_COW : m_Pimpl(new cComplexRectImpl(InitialFragments)) #endif { #if !IS_COMPLEXRECT_COW new (m_Pimpl /* dst */, sizeof(m_Pimpl)) cComplexRectImpl(InitialFragments); #endif } // --------------------------------------------------------------------------------------- cComplexRect::cComplexRect(const cComplexRect & Other) { *this = Other; } // --------------------------------------------------------------------------------------- cComplexRect::~cComplexRect() { #if !IS_COMPLEXRECT_COW reinterpret_cast<cComplexRectImpl &>(m_Pimpl[0]).~cComplexRectImpl(); #endif } // ======================================================================================= // === operator= ========================================================================= // ======================================================================================= cComplexRect & QAPI cComplexRect::operator=(const cComplexRect & Other) { #if IS_COMPLEXRECT_COW m_Pimpl = Other.m_Pimpl; #else new (m_Pimpl /* dst */, sizeof(m_Pimpl)) cComplexRectImpl(reinterpret_cast<const cComplexRectImpl &>(Other.m_Pimpl[0])); #endif return *this; } cComplexRect & QAPI cComplexRect::operator=(const cRect & Other) { cComplexRectImpl & Pimpl = getWriteImpl(*this); Pimpl.m_Fragments.clear(); Pimpl.m_Fragments.push_back(Other); Pimpl.m_IsBoundsOutOfDate = false; Pimpl.m_IsBoundsDegenerate = Other.isDegenerate(); Pimpl.m_Bounds = Other; return *this; } // ======================================================================================= // === serialise ========================================================================= // ======================================================================================= String QAPI cComplexRect::serialise(void) const { const cComplexRectImpl & Pimpl = getReadImpl(*this); StringStream Buffer; Buffer << L"ComplexRect : " << (unsigned int)Pimpl.m_Fragments.size() << L" fragments {"; cComplexRectImpl::RectList::const_iterator end(Pimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = Pimpl.m_Fragments.begin(); i != end; ++i) { Buffer << L" { " << i->org.x << L", " << i->org.y << L", " << i->len.x << L", " << i->len.y << L" }"; } Buffer << L" }"; return Buffer.str(); } // ======================================================================================= // === calcBounds ======================================================================== // ======================================================================================= cRect QAPI cComplexRect::calcBounds(void) const { return getReadImpl(*this).calcBounds(); } // ======================================================================================= // === isDegenerate ====================================================================== // ======================================================================================= bool QAPI cComplexRect::isDegenerate(void) const { const cComplexRectImpl & Pimpl = getReadImpl(*this); if (Pimpl.m_IsBoundsOutOfDate) (void)Pimpl.calcBounds(); return Pimpl.m_IsBoundsDegenerate; } // ======================================================================================= // === countFragments ==================================================================== // ======================================================================================= unsigned int QAPI cComplexRect::countFragments(void) const { return (unsigned int)getReadImpl(*this).m_Fragments.size(); } // ======================================================================================= // === clearFragments ==================================================================== // ======================================================================================= bool QAPI cComplexRect::clearFragments(void) { const unsigned int PrevSize = (unsigned int)getReadImpl(*this).m_Fragments.size(); if (PrevSize > 0) { cComplexRectImpl & Pimpl = getWriteImpl(*this); Pimpl.m_Fragments.clear(); Pimpl.m_IsBoundsOutOfDate = false; Pimpl.m_IsBoundsDegenerate = true; // Pimpl.m_IsOptimised = true; Pimpl.m_Bounds = cRect(0, 0, 0, 0); return true; } else { return false; } } // ======================================================================================= // === cFragmentIterator ================================================================= // ======================================================================================= cComplexRect::cFragmentIterator::cFragmentIterator(const cComplexRect * const ComplexRect) { #if defined(_DEBUG) QKERNELBASEVERIFY(sizeof(m_Pimpl) >= sizeof(cComplexRectFragmentIteratorImpl)); #endif // Use placement new to create an impl using pre-allocated memory. Need to remember that we // bceome responsible for manually calling the destructors of classes contained within // cComplexRectFragmentIteratorImpl. See ~cFragmentIterator() below. cComplexRectFragmentIteratorImpl* ThisImpl = new (m_Pimpl) cComplexRectFragmentIteratorImpl(); ThisImpl->m_ComplexRectImpl = &getReadImpl(*ComplexRect); ThisImpl->m_Iterator = ThisImpl->m_ComplexRectImpl->m_Fragments.begin(); ThisImpl->m_IteratorPosition = 0; } cComplexRect::cFragmentIterator::~cFragmentIterator() { cComplexRectFragmentIteratorImpl & ThisImpl = reinterpret_cast<cComplexRectFragmentIteratorImpl &>(*m_Pimpl); // Need to manually call destructors for classes allocated using placement new!! ThisImpl.~cComplexRectFragmentIteratorImpl(); } bool /* is valid? */ cComplexRect::cFragmentIterator::gotoFragment(const unsigned int WhichFragment) { cComplexRectFragmentIteratorImpl & ThisImpl = reinterpret_cast<cComplexRectFragmentIteratorImpl &>(*m_Pimpl); const bool IsValid = WhichFragment < ThisImpl.m_ComplexRectImpl->m_Fragments.size(); if (IsValid) { ThisImpl.m_Iterator = ThisImpl.m_ComplexRectImpl->m_Fragments.begin(); for (unsigned int j = 0; j < WhichFragment; ++j) ThisImpl.m_Iterator++; } ThisImpl.m_IteratorPosition = WhichFragment; return IsValid; } bool /* is valid? */ cComplexRect::cFragmentIterator::nextFragment() { cComplexRectFragmentIteratorImpl & ThisImpl = reinterpret_cast<cComplexRectFragmentIteratorImpl &>(*m_Pimpl); ThisImpl.m_IteratorPosition++; const bool IsValid = ThisImpl.m_IteratorPosition < ThisImpl.m_ComplexRectImpl->m_Fragments.size(); if (IsValid) ThisImpl.m_Iterator++; return IsValid; } bool /* is valid? */ cComplexRect::cFragmentIterator::prevFragment() { cComplexRectFragmentIteratorImpl & ThisImpl = reinterpret_cast<cComplexRectFragmentIteratorImpl &>(*m_Pimpl); ThisImpl.m_IteratorPosition--; const bool IsValid = ThisImpl.m_IteratorPosition >= 0; if (IsValid) ThisImpl.m_Iterator--; return IsValid; } cRect * cComplexRect::cFragmentIterator::operator->() const { const cComplexRectFragmentIteratorImpl & ThisImpl = reinterpret_cast<const cComplexRectFragmentIteratorImpl &>(*m_Pimpl); return ThisImpl.m_Iterator.operator->(); } cRect & cComplexRect::cFragmentIterator::operator*() const { const cComplexRectFragmentIteratorImpl & ThisImpl = reinterpret_cast<const cComplexRectFragmentIteratorImpl &>(*m_Pimpl); return ThisImpl.m_Iterator.operator*(); } // ======================================================================================= // === optimise ========================================================================== // ======================================================================================= bool QAPI cComplexRect::optimise(void) { bool WasAnyOptimisationDone = false; const cComplexRectImpl & ReadPimpl = getReadImpl(*this); if (ReadPimpl.m_Fragments.size() > 1 && !ReadPimpl.isDegenerate()/* && !ReadPimpl.m_IsOptimised*/) { cComplexRectImpl & Pimpl = getWriteImpl(*this); cComplexRectImpl::RectList & Fragments = Pimpl.m_Fragments; cComplexRectImpl::RectList::iterator i, j, end = Fragments.end(); // Turn rects from Internal Top Left + Size to Internal Top Left + External Bottom Right. for (i = Fragments.begin(); i != end; ++i) { i->len += i->org; // len is now External Bottom Right } bool WasAnyOptimisationDoneOnThisPass; do { WasAnyOptimisationDoneOnThisPass = false; // Merges pairs sharing same vert edge. for (i = Fragments.begin(); i != end; ++i) { if (*i != cRect(0, 0, 0, 0) /* ignore if marked for removal */) { for (j = Fragments.begin(); j != end; ++j) { if (*j != cRect(0, 0, 0, 0) /* ignore if marked for removal */) { if (*j != *i && i->len.x == j->org.x /* Is I right same as J left? Remember len is bottom right NOT size */ && i->org.y == j->org.y && i->len.y == j->len.y /* Are we vertically aligned? */) { // Excellent, we can merge these two fragments. i->len.x = j->len.x; WasAnyOptimisationDoneOnThisPass = true; *j = cRect(0, 0, 0, 0); // Mark for removal } } } } } // Merges pairs sharing same horiz edge. for (i = Fragments.begin(); i != end; ++i) { if (*i != cRect(0, 0, 0, 0) /* ignore if marked for removal */) { for (j = Fragments.begin(); j != end; ++j) { if (*j != cRect(0, 0, 0, 0) /* ignore if marked for removal */) { if (j != i && i->len.y == j->org.y /* Is I bottom same as J top? Remember len is bottom right NOT size */ && i->org.x == j->org.x && i->len.x == j->len.x /* Are we horiz aligned? */) { // Excellent, we can merge these two fragments. i->len.y = j->len.y; WasAnyOptimisationDoneOnThisPass = true; *j = cRect(0, 0, 0, 0); // Mark for removal } } } } } if (WasAnyOptimisationDoneOnThisPass) { // Remove all rects that are marked for removal for (i = Fragments.begin(); i != Fragments.end();) { if (*i == cRect(0, 0, 0, 0)) { i = Fragments.erase(i); } else { ++i; } } end = Fragments.end(); Pimpl.m_IsBoundsOutOfDate= true; } if (WasAnyOptimisationDoneOnThisPass) WasAnyOptimisationDone = true; } while (WasAnyOptimisationDoneOnThisPass); // Turn rects from Internal Top Left + External Bottom Right back to Internal Top Left + Size. end = Fragments.end(); for (i = Fragments.begin(); i != end; ++i) { i->len -= i->org; // len is now Size } Pimpl.m_IsOptimised = true; } return WasAnyOptimisationDone; } // ======================================================================================= // === amalgamate ======================================================================== // ======================================================================================= bool QAPI cComplexRect::amalgamate( const float BigAreaRatio, const unsigned int SmallAreaThreshold) { bool WasAnyAmalgamationDone = false; const cComplexRectImpl & ReadPimpl = getReadImpl(*this); if (ReadPimpl.m_Fragments.size() > 1 && !ReadPimpl.isDegenerate()) { cComplexRectImpl & Pimpl = getWriteImpl(*this); cComplexRectImpl::RectList & Fragments = Pimpl.m_Fragments; cComplexRectImpl::RectList::iterator end(Fragments.end()); for (cComplexRectImpl::RectList::iterator i = Fragments.begin(); i != end; ++i) { for (cComplexRectImpl::RectList::iterator j = i; j != end; ++j) { if (j != i) { const unsigned int AreaOfFragmentI = i->len.x * i->len.y; const unsigned int AreaOfFragmentJ = j->len.x * j->len.y; const cRect Union (i->Union(*j)); const unsigned int AreaOfUnion = Union.len.x * Union.len.y; const unsigned int UnionLongestEdgeLength = Max<unsigned int>(Union.len.x, Union.len.y); if (UnionLongestEdgeLength < SmallAreaThreshold) { *i = Union; *j = cRect(0, 0, 0, 0); // Mark for removal WasAnyAmalgamationDone = true; } else { const float RatioA = (float)AreaOfUnion / (float)(AreaOfFragmentI + AreaOfFragmentJ); if (RatioA > 0.0f) { const float RatioB = 100.0f / RatioA; if (RatioB > BigAreaRatio) { *i = Union; *j = cRect(0, 0, 0, 0); // Mark for removal WasAnyAmalgamationDone = true; } } } } } } if (WasAnyAmalgamationDone) { // Remove all rects that are marked for removal for (cComplexRectImpl::RectList::iterator i = Fragments.begin(); i != Fragments.end();) { if (*i == cRect(0, 0, 0, 0)) { i = Fragments.erase(i); } else { ++i; } } } } return WasAnyAmalgamationDone; } // ======================================================================================= // === isContaining ====================================================================== // ======================================================================================= bool QAPI cComplexRect::isContaining(const cRect & Other) const { bool IsContained = false; const cComplexRectImpl & Pimpl = getReadImpl(*this); if (!Pimpl.isDegenerate()) { if (Pimpl.calcBounds().isOverlapped(Other)) { cComplexRect Remainder(Other); Remainder.subtract(*this); IsContained = Remainder.isDegenerate(); } } return IsContained; } // --------------------------------------------------------------------------------------- bool QAPI cComplexRect::isContaining(const cComplexRect & Other) const { bool IsContained = false; const cComplexRectImpl & Pimpl = getReadImpl(*this); const cComplexRectImpl & OtherPimpl = getReadImpl(Other); if (!Pimpl.isDegenerate() && !OtherPimpl.isDegenerate()) { if (Pimpl.calcBounds().isOverlapped(OtherPimpl.calcBounds())) { IsContained = true; const cComplexRectImpl::RectList::const_iterator end(OtherPimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = OtherPimpl.m_Fragments.begin(); i != end; ++i) { if (!isContaining(*i)) { IsContained = false; break; } } } } return IsContained; } // --------------------------------------------------------------------------------------- bool QAPI cComplexRect::isContaining(const cComplexRect & Other, const cXY & OrgOffset) const { bool IsContained = false; const cComplexRectImpl & Pimpl = getReadImpl(*this); const cComplexRectImpl & OtherPimpl = getReadImpl(Other); if (!Pimpl.isDegenerate() && !OtherPimpl.isDegenerate()) { const cRect OtherBounds(OtherPimpl.calcBounds()); if (Pimpl.calcBounds().isOverlapped(cRect(OtherBounds.org + OrgOffset, OtherBounds.len))) { IsContained = true; const cComplexRectImpl::RectList::const_iterator end(OtherPimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = OtherPimpl.m_Fragments.begin(); i != end; ++i) { if (!isContaining(cRect(i->org + OrgOffset, i->len))) { IsContained = false; break; } } } } return IsContained; } // ======================================================================================= // === isOverlapping ===================================================================== // ======================================================================================= bool QAPI cComplexRect::isOverlapping(const cRect & Other) const { bool IsOverlapped = false; const cComplexRectImpl & Pimpl = getReadImpl(*this); if (!Pimpl.isDegenerate() && !Other.isDegenerate()) { if (Pimpl.calcBounds().isOverlapped(Other)) { if (Pimpl.m_Fragments.size() == 1) { IsOverlapped = true; } else { const cComplexRectImpl::RectList::const_iterator end(Pimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = Pimpl.m_Fragments.begin(); i != end; ++i) { if (i->isOverlapped(Other)) { IsOverlapped = true; break; } } } } } return IsOverlapped; } // --------------------------------------------------------------------------------------- bool QAPI cComplexRect::isOverlapping(const cComplexRect & Other) const { bool IsOverlapped = false; const cComplexRectImpl & Pimpl = getReadImpl(*this); const cComplexRectImpl & OtherPimpl = getReadImpl(Other); if (!Pimpl.isDegenerate() && !OtherPimpl.isDegenerate()) { if (Pimpl.calcBounds().isOverlapped(OtherPimpl.calcBounds())) { if (Pimpl.m_Fragments.size() == 1 && OtherPimpl.m_Fragments.size() == 1) { IsOverlapped = true; } else { const cComplexRectImpl::RectList::const_iterator end(OtherPimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = OtherPimpl.m_Fragments.begin(); i != end; ++i) { if (isOverlapping(*i)) { IsOverlapped = true; break; } } } } } return IsOverlapped; } // --------------------------------------------------------------------------------------- bool QAPI cComplexRect::isOverlapping(const cComplexRect & Other, const cXY & OrgOffset) const { bool IsOverlapped = false; const cComplexRectImpl & Pimpl = getReadImpl(*this); const cComplexRectImpl & OtherPimpl = getReadImpl(Other); if (!Pimpl.isDegenerate() && !OtherPimpl.isDegenerate()) { const cRect OtherBounds(OtherPimpl.calcBounds()); if (Pimpl.calcBounds().isOverlapped(cRect(OtherBounds.org + OrgOffset, OtherBounds.len))) { if (Pimpl.m_Fragments.size() == 1 && OtherPimpl.m_Fragments.size() == 1) { IsOverlapped = true; } else { const cComplexRectImpl::RectList::const_iterator end(OtherPimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = OtherPimpl.m_Fragments.begin(); i != end; ++i) { if (isOverlapping(cRect(i->org + OrgOffset, i->len))) { IsOverlapped = true; break; } } } } } return IsOverlapped; } // ======================================================================================= // === or ================================================================================ // ======================================================================================= cComplexRect & QAPI cComplexRect::or(const cRect & Other) { if (!Other.isDegenerate())// && !isContaining(Other)) { cComplexRectImpl & Pimpl = getWriteImpl(*this); subtract(Other); Pimpl.append(Other); } return *this; } // --------------------------------------------------------------------------------------- cComplexRect & QAPI cComplexRect::orNotOverlapping(const cRect & Other) { #if defined(_DEBUG) QKERNELBASEVERIFY(!isOverlapping(Other)); #endif if (!Other.isDegenerate())// && !isContaining(Other)) { cComplexRectImpl & Pimpl = getWriteImpl(*this); Pimpl.append(Other); } return *this; } // --------------------------------------------------------------------------------------- cComplexRect & QAPI cComplexRect::or(const cComplexRect & Other) { if (!Other.isDegenerate())// && !isContaining(Other)) { subtract(Other); getWriteImpl(*this).append(getReadImpl(Other)); } return *this; } // --------------------------------------------------------------------------------------- cComplexRect & QAPI cComplexRect::or(const cComplexRect & Other, const cXY & OrgOffset) { if (!Other.isDegenerate())// && !isContaining(Other, OrgOffset)) { subtract(Other, OrgOffset); getWriteImpl(*this).append(getReadImpl(Other), OrgOffset); } return *this; } // ======================================================================================= // === subtract ========================================================================== // ======================================================================================= cComplexRect & QAPI cComplexRect::subtract(const cComplexRect & Other) { if (isOverlapping(Other)) { const cComplexRectImpl & OtherPimpl = getReadImpl(Other); const cComplexRectImpl::RectList::const_iterator end(OtherPimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = OtherPimpl.m_Fragments.begin(); i != end; ++i) { subtract(*i); } } return *this; } // --------------------------------------------------------------------------------------- cComplexRect & QAPI cComplexRect::subtract(const cComplexRect & Other, const cXY & OrgOffset) { if (isOverlapping(Other, OrgOffset)) { const cComplexRectImpl & OtherPimpl = getReadImpl(Other); const cComplexRectImpl::RectList::const_iterator end(OtherPimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = OtherPimpl.m_Fragments.begin(); i != end; ++i) { (void)subtract(cRect(i->org + OrgOffset, i->len)); if (getReadImpl(*this).isDegenerate()) break; } } return *this; } // --------------------------------------------------------------------------------------- cComplexRect & QAPI cComplexRect::subtract(const cRect & Other) { // If fragment to clear or this Complex Rect is degenerate then no point doing anything. if (getReadImpl(*this).isDegenerate() || Other.isDegenerate()) { // Do nothing. } else { cComplexRectImpl & Pimpl = getWriteImpl(*this); const int & cx = Other.org.x; const int & cy = Other.org.y; const int & cw = Other.len.x; const int & ch = Other.len.y; cComplexRect NewFragments; cComplexRectImpl & NewFragmentsPimpl = getWriteImpl(NewFragments); /* bool trace = false; if (Pimpl.m_Fragments.size() == 102) { trace = true; } if (trace) QTRACE((L"end %s", Pimpl.m_Fragments.end().serialise().c_str())); */ int n = 0; for (cComplexRectImpl::RectList::iterator i = Pimpl.m_Fragments.begin(); i != Pimpl.m_Fragments.end();) { // if (trace) QTRACE((L"%d i %s End (%s)", n, i.serialise().c_str(), Pimpl.m_Fragments.end().serialise().c_str())); n++; bool IsRemoving = false; int & ix = i->org.x; int & iy = i->org.y; int & iw = i->len.x; int & ih = i->len.y; const int cr = cx + cw; const int ir = ix + iw; if (cr > ix && cx < ir) // Overlapping horizontally? { const int cb = cy + ch; const int ib = iy + ih; if (cb > iy && cy < ib) // Overlapping veritically? { const unsigned int OverlapType = ( (cy <= iy) ? 1 << 3 : 0 ) | ( (cb >= ib) ? 1 << 2 : 0 ) | ( (cx <= ix) ? 1 << 1 : 0 ) | ( (cr >= ir) ? 1 << 0 : 0 ); // The macros cx, cy, cw, ch, cr, cb are // I## Fragment to clear // defined as being the dimensions of the // ### // fragment to clear and ix, iy, iw, ih, ir and // ### // ib as being the dimensions of an existing // fragment in the list. // C-+ Current exisiting // | | fragment // +-+ switch (OverlapType) { case 0: // REMOVES internal portion. // Sub- C-------+ { // div. | 0 | //Pimpl.m_IsOptimised = false; ADD(ix, cy, cx - ix, ch); // 1 +-I####-+ ADD(cr, cy, ir - cr, ch); // 2 |1#####2| ADD(ix, cb, iw, ib - cb); // 3 +-#####-+ ih = cy - iy; // 0 | 3 | break; // +-------+ } case 1: // REMOVES right middle portion. { //Pimpl.m_IsOptimised = false; // C-------+ // | 0 | ADD(ix, cy, cx - ix, ch); // +----I#### ADD(ix, cb, iw, ib - cb); // 2 | 1 ##### ih = cy - iy; // 0 +----##### // | 2 | break; // +-------+ } case 2: // REMOVES left middle portion. { //Pimpl.m_IsOptimised = false; // C-------+ // | 0 | ADD(cr, cy, ir - cr, ch); // 1 I####----+ ADD(ix, cb, iw, ib - cb); // 2 ##### 1 | ih = cy - iy; // 0 #####----+ // | 2 | break; // +-------+ } case 3: // REMOVES middle horiz portion. { //Pimpl.m_IsOptimised = false; // C-------+ // | 0 | ADD(ix, cb, iw, ib - cb); // 1 I########## ih = cy - iy; // 0 ########### // ########### // | 1 | break; // +-------+ } case 4: // REMOVES bottom middle portion. { //Pimpl.m_IsOptimised = false; // C-------+ // | | ADD(ix, cy, cx - ix, ib - cy); // 1 | 0 | ADD(cr, cy, ir - cr, ib - cy); // 2 | | ih = cy - iy; // 0 +-I####-+ // |1#####2| break; // +-#####-+ } case 5: // REMOVES bottom right portion. { //Pimpl.m_IsOptimised = false; // C-------+ // | | ADD(ix, cy, cx - ix, ib - cy); // 1 | 0 | ih = cy - iy; // 0 | | // +----I#### // | 1 ##### break; // +----##### } case 6: // REMOVES bottom left portion. { //Pimpl.m_IsOptimised = false; // C-------+ // | | ADD(cr, cy, ir - cr, ib - cy); // 1 | 0 | ih = cy - iy; // 0 | | // I####----+ // ##### 1 | break; // #####----+ } case 7: // REMOVES all bottom portion. { //Pimpl.m_IsOptimised = false; // C-------+ // | | ih = cy - iy; // 0 | 0 | // | | // I########## // ########### break; // ########### } case 8: // REMOVES top middle portion. { //Pimpl.m_IsOptimised = false; // C-I####-+ // |1#####2| ADD(ix, iy, cx - ix, cb - iy); // 1 +-#####-+ ADD(cr, iy, ir - cr, cb - iy); // 2 | | ih = ib - cb; iy = cb; // 0 | 0 | // | | break; // +-------+ } case 9: // REMOVES top right corner. { //Pimpl.m_IsOptimised = false; // C----I#### // | 1 ##### ADD(ix, iy, cx - ix, cb - iy); // 1 +----##### ih = ib - cb; iy = cb; // 0 | | // | 0 | // | | break; // +-------+ } case 10: // REMOVES top left corner. { //Pimpl.m_IsOptimised = false; // I####----+ // ##### 1 | ADD(cr, iy, ir - cr, cb - iy); // 1 #####----+ ih = ib - cb; iy = cb; // 0 | | // | 0 | // | | break; // +-------+ } case 11:// REMOVES all top edge. { //Pimpl.m_IsOptimised = false; // I########## // ########### ih = ib - cb; iy = cb; // 0 ########### // | | // | 0 | // | | break; // +-------+ } case 12: // REMOVES vertical down middle. { //Pimpl.m_IsOptimised = false; // C-I####-+ // | ##### | ADD(cr, iy, ir - cr, ih); // 1 | ##### | iw = cx - ix; // 0 |0#####1| // | ##### | // | ##### | break; // +-#####-+ } case 13:// REMOVES all right edge. { //Pimpl.m_IsOptimised = false; // C----I#### // | ##### iw = cx - ix; // 0 | ##### // | 0 ##### // | ##### // | ##### break; // +----##### } case 14: // REMOVES all left edge. { //Pimpl.m_IsOptimised = false; // I####----+ // ##### | iw = ir - cr; ix = cr; // 0 ##### | // ##### 0 | // ##### | // ##### | break; // #####----+ } case 15: // REMOVES all. { // I########## // ########### IsRemoving = true; // ########### // ########### // ########### // ########### break; // ########### } } } Pimpl.m_IsBoundsOutOfDate = true; } if (IsRemoving) { i = Pimpl.m_Fragments.erase(i); } else { ++i; } } if (NewFragmentsPimpl.m_Fragments.size() > 0) { Pimpl.append(NewFragmentsPimpl); } } return *this; } // ======================================================================================= // === and =============================================================================== // ======================================================================================= cComplexRect & QAPI cComplexRect::and(const cComplexRect & Other) { if (getReadImpl(*this).isDegenerate()) { clearFragments(); } else { const cComplexRectImpl & OtherPimpl = getReadImpl(Other); const cComplexRect OriginalBackup(*this); cComplexRect & Accumulator = *this; Accumulator.clearFragments(); const cComplexRectImpl::RectList::const_iterator end(OtherPimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = OtherPimpl.m_Fragments.begin(); i != end; ++i) { cComplexRect Scratch(OriginalBackup); Scratch.and(*i); getWriteImpl(Accumulator).append(getReadImpl(Scratch)); } } return *this; } // --------------------------------------------------------------------------------------- cComplexRect & QAPI cComplexRect::and(const cComplexRect & Other, const cXY & OrgOffset) { if (getReadImpl(*this).isDegenerate()) { clearFragments(); } else { const cComplexRectImpl & OtherPimpl = getReadImpl(Other); const cComplexRect OriginalBackup(*this); cComplexRect & Accumulator = *this; Accumulator.clearFragments(); const cComplexRectImpl::RectList::const_iterator end(OtherPimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::const_iterator i = OtherPimpl.m_Fragments.begin(); i != end; ++i) { cComplexRect Scratch(OriginalBackup); Scratch.and(cRect(i->org + OrgOffset, i->len)); getWriteImpl(Accumulator).append(getReadImpl(Scratch)); } } return *this; } // --------------------------------------------------------------------------------------- cComplexRect & QAPI cComplexRect::and(const cRect & Other) { // If framgment to and or this Complex Rect is degenerate then we end up with a // degenerate result. if (getReadImpl(*this).isDegenerate() || Other.isDegenerate()) { clearFragments(); } else { cComplexRectImpl & Pimpl = getWriteImpl(*this); const int & cx = Other.org.x; const int & cy = Other.org.y; const int & cw = Other.len.x; const int & ch = Other.len.y; for (cComplexRectImpl::RectList::iterator i = Pimpl.m_Fragments.begin(); i != Pimpl.m_Fragments.end();) { bool IsRemoving = false; int & ix = i->org.x; int & iy = i->org.y; int & iw = i->len.x; int & ih = i->len.y; // We'll define cx, cy, cw, ch, cr, cb as being the dimensions of the 'keep' rect // and ix, iy, iw, ih, ir and ib as being the dimensions of the current fragment. const int cr = cx + cw; const int ir = ix + iw; // If Rect we're ANDing overlaps this Rect aleady in the ComplexRect then // we'll have to subdivide the the exiting one. Else, just discard it! if (cr > ix && cx < ir) { const int cb = cy + ch; const int ib = iy + ih; if (cb > iy && cy < ib) { // But first we have to work out _how_ the new Rect overlaps the // existing one. const unsigned OverlapType = ( (cy <= iy) ? 1 << 3 : 0 ) | ( (cb >= ib) ? 1 << 2 : 0 ) | ( (cx <= ix) ? 1 << 1 : 0 ) | ( (cr >= ir) ? 1 << 0 : 0 ); switch (OverlapType) { case 0: // KEEPS centre portion { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // I---+ ix = cx; iy = cy; // |C##| iw = cw; ih = ch; // |###| break; // +---+ } case 1: // KEEPS right middle portion. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // I---+ ix = cx; iy = cy; // | C## iw = ir - cx; ih = ch; // | ### break; // +---+ } case 2: // KEEPS left middle portion. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // I---+ iy = cy; // C## | iw = cr - ix; ih = ch; // ### | break; // +---+ } case 3: // KEEPS all middle horiz portion. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // I---+ iy = cy; // C###### ih = ch; // ####### break; // +---+ } case 4: // KEEPS bottom middle portion. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // I---+ ix = cx; iy = cy; // | | iw = cw; ih = ib - cy; // |C##| break; // +###+ } // ### case 5: // KEEPS bottom right portion. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // I---+ ix = cx; iy = cy; // | | iw = ir - cx; ih = ib - cy; // | C## break; // +--### } // ### case 6: // KEEPS bottom left portion. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // I---+ iy = cy; // | | iw = cr - ix; ih = ib - cy; // C## | break; // ###--+ } // ### case 7: // KEEPS all bottom portion. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // I---+ iy = cy; // | | ih = ib - cy; // C###### break; // ####### } case 8: // KEEPS top middle portion. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // C## ix = cx; // T###+ iw = cw; ih = cb - iy; // |###| break; // | | } // +---+ case 9: // KEEPS top right corner. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // C## ix = cx; // I--### iw = ir - cx; ih = cb - iy; // | ### break; // | | } // +---+ case 10: // KEEPS top left corner. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // C## iw = cr - ix; ih = cb - iy; // ###--+ break; // ### | } // +---+ case 11: // KEEPS all top edge. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // C###### ih = cb - iy; // ####### break; // | | } // +---+ case 12: // KEEPS vertical portion down middle. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // C## ix = cx; // I-###-+ iw = cw; // | ### | break; // +-###-+ } // ### case 13: // KEEPS all right edge. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // C## ix = cx; // I----### iw = ir - cx; // | ### break; // +----### } // ### case 14: // KEEPS all left edge. { Pimpl.m_IsBoundsOutOfDate = true; //Pimpl.m_IsOptimised = false; // C## iw = cr - ix; // ###----+ break; // ### | } // ###----+ // ### case 15: // KEEPS all. { // C####### break; // ######## } // ######## } } else { IsRemoving = true; } } else { IsRemoving = true; } if (IsRemoving) { Pimpl.m_IsBoundsOutOfDate = true; i = Pimpl.m_Fragments.erase(i); } else { ++i; } } } return *this; } // ======================================================================================= // === not =============================================================================== // ======================================================================================= cComplexRect & QAPI cComplexRect::not(const cRect & Other) { cComplexRectImpl & Pimpl = getWriteImpl(*this); cComplexRect Inverse(Other); const cComplexRectImpl::RectList::const_iterator end(Pimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::iterator i = Pimpl.m_Fragments.begin(); i != end; ++i) { Inverse.subtract(*i); } subtract(Other); Pimpl.append(getReadImpl(Inverse)); return *this; } // --------------------------------------------------------------------------------------- cComplexRect & QAPI cComplexRect::not(const cComplexRect & Other) { cComplexRectImpl & Pimpl = getWriteImpl(*this); cComplexRect Inverse(Other); const cComplexRectImpl::RectList::const_iterator end(Pimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::iterator i = Pimpl.m_Fragments.begin(); i != end; ++i) { Inverse.subtract(*i); } subtract(Other); Pimpl.append(getReadImpl(Inverse)); return *this; } // --------------------------------------------------------------------------------------- cComplexRect & QAPI cComplexRect::not(const cComplexRect & Other, const cXY & OrgOffset) { cComplexRectImpl & Pimpl = getWriteImpl(*this); cComplexRect Inverse(Other); const cComplexRectImpl::RectList::const_iterator end(Pimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::iterator i = Pimpl.m_Fragments.begin(); i != end; ++i) { Inverse.subtract(cRect(i->org + OrgOffset, i->len)); } subtract(Other); Pimpl.append(getReadImpl(Inverse)); return *this; } // ======================================================================================= // === incOrg ============================================================================ // ======================================================================================= cComplexRect & QAPI cComplexRect::incOrg(const cXY Inc) { if (Inc != cXY(0, 0)) { if (getReadImpl(*this).m_Fragments.size() > 0) { cComplexRectImpl & Pimpl = getWriteImpl(*this); const cComplexRectImpl::RectList::const_iterator end(Pimpl.m_Fragments.end()); for (cComplexRectImpl::RectList::iterator i = Pimpl.m_Fragments.begin(); i != end; ++i) { i->org += Inc; } if (!Pimpl.m_IsBoundsOutOfDate) { Pimpl.m_Bounds.org += Inc; } } } return *this; } // ======================================================================================= // === getFragments ====================================================================== // ======================================================================================= cRect & QAPI cComplexRect::getFragment(const unsigned int j) const { const cComplexRectImpl & Pimpl = getReadImpl(*this); const cComplexRectImpl::RectList::const_iterator end(Pimpl.m_Fragments.end()); unsigned int n = 0; for (cComplexRectImpl::RectList::const_iterator i = Pimpl.m_Fragments.begin(); i != end; ++i) { if (n == j) return *i; n++; } throw cNotFound(__FILE__, __LINE__, L"getFragment j out of range %d", j); } std::vector<cRect> QAPI cComplexRect::getFragments(void) const { const cComplexRectImpl & Pimpl = getReadImpl(*this); std::vector<cRect> Result; Result.resize(Pimpl.m_Fragments.size()); const cComplexRectImpl::RectList::const_iterator end(Pimpl.m_Fragments.end()); unsigned int n = 0; for (cComplexRectImpl::RectList::const_iterator i = Pimpl.m_Fragments.begin(); i != end; ++i) { Result.at(n++) = *i; } return Result; }
[ "drjwcain@gmail.com" ]
drjwcain@gmail.com
44ddba0b6e845c3d895f2c914d229c731fa15ff9
b53f734bc5c2259697988f98799745b6a8773996
/juez4.cpp
579c0ce737f963f86a42609d1da8490e5903cdad
[]
no_license
Maitgon/juez-dial
ba997dd8200f43d76c2117656fda39752a19bb84
001fcae00dc74b696ee40f05617da529df12b650
refs/heads/master
2023-01-23T20:17:10.434702
2020-12-08T11:49:23
2020-12-08T11:49:23
243,126,549
0
0
null
null
null
null
UTF-8
C++
false
false
1,228
cpp
#include <iostream> #include <vector> using namespace std; #define pb push_back /* Precondicion: A = vec[0..N] (N > 0) y (N <= 10000) y (Para todo i : 0 <= i < N : -50 > vec[i] > 60) */ vector<int> solucion (vector<int> vec){ int n_picos = 0; int n_valles = 0; int size = vec.size(); if (size > 2){ for (int i = 1; i < size - 1; i++){ if ((vec[i-1] < vec[i]) && (vec[i] > vec[i+1])){ n_picos++; } if ((vec[i-1] > vec[i]) && (vec[i] < vec[i+1])){ n_valles++; } } } vector<int> sol_vec (2); sol_vec[0] = n_picos; sol_vec[1] = n_valles; return sol_vec; } /* Postcondicion: B = ((sol_vec[0] = (#i : 1 <= i < N-1 : (vec[i-1] < vec[i]) y (vec[i] > vec[i+1]))) y (sol_vec[1] = (#i : 1 <= i < N-1 : (vec[i-1] > vec[i]) y (vec[i] < vec[i+1])))) */ void resuelveCaso() { int num; cin >> num; vector<int> vec; for (int i = 0; i < num; i++){ int elem; cin >> elem; vec.pb(elem); } vector<int> sol; sol = solucion(vec); cout << sol[0] << " " << sol[1] << endl; } int main() { int numCasos; std::cin >> numCasos; for (int i = 0; i < numCasos; ++i) resuelveCaso(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
2b3da6eb63c3ab5d9e25f32abc7e03176d15eb99
1c0ac60b81e88f034e154a3a75f4ee4f5f2c96e7
/client/project/include/gamefield.hpp
c8ea603752289ee044f91f225b72107de65b5261
[]
no_license
Adeksi/scav
db3abddfbc90805b69dfa46ceef9c34ba04ef634
95b4ce8f7624dc61297a26a84afffba36d232cd4
refs/heads/master
2021-02-15T13:48:13.563189
2018-05-19T15:45:20
2018-05-19T15:45:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,099
hpp
#ifndef SCAV_GAMEFIELD_HPP_ #define SCAV_GAMEFIELD_HPP_ #include "game_object.hpp" #include <mutex> #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> #include <SFML/System.hpp> #include <SFML/Network.hpp> #include "physics_object.hpp" #include "textures.hpp" #include "map_constructor.hpp" #include "menu.hpp" #include "animation.hpp" #include "cursor.hpp" #include "inventor.hpp" #include <map> #include <list> #include <ctime> using namespace sf; class GameField { private: float size; b2World* world; Textures* t_cont; MapConst g_map; Interface interface; Cursor g_curs; Inventor inv; bool start; float border_pos; bool pause; int winner; Player* player; RenderWindow window; View g_cam; TempContainer tmp_a_cont; RectangleShape field_border; StaticObject* borders[4]; std::map<int, Player*> players; std::map<int, PhysicsObject*> objects; bool was_shot; std::list<DrawableBullet*> bullets; std::mutex mtx; std::mutex render_mtx; int last_shot; void draw_border(float x, float y); void show_message(const std::string& msg); void check_key(); void draw(); void inventor_interact(); public: GameField(Textures* txt); ~GameField(); b2World* get_physics_world(); void set_player(int player_id); bool get_action(sf::Packet& packet); void shoot(); bool render(); MapConst& get_map(); std::mutex& get_mutex(); Player* get_player(); Player* find_player(int obj_id); int add_player(Player* obj, int new_id); void delete_player(int cl_id); void delete_all(); void set_winner(int w); void resume(); Inventor* get_inventor(); int add_object(PhysicsObject* obj, int new_id); void set_start(bool _s); bool get_start(); void delete_object(int id); PhysicsObject* get_object(int id); int add_bullet(DrawableBullet* obj); void delete_bullet(DrawableBullet* b); void move_border(float secs); RenderWindow* get_window(); }; #endif // SCAV_GAME_OBJECT_HPP_
[ "ukhachev.v.s@gmail.com" ]
ukhachev.v.s@gmail.com
ec843a0f180a362fcf57d17ce81a5578e03f9b3d
d6397839af09cf7a183a985204c7c4f84a836133
/src/Community_Tab.cpp
5d2f1dbf57e14b0466b8e8f242e6ae1406614e72
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
LCWilliams/UnrealatedLauncher
88264e5ff27201154585b3f4ce77ec900b89e635
07708422a4a28cc67978375ff73b9165f5c2ed70
refs/heads/master
2023-04-08T23:34:02.765019
2021-04-22T00:04:59
2021-04-22T00:04:59
110,151,546
0
0
null
null
null
null
UTF-8
C++
false
false
338
cpp
#include <headers/LauncherMainPages.h> using namespace UnrealatedLauncher; Launcher_CommunityTab::Launcher_CommunityTab(){ // Tab Grid settings: set_row_homogeneous(false); set_column_homogeneous(false); } // END - Community Tab Constructor. Launcher_CommunityTab::~Launcher_CommunityTab(){ } // END - Community Tab Destructor.
[ "LCWilliams_services@gmx.co.uk" ]
LCWilliams_services@gmx.co.uk
c1106be0dfe04fb901e8d6e98747ed79ae965290
8f64603c20b71dfdaf87eadac7156428a92cbfb5
/utk/io/io.cpp
ccd7ff6d1b7e99c22964aeb2ed179c92ab38098b
[]
no_license
urp/urban-robots
b46a50bbac6abc60a15c3bafff97a422b29671ad
fbd97f59c44d8f578fdf9507eb888163f816c850
refs/heads/master
2020-05-17T19:36:50.309048
2013-05-23T14:08:47
2013-05-23T14:08:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
820
cpp
//io.hpp //Copyright (C) 2006-2012 Peter Urban (peter.urban@s2003.tu-chemnitz.de) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either version 2 //of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # include "utk/io/io.hpp"
[ "urp@pks.mpg.de" ]
urp@pks.mpg.de
2c4f1913b5c624449e195e336cb897a0c73dc76e
9debf45ae60f98a4aa88ec79ad8492c2973463db
/Source/SOrb/Basic/Helpers/SoPlatformHelper.h
a38a5593ee4371dbb662abc3c047ddf96aa725e7
[ "MIT" ]
permissive
Jusedawg/WarriOrb
55643eed78c84ba84993b42c22ecada90515c893
7c20320484957e1a7fe0c09ab520967849ba65f1
refs/heads/master
2023-05-11T21:07:01.523893
2021-05-29T10:15:29
2021-05-29T10:15:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,890
h
// Copyright (c) Csaba Molnar & Daniel Butum. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "Camera/CameraTypes.h" #include "SoPlatformHelper.generated.h" struct FDisplayMetrics; struct FSoDisplayResolution; class FAudioDevice; class FWindowsApplication; class IOnlineSubsystem; enum class ESoInputDeviceType : uint8; class UForceFeedbackEffect; class UCameraShake; // Information about the current engine version USTRUCT(BlueprintType) struct FSoEngineInfo { GENERATED_USTRUCT_BODY() public: FString ToString() const; public: /** The depot name, indicate where the executables and symbols are stored. */ UPROPERTY(BlueprintReadOnly) FString DepotName; /** Product version, based on FEngineVersion. */ UPROPERTY(BlueprintReadOnly) FString EngineVersion; }; // Information about the current OS USTRUCT(BlueprintType) struct FSoOperatingSystemInfo { GENERATED_USTRUCT_BODY() public: FString ToString() const; public: UPROPERTY(BlueprintReadOnly) FString OSMajor; UPROPERTY(BlueprintReadOnly) FString OSMinor; UPROPERTY(BlueprintReadOnly) FString OSVersion; UPROPERTY(BlueprintReadOnly) bool bIs64Bits = false; }; // Information about the current CPU USTRUCT(BlueprintType) struct FSoCPUInfo { GENERATED_USTRUCT_BODY() public: FString ToString() const; public: // Does not include hyper threading UPROPERTY(BlueprintReadOnly) int32 CPUPhysicalCores = 0; // Includes hyper threading UPROPERTY(BlueprintReadOnly) int32 CPULogicalCores = 0; UPROPERTY(BlueprintReadOnly) FString CPUVendor; UPROPERTY(BlueprintReadOnly) FString CPUBrand; /** * On x86(-64) platforms, uses cpuid instruction to get the CPU signature * * Bits 0-3 Stepping ID * Bits 4-7 Model * Bits 8-11 Family * Bits 12-13 Processor type (Intel) / Reserved (AMD) * Bits 14-15 Reserved * Bits 16-19 Extended model * Bits 20-27 Extended family * Bits 28-31 Reserved */ uint32 CPUInfo = 0; }; // Information about the current CPU USTRUCT(BlueprintType) struct FSoGPUInfo { GENERATED_USTRUCT_BODY() public: FString ToString() const; public: // DirectX VendorId, 0 if not set uint32 GPUVendorID = 0; uint32 GPUDeviceID = 0; uint32 GPUDeviceRevision = 0; // e.g. "NVIDIA GeForce GTX 680" or "AMD Radeon R9 200 / HD 7900 Series" UPROPERTY(BlueprintReadOnly) FString DesktopGPUAdapter; // e.g. "NVIDIA GeForce GTX 680" or "AMD Radeon R9 200 / HD 7900 Series" UPROPERTY(BlueprintReadOnly) FString RenderingGPUAdapter; // e.g. "15.200.1062.1004"(AMD) // e.g. "9.18.13.4788"(NVIDIA) first number is Windows version (e.g. 7:Vista, 6:XP, 4:Me, 9:Win8(1), 10:Win7), last 5 have the UserDriver version encoded // also called technical version number (https://wiki.mozilla.org/Blocklisting/Blocked_Graphics_Drivers) UPROPERTY(BlueprintReadOnly) FString AdapterInternalDriverVersion; // e.g. "Catalyst 15.7.1"(AMD) or "Crimson 15.7.1"(AMD) or "347.88"(NVIDIA) // also called commercial version number (https://wiki.mozilla.org/Blocklisting/Blocked_Graphics_Drivers) UPROPERTY(BlueprintReadOnly) FString AdapterUserDriverVersion; // e.g. 3-13-2015 UPROPERTY(BlueprintReadOnly) FString AdapterDriverDate; }; // Information about the RAM and GPU memory USTRUCT(BlueprintType) struct FSoPlatformMemoryInfo { GENERATED_USTRUCT_BODY() public: FString ToString() const; public: /** The amount of physical memory currently available, in MegaBytes. */ double RAMAvailablePhysicalMB = 0.f; /** The amount of virtual memory currently available, in MegaBytes. */ double RAMAvailableVirtualMB = 0.f; /** The amount of physical memory used by the process, in MegaBytes. */ double RAMUsedPhysicalMB = 0.f; /** The peak amount of physical memory used by the process, in MegaBytes. */ double RAMPeakUsedPhysicalMB = 0.f; /** Total amount of virtual memory used by the process, in MegaBytes. */ double RAMUsedVirtualMB = 0.f; /** The peak amount of virtual memory used by the process, in MegaBytes. */ double RAMPeakUsedVirtualMB = 0.f; /** Amount of memory allocated by textures. In MegaBytes. */ double GPUTextureMemoryMB = 0.f; /** Amount of memory allocated by rendertargets. In MegaBytes. */ double GPURenderTargetMemoryMB = 0.f; /** In percent. If non-zero, the texture pool size is a percentage of GTotalGraphicsMemory. */ UPROPERTY(BlueprintReadOnly) int32 GPUPoolSizeVRAMPercentage = 0; }; // Corresponds to the one in XboxOneMisc.h UENUM(BlueprintType) enum class ESoXboxOneConsoleType : uint8 { Invalid, XboxOne UMETA(DisplayName = "Xbox One"), XboxOneS UMETA(DisplayName = "Xbox One S"), XboxOneX UMETA(DisplayName = "Xbox One X (Scorpio)") }; UENUM(BlueprintType) enum class ESoGamepadLayoutType : uint8 { Xbox = 0 UMETA(DisplayName = "Xbox"), PlayStation UMETA(DisplayName = "PlayStation"), Switch UMETA(DisplayName = "Nintendo Switch"), Num UMETA(Hidden) }; UCLASS() class SORB_API USoPlatformHelper : public UBlueprintFunctionLibrary { GENERATED_BODY() public: // Prints error to all outputs possible static void PrintErrorToAll(const UObject* WorldContextObject, const FString& Message); static void PrintToAll(const UObject* WorldContextObject, const FString& Message); // Prints the message to the developer console static void PrintToConsole(const UObject* WorldContextObject, const FString& Message); // Prints the message to the screen for TimeToDisplaySeconds static void PrintToScreen(const FString& Message, float TimeToDisplaySeconds = 5.f, FColor DisplayColor = FColor::White); // Safer version of LaunchURL // Opens the specified URL in the platform's web browser of choice UFUNCTION(BlueprintCallable, Category = ">Platform") static bool LaunchURL(const FString& URL, bool bCopyURLToClipboard = true); // Safe version of ExploreFolder UFUNCTION(BlueprintCallable, Category = ">Platform") static bool ExploreFolder(const FString& FolderPath); // By default in non shipping and non editor builds GC verify is on // https://answers.unrealengine.com/questions/177892/game-hitches-gc-mark-time.html // We disable it by default if no command line flags are given static void DisableVerifyGC(bool bCheckForCommandLineOverrides = true); // // Disables/Enables all AI Logging // determines whether AI logging should be processed or not // static void SetIsAILoggingEnabled(bool bEnabled, bool bCheckForCommandLineOverrides); static void DisableAILogging(bool bCheckForCommandLineOverrides = true) { SetIsAILoggingEnabled(false, bCheckForCommandLineOverrides); } static void EnableAILogging(bool bCheckForCommandLineOverrides = true) { SetIsAILoggingEnabled(true, bCheckForCommandLineOverrides); } // // Disables/Enables all screen messages // static void SetAreScreenMessagesEnabled(bool bEnabled, bool bCheckForCommandLineOverrides); static void DisableScreenMessages(bool bCheckForCommandLineOverrides = true) { SetAreScreenMessagesEnabled(false, bCheckForCommandLineOverrides); } static void EnableScreenMessages(bool bCheckForCommandLineOverrides = true) { SetAreScreenMessagesEnabled(true, bCheckForCommandLineOverrides); } // // Disables/Enables Mouse support // static void SetIsMouseEnabled(const UObject* WorldContextObject, bool bEnabled); static void SetIsMouseAllowed(const UObject* WorldContextObject, bool bAllowed); UFUNCTION(BlueprintPure, Category = ">Mouse", meta = (WorldContext = "WorldContextObject")) static bool IsMouseAllowed(const UObject* WorldContextObject); UFUNCTION(BlueprintCallable, Category = ">Mouse", meta = (WorldContext = "WorldContextObject")) static void DisallowMouse(const UObject* WorldContextObject) { SetIsMouseAllowed(WorldContextObject, false); } UFUNCTION(BlueprintCallable, Category = ">Mouse", meta = (WorldContext = "WorldContextObject")) static void AllowMouse(const UObject* WorldContextObject) { SetIsMouseAllowed(WorldContextObject, true); } // // Screen/Game // // Moves the game window to the default screen of the user static void MoveGameToDefaultMonitor(); /** * Gets the list of support fullscreen resolutions. * @return true if successfully queried the device for available resolutions. */ static bool GetSupportedFullscreenResolutions(TArray<FSoDisplayResolution>& OutResolutions); /** * Gets the list of windowed resolutions which are convenient for the current primary display size. * @return true if successfully queried the device for available resolutions. */ static bool GetConvenientWindowedResolutions(TArray<FSoDisplayResolution>& OutResolutions); // Gets the refresh of all the displays as a set of ints static bool GetDisplaysRefreshRates(TSet<int32>& OutRefreshRates); // Gets info about all the displays static bool GetDisplaysMetrics(FDisplayMetrics& OutDisplayMetrics); /** Gets the AudioDevice from the world if it supports audio and it has an audio device. */ static FAudioDevice* GetAudioDevice(const UObject* WorldContextObject); /** * Creates the folders for this FolderPath. * Can be a RootDirectory/Directory or RootDirectory/Directory/Somefile.txt * in Both cases it will create the RootDirectory/Directory path */ static bool CreateDirectoryRecursively(const FString& FolderPath); // What it says, quits the game static void QuitGame(const UObject* WorldContextObject = nullptr); // Is the game in background? static bool IsGameInBackground(UObject* WorldContextObject = nullptr) { return !IsGameInForeground(WorldContextObject); } // Is the game in foreground, aka focused static bool IsGameInForeground(UObject* WorldContextObject = nullptr); // Sets the pause state of the game static bool SetGamePaused(const UObject* WorldContextObject, bool bPaused); // Returns the game's paused state static bool IsGamePaused(const UObject* WorldContextObject); // Sets the global time dilation static void SetGlobalTimeDilation(const UObject* WorldContextObject, float TimeDilation); // Gets the global time dilation static float GetGlobalTimeDilation(const UObject* WorldContextObject); // Are all game windows hidden? static bool AreAllGameWindowsHidden(); // Gets the Unreal Engine version information static const FSoEngineInfo& GetUnrealEngineInfo(); // Gets information about the operating system static FSoOperatingSystemInfo GetOperatingSystemInfo(); // // Platform // // Helper method, to get all the info about the game that is not character related static FString ToStringPlatformContext(); // Your GPU sucks static void WarnIfGPUIsBlacklisted(); // Gets information about the CPU static FSoCPUInfo GetCPUInfo(); // Gets information about the CPU static FSoGPUInfo GetGPUInfo(); // Gets information about the memory static FSoPlatformMemoryInfo GetMemoryInfo(); // Gets whether user settings should override the resolution or not static bool HasFixedResolution(); // Gets whether user settings should override the VSync or not // Usually only true in editor and consoles (xbox, ps4, switch) static bool HasFixedVSync(); // Gets whether this platform supports windowed mode rendering. static bool SupportsWindowedMode(); // Whether the platform allows an application to quit to the OS // Apparently only false on Switch static bool SupportsQuit(); // Returns the root of the packaged game static FString GetGameRootPath(); /** * Returns the string name of the current platform, to perform different behavior based on platform. * (Platform names include Windows, Mac, IOS, Android, PS4, Switch, XboxOne, HTML5, Linux) */ static FString GetPlatformName(); // The platform has shit hardware UFUNCTION(BlueprintPure, Category = ">Platform", DisplayName = "Does Platform Has Weak Hardware") static bool HasWeakHardware(); // Some consoles has fixed static bool HasFixedWeakHardware() { return IsSwitch() || IsXboxOneConsoleType() || IsXboxOneSConsoleType(); } UFUNCTION(BlueprintPure, Category = ">Platform", DisplayName = "Is Platform Switch") static bool IsSwitch() { return PLATFORM_SWITCH; } UFUNCTION(BlueprintPure, Category = ">Platform", DisplayName = "Is Platform Xbox One") static bool IsXboxOne() { return PLATFORM_XBOXONE; } UFUNCTION(BlueprintPure, Category = ">Platform", DisplayName = "Is Platform Xbox One && Console == Xbox One") static bool IsXboxOneConsoleType() { return GetXboxOneConsoleType() == ESoXboxOneConsoleType::XboxOne; } UFUNCTION(BlueprintPure, Category = ">Platform", DisplayName = "Is Platform Xbox One && Console == Xbox One S") static bool IsXboxOneSConsoleType() { return GetXboxOneConsoleType() == ESoXboxOneConsoleType::XboxOneS; } UFUNCTION(BlueprintPure, Category = ">Platform", DisplayName = "Is Platform Xbox One && Console == Xbox One X") static bool IsXboxOneXConsoleType() { return GetXboxOneConsoleType() == ESoXboxOneConsoleType::XboxOneX; } UFUNCTION(BlueprintPure, Category = ">Platform") static ESoXboxOneConsoleType GetXboxOneConsoleType(); UFUNCTION(BlueprintPure, Category = ">Platform", DisplayName = "Is Platform Linux") static bool IsLinux() { return PLATFORM_LINUX; } UFUNCTION(BlueprintPure, Category = ">Platform", DisplayName = "Is Platform Windows") static bool IsWindows() { return PLATFORM_WINDOWS; } UFUNCTION(BlueprintPure, Category = ">Platform", DisplayName = "Is Platform Mac") static bool IsMac() { return PLATFORM_MAC; } // // Build // // Helper method to get the string of some compiled options like WITH_EDITOr and such, WITH_STATS static const FString& ToStringCompileFlags(); // Gets the build version of this game (Warriorb) duh. UFUNCTION(BlueprintPure, Category = ">Build") static const FString& GetGameBuildVersion(); // Gets git branch UFUNCTION(BlueprintPure, Category = ">Build") static const FString& GetGameBuildBranch(); // Gets git commit hash UFUNCTION(BlueprintPure, Category = ">Build") static const FString& GetGameBuildCommit(); // Format: BuildVersion - BuildCommit BuildBanch UFUNCTION(BlueprintPure, Category = ">Build") static FString GetGameBuildAll(); UFUNCTION(BlueprintPure, Category = ">Build") static bool IsDemo() { return WARRIORB_DEMO; } // The opposite of IsDemo UFUNCTION(BlueprintPure, Category = ">Build") static bool IsNormalGame() { return !IsDemo(); } // // Steam // UFUNCTION(BlueprintPure, Category = ">Build") static bool IsWithSteam() { return WARRIORB_WITH_STEAM; } static bool InitializedSteam(); // NOTE: this returns a string in the format specified here https://partner.steamgames.com/doc/store/localization#8 static FString GetSteamCurrentGameLanguage(); // Queries current app static FString GetCurrentSteamAppID(); UFUNCTION(BlueprintPure, Category = ">Steam") static int32 GetSteamAppID(bool bDemo) { return bDemo ? WARRIORB_STEAM_DEMO_APP_ID : WARRIORB_STEAM_APP_ID; } static bool IsSteamInitialized(); static bool OpenSteamOverlayToStore(uint32 AppID, bool bAddToCart = false, bool bShowCart = false); // Seems kinda stupid because if you have the controller connected and you launch the game from the NON big // picture interface this will still report as true static bool IsSteamBigPicture(); // NOTE: only works on windows and if the check is enabled UFUNCTION(BlueprintPure, Category = ">Steam") static bool IsSteamBuildPirated(); // // Discord // static int64 GetDiscordClientID(bool bDemo) { return bDemo ? WARRIORB_DISCORD_DEMO_CLIENT_ID : WARRIORB_DISCORD_CLIENT_ID; } // // Assets // UFUNCTION(Exec) static void PrintAllAssets(); UFUNCTION(Exec) static void PrintAllAssetsMaps(); // // Keyboard // UFUNCTION(BlueprintPure, Category = ">AuraSDK") static bool UseAsusAuraSDK() { return PLATFORM_WINDOWS && WARRIORB_USE_ASUS_AURA_SDK; } // // Camera // /** * Play Camera Shake * @param Shake - Camera shake animation to play * @param Scale - Scalar defining how "intense" to play the anim * @param PlaySpace - Which coordinate system to play the shake in (used for CameraAnims within the shake). * @param UserPlaySpaceRot - Matrix used when PlaySpace = CAPS_UserDefined */ UFUNCTION(BlueprintCallable, Category=">Camera", meta = (WorldContext = "WorldContextObject")) static void PlayCameraShake( const UObject* WorldContextObject, TSubclassOf<UCameraShake> Shake, float Scale = 1.f, ECameraAnimPlaySpace::Type PlaySpace = ECameraAnimPlaySpace::CameraLocal, FRotator UserPlaySpaceRot = FRotator::ZeroRotator ); // // Gamepad // static bool IsAnyGamepadConnected() { return NumGamepads() > 0; } static FString GetFirstGamepadName(); static FString GetGamepadName(int32 JoystickIndex); static ESoGamepadLayoutType GetGamepadLayoutTypeFromName(const FString& GamepadName); static FString GamepadLayoutToString(ESoGamepadLayoutType Layout); static bool IsJoystickIndexAGamepad(int32 JoystickIndex); static int32 NumGamepads(); // Does the current platform has a hard coded game controller static bool HasHardcodedGamepad() { return PLATFORM_XBOXONE || PLATFORM_SWITCH || PLATFORM_PS4; } // Get the hard coded game controller type static ESoInputDeviceType GetHardcodedGamepadType(); // Should we use the UI for console? UFUNCTION(BlueprintPure, Category = ">Platform") static bool IsConsole() { return PLATFORM_XBOXONE || PLATFORM_SWITCH || PLATFORM_PS4 || WARRIORB_CONSOLE_TEST; } UFUNCTION(BlueprintPure, Category = ">Platform") static bool CanHaveKeyboard() { if (WARRIORB_NO_KEYBOARD_TEST) return false; return PLATFORM_DESKTOP || PLATFORM_XBOXONE; } // // Gamepad force feedback (aka vibration) // /** * Play a force feedback pattern on the player's controller * @param ForceFeedbackEffect The force feedback pattern to play * @param bLooping Whether the pattern should be played repeatedly or be a single one shot * @param bIgnoreTimeDilation Whether the pattern should ignore time dilation * @param bPlayWhilePaused Whether the pattern should continue to play while the game is paused * @param Tag A tag that allows stopping of an effect. If another effect with this Tag is playing, it will be stopped and replaced */ UFUNCTION(BlueprintCallable, Category = ">Gamepad|ForceFeedback", meta = (WorldContext = "WorldContextObject")) static void PlayForceFeedback( const UObject* WorldContextObject, UForceFeedbackEffect* ForceFeedbackEffect, FName Tag = NAME_None, bool bLooping = false, bool bIgnoreTimeDilation = false, bool bPlayWhilePaused = false ); static void SetForceFeedbackScale(const UObject* WorldContextObject, float NewValue); static float GetForceFeedbackScale(const UObject* WorldContextObject); // // Display Gamma // static void SetDisplayGamma(float NewGamma); static float GetDisplayGamma(); // // OS specific // #if PLATFORM_WINDOWS static TSharedPtr<FWindowsApplication> GetWindowsApplication(); #endif };
[ "danibutum@gmail.com" ]
danibutum@gmail.com
323b6fa06257744ca9c9bdfbd63eb87683f0dc88
fa5750449293d2cf330dd57ecddaf9fbd64119a2
/templates/higher_order_function intro.cpp
e2507b21433e9aa31392701399ea3508c893d6b4
[]
no_license
TutoRepos/cookbook-c-cpp
397831848c4d740cc69656267ad97898f4f099b4
ea506038e4b001432677df7c92abc71a87030e21
refs/heads/master
2022-03-25T07:37:38.107288
2019-12-28T13:01:47
2019-12-28T13:01:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,074
cpp
#include <iostream> #include <vector> #include <string> #include <chrono> std::vector<int> vi{ 1,2,3,4,5 }; std::vector<std::string> vs{ "ja", "ty", "my", "vy" }; template<typename T> void print_without_ened_coma(const std::vector<T>& v) { if (std::empty(v)) { return; } std::cout << *v.begin(); //printing for (auto it = std::next(v.begin()); it != v.end(); ++it) { std::cout << ", ", //separating std::cout << *it; //separating } } template<typename T> void print(const std::vector<T>& v) { for (auto i : v) std::cout << i << ", "; } // making it more generalized with this template // this will abstract out the control flow logic // it is reusable template<typename Range, typename Printing, typename Separating> void make_separated(Range&& range, Printing&& print, Separating&& separate) { if (std::empty(range)) { return; } print(*range.begin()); for (auto it = std::next(range.begin()); it != range.end(); ++it) { separate(); print(*it); } } //and now i can overload and use template<typename T> void new_print(const std::vector<T>& v) { make_separated(v, [](const auto& x) {std::cout << x; }, []() {std::cout << ", "; }); } void new_print(const std::string& s) { make_separated(s, [](const auto& x) {std::cout << x; }, []() {std::cout << ", "; }); } template<typename T> void new_print(std::initializer_list<T> ilist) { make_separated(ilist, [](const auto& x) {std::cout << x; }, []() {std::cout << ", "; }); } /*simple benchamrk as HOF*/ template<typename T> auto benchmark(T&& func) { const auto t = std::chrono::high_resolution_clock::now(); func(); return std::chrono::high_resolution_clock::now() - t; } int main() { //print(vi); //print_without_ened_coma(vi); //new_print({ 2134,2414,5345,63245,53 }); //new_print({ "dsad", "sdsada", "sdsada", "sdada", "sdsa" }); //new_print(vi); //new_print(vs); std::chrono::duration<double> x = benchmark([]() {std::cout << "hello\n"; }); std::cout << x.count(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
b2bb4457f262d808ce6ce3eca58fbc1b29ea9761
219892e4c63c991978c45184285fd57683c74bb4
/missionariesandcannibals/missionaries.cpp
1dc7599e967fd10d58bb84793267434b41fdc97b
[]
no_license
TristanOM/missionary_cannibal_problem
432f701abd8ffecbd08fb07270f3ac8839b79313
0974ed07ccf842b3728a1d212738f197be2ce53c
refs/heads/master
2021-01-10T15:14:38.267561
2016-02-23T02:35:21
2016-02-23T02:35:21
52,323,858
0
0
null
null
null
null
UTF-8
C++
false
false
387
cpp
//Missionaries and Cannibals problem //Tristan Oliver-Mallory #include <iostream> using namespace std; int main() { //The left side of the array represents the number of missionaries and right represent number of cannibals int rightSide [2] = {3,3};//This is the starting side int leftSide [2] = {0,0};//this is the finishing side int boat [2] = {0,0};//this is the boat }
[ "tristanolivermall212@pointloma.edu" ]
tristanolivermall212@pointloma.edu
0e14eb224252de6bc5dcff0625c70f7b4085a95f
5e3a3085d8e064edf92351d21f749ace121d4179
/BankKataLib/Transazione.cpp
c3e0f2499e7a28aaaf141825d8ffd93b5e93c616
[]
no_license
yuroller/BankKataApp
18beee7d07927ff9c87311b9bee4a3982407b71f
bb0cf791e132c5742566994cd0231e622b519286
refs/heads/master
2020-03-11T20:23:08.875419
2018-04-15T15:16:33
2018-04-15T15:16:33
130,234,904
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include "stdafx.h" #include "Transazione.h" #include <ostream> std::ostream& operator<<(std::ostream& os, const Transazione& tr) { return os << "Transazione[" << tr.importo_ << ',' << tr.data_ << ']'; }
[ "yv@3cx.com" ]
yv@3cx.com
9a2a39d2342d44b0cc599dffeb606efbda1e6d10
6da5fdc518b7e7a8992fa4b663164bfb3bdcb9b6
/centaur/servos/gritlegfirmware/gritlegfirmware.ino
ac7131382d1058adc43380e25881c44441809476
[]
no_license
wmacevoy/grit
8042bab120604ca25dcf61764442b36b7545b546
a8dfa9114debd09afba2b6199c2766f1349f6d32
refs/heads/master
2020-12-26T21:38:33.825695
2016-02-14T00:45:05
2016-02-14T00:45:05
23,447,543
1
0
null
null
null
null
UTF-8
C++
false
false
4,813
ino
#include <EEPROM.h> #include <Servo.h> #include <Wire.h> const int ServoPin=3; byte goal=0; byte current=0; Servo talon; const int STARTADDRESS=0; class Settings { public: short low; short high; byte address; byte speed; void writeMemory() { byte *ptr=(byte *)this; for (int i=0;i<sizeof(Settings);i++){ EEPROM.write(STARTADDRESS+i,ptr[i]); } } void readMemory() { byte *ptr=(byte *)this; for (int i=0;i<sizeof(Settings);i++){ ptr[i]=EEPROM.read(STARTADDRESS+i); } } void show() { Serial.println("Settings"); Serial.print("low: "); Serial.println(low); Serial.print("high: "); Serial.println(high); Serial.print("address: "); Serial.println(address); Serial.print("speed: "); Serial.println(speed); } }; Settings settings; void showMenu() { Serial.println("c, s,l,h,a,w,g,m, and p"); Serial.println("c calibrate talon"); Serial.println("s show sensor values"); Serial.println("l low position 0 degrees [0 to 1023]"); Serial.println("h high position 180 degrees [0 to 1023]"); Serial.println("a I^C address [0 to 127]"); Serial.println("w write settings to EEProm"); Serial.println("g goto to position [0 to 180]"); Serial.println("m speed [0 to 255]"); Serial.println("p print current values"); } void handleUI(char c) { if (c=='c' || c=='C') { Serial.println("Press Calibrate Button"); delay(1000); Serial.println("Min"); talon.writeMicroseconds(1000); delay(1000); Serial.println("Max"); talon.writeMicroseconds(2000); delay(1000); Serial.println("Center"); talon.writeMicroseconds(1500); delay(1000); Serial.println("Complete/Release button"); } else if (c=='s' || c=='S') { Serial.print("Sensor 0:"); Serial.println(analogRead(0)); } else if (c=='l' || c=='L') { int value=Serial.parseInt(); if (value>=0 && value<=1023) { Serial.println("Ok"); settings.low=value; } else { Serial.println("Invalid Low Value"); } } else if (c=='h' || c=='H') { int value=Serial.parseInt(); if (value>=0 && value<=1023) { Serial.println("Ok"); settings.high=value; } else { Serial.println("Invalid High Value"); } } else if (c=='m' || c=='M') { int value=Serial.parseInt(); if (value>=0 && value<=255) { Serial.println("Ok"); settings.speed=value; } else { Serial.println("Invalid High Value"); } } else if (c=='a' || c=='A') { int newAddress=Serial.parseInt(); if (newAddress>0 && newAddress<=127) { Serial.println("Ok"); settings.address=newAddress; } else { Serial.println("Invalid Address"); } } else if (c=='w' || c=='W') { Serial.println("Ok"); settings.writeMemory(); } else if (c=='g' || c=='G') { int newGoal=Serial.parseInt(); if (newGoal>=0 && newGoal<=180) { Serial.println("Ok"); goal=newGoal; } else { Serial.println("Invalid Goal Position"); } } else if (c=='p' || c=='P') { settings.show(); Serial.print("Goal: "); Serial.println(goal); } } void forward() { int time=map(settings.speed,0,255,1500,1000); talon.writeMicroseconds(time); } void reverse() { int time=map(settings.speed,0,255,1500,2000); talon.writeMicroseconds(time); } void softStop() { // No Braking talon.writeMicroseconds(1500); } void receiveEvent(int howMany) { int newGoal=goal; int newSpeed=settings.speed; while (!Wire.available()); if (Wire.available()>0) { newGoal=Wire.read(); } if (newGoal>=0 && newGoal<=180) { goal=newGoal; } while (!Wire.available()); if (Wire.available()>0) { newSpeed=Wire.read(); } if (newSpeed>=0 && newSpeed<=255) { settings.speed=newSpeed; } } void requestEvent() { Wire.write(goal); Wire.write(current); Wire.write(settings.speed); } void getCurrent() { current=map(analogRead(0),settings.low,settings.high,0,180); } void setup() { talon.attach(ServoPin); softStop(); settings.readMemory(); Wire.begin(settings.address); Wire.onReceive(receiveEvent); Wire.onRequest(requestEvent); Serial.begin(9600); getCurrent(); int value=analogRead(0); if (current>180 || current<0) { if (abs(value-settings.low)>abs(value-settings.high)) current=180; else current=0; } goal=current; showMenu(); } void loop() { int dd=(abs(settings.low-settings.high)*7)/100; if (dd==0) dd=1; int joint=analogRead(0); getCurrent(); int goalPosition=map(goal,0,180,settings.low,settings.high); // Serial.println(goalPosition); if (abs(joint-goalPosition)<dd) { softStop(); } else if(joint > goalPosition) { reverse(); } else { forward(); } if (Serial.available()) { handleUI(Serial.read()); } }
[ "wmacevoy@gmail.com" ]
wmacevoy@gmail.com
1c9b39ee3950d0e2289b979769ba0a7b764a2e3f
b168b1d82fef2d8787ee6cd2bf51c7cfccb132f9
/etrobo_tr/app/LineTracer.h
7707602a78e697f2a12cc6db50f9026a4c632c5b
[]
no_license
y20510/ETRobo_IIT2021
348e92b4d88136ff76a4a36f460e17bf3fcf2b47
a682df3217d3a40d7cc70cdf892025502ba3883e
refs/heads/main
2023-07-28T05:40:06.038352
2021-09-07T05:28:59
2021-09-07T05:28:59
381,236,454
0
1
null
null
null
null
UTF-8
C++
false
false
1,078
h
/****************************************************************************** * LineTracer.h (for LEGO Mindstorms EV3) * Created on: 2015/01/25 * Definition of the Class LineTracer * Author: Kazuhiro Kawachi * Copyright (c) 2015 Embedded Technology Software Design Robot Contest *****************************************************************************/ #ifndef EV3_APP_LINETRACER_H_ #define EV3_APP_LINETRACER_H_ #include "LineMonitor.h" #include "Walker.h" #include "TouchMonitor.h" #include "ArmMove.h" class LineTracer { public: LineTracer(LineMonitor *lineMonitor, Walker *walker, TouchMonitor *touchMonitor, ArmMove *armMove); void run(); bool isFinish(); private: LineMonitor *mLineMonitor; Walker *mWalker; bool mIsInitialized; TouchMonitor *mTouchMonitor; ArmMove *mArmMove; float calc_prop_value(int nowBrightness); bool mStartButton; bool mTracerFinish = false; bool mArmSet; }; #endif // EV3_APP_LINETRACER_H_
[ "77314422+y20505@users.noreply.github.com" ]
77314422+y20505@users.noreply.github.com
0d3663d8be96ad44cdb20423452c920df1d54951
6d76e9ffba6dfb05c0a5a147c3bf256e685ab976
/CCCC天梯赛/c4天梯-练习/L3-010.cpp
b612a669839da38d3ce4330edd3c406f42941513
[]
no_license
Penn000/ACM
6383b901b9dd0399e663811ceb847c9e92bb57f0
1f2c89a8272379d9e52ab8827f41be142178ed30
refs/heads/master
2020-03-22T14:23:01.643633
2019-07-09T05:44:40
2019-07-09T05:44:40
140,175,176
2
0
null
null
null
null
UTF-8
C++
false
false
1,380
cpp
//2017-03-22 #include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; int ans[25]; struct node{ int data; node *lson, *rson; node(int d):data(d), lson(NULL), rson(NULL){} }; class BST { public: node *rt; BST():rt(NULL){} void insert(int a) { node* nd = new node(a); if(rt == NULL){ rt = nd; }else{ node *p = rt, *q = NULL; while(p != NULL){ q = p; if(a > p->data){ p = p->lson; }else{ p = p->rson; } } if(a > q->data)q->lson = nd; else q->rson = nd; } } void judge() { queue<node*> q; q.push(rt); node *tmp; bool fg = true; int cnt = 0; while(!q.empty()) { tmp = q.front(); q.pop(); ans[cnt++] = tmp->data; if(tmp->lson)q.push(tmp->lson); else{ if(tmp->rson){ fg = false; } if(!q.empty()){ if(q.front()->lson || q.front()->rson){ fg = false; } } } if(tmp->rson)q.push(tmp->rson); else{ if(!q.empty()){ if(q.front()->lson || q.front()->rson){ fg = false; } } } } for(int i = 0; i < cnt; i++) if(i == cnt-1)cout<<ans[i]<<endl; else cout<<ans[i]<<" "; if(fg)cout<<"YES"<<endl; else cout<<"NO"<<endl; } }; int main() { int n, a; while(cin>>n) { BST bst; for(int i = 0; i < n; i++) { cin>>a; bst.insert(a); } bst.judge(); } return 0; }
[ "593678620@qq.com" ]
593678620@qq.com