text
string
size
int64
token_count
int64
#include <QTextStream> int main(void) { QTextStream(stdout) << "Hello, console!" << endl; return 0; }
106
44
#include "Arduino.h" #include "fram.h" #include "Wire.h" void FRAMinit(){ Wire.begin(); } void FRAMwrite(uint16_t address, uint8_t data){ Wire.beginTransmission(pageAddress(address)); Wire.write(wordAddress(address)); Wire.write(data); Wire.endTransmission(true); } void FRAMwriteblock(uint16_t startAddress, uint8_t data[], uint16_t length){ Wire.beginTransmission(pageAddress(startAddress)); Wire.write(wordAddress(startAddress)); Wire.write(data, length); Wire.endTransmission(true); } uint8_t FRAMread(uint16_t address){ Wire.beginTransmission(pageAddress(address)); Wire.write(wordAddress(address)); Wire.endTransmission(false); Wire.requestFrom(pageAddress(address), 1); uint8_t data = Wire.read(); return data; } void FRAMreadblock(uint16_t startAddress, uint8_t buffer[], uint16_t number){ Wire.beginTransmission(pageAddress(startAddress)); Wire.write(wordAddress(startAddress)); Wire.endTransmission(false); Wire.requestFrom(pageAddress(startAddress), number); for(int i = 0; i < number; i++){ buffer[i] = Wire.read(); } } void FRAMpack(uint16_t address, void* data, uint8_t len){ Wire.beginTransmission(pageAddress(address)); Wire.write(wordAddress(address)); Wire.write((uint8_t*)data, len); Wire.endTransmission(true); } uint8_t FRAMunpack(uint16_t address, void* data, uint8_t len){ uint8_t rc; uint8_t *p = (uint8_t*)data; Wire.beginTransmission(pageAddress(address)); Wire.write(wordAddress(address)); Wire.endTransmission(false); Wire.requestFrom(pageAddress(address), len); for(rc = 0, p; rc < len ; rc++, p++){ *p = (uint8_t)Wire.read(); } return rc; } uint8_t pageAddress(uint16_t dataAddress){ uint8_t page = dataAddress >> 8; return (BASEADDR | page); } uint8_t wordAddress(uint16_t dataAddress){ return (dataAddress & 0b11111111); }
1,951
738
#include "flashstorage.h" #include "config.h" Adafruit_FlashTransport_QSPI flashTransport; Adafruit_SPIFlash flash(&flashTransport); FatFileSystem fatfs; Adafruit_USBD_MSC usb_msc; /* * General file access functions */ uint16_t read16(File &f) { uint16_t result; ((uint8_t *)&result)[0] = f.read(); // LSB ((uint8_t *)&result)[1] = f.read(); // MSB return result; } uint32_t read32(File &f) { uint32_t result; ((uint8_t *)&result)[0] = f.read(); // LSB ((uint8_t *)&result)[1] = f.read(); ((uint8_t *)&result)[2] = f.read(); ((uint8_t *)&result)[3] = f.read(); // MSB return result; } int readLine(File &f, char l[]){ int pos=0; char c; while (f.available()&&(pos<MAX_LINE_LENGTH)) { c=f.read();//read next character if (c=='\n') { l[pos]=NULL; //terminate string return pos; } if (pos<MAX_LINE_LENGTH) { l[pos++]=c;} } //if we are here and not yet exited, it means we reached end of file or end of buffer before meeting \n l[pos]=NULL; return pos; } /* * USB MASS STORAGE functions * */ //initializing mass storage object usb_msc // assumes that flash and fatfs have already been initilaized void msc_init(){ // Set disk vendor id, product id and revision with string up to 8, 16, 4 characters respectively usb_msc.setID("Adafruit", "External Flash", "1.0"); // Set callback usb_msc.setReadWriteCallback(msc_read_cb, msc_write_cb, msc_flush_cb); // Set disk size, block size should be 512 regardless of spi flash page size usb_msc.setCapacity(flash.size()/512, 512); // MSC is ready for read/write usb_msc.setUnitReady(true); usb_msc.begin(); } // Callback invoked when received READ10 command. // Copy disk's data to buffer (up to bufsize) and // return number of copied bytes (must be multiple of block size) int32_t msc_read_cb (uint32_t lba, void* buffer, uint32_t bufsize){ // Note: SPIFLash Bock API: readBlocks/writeBlocks/syncBlocks // already include 4K sector caching internally. We don't need to cache it, yahhhh!! return flash.readBlocks(lba, (uint8_t*) buffer, bufsize/512) ? bufsize : -1; } // Callback invoked when received WRITE10 command. // Process data in buffer to disk's storage and // return number of written bytes (must be multiple of block size) int32_t msc_write_cb (uint32_t lba, uint8_t* buffer, uint32_t bufsize){ digitalWrite(LED_BUILTIN, HIGH); // Note: SPIFLash Bock API: readBlocks/writeBlocks/syncBlocks // already include 4K sector caching internally. We don't need to cache it, yahhhh!! return flash.writeBlocks(lba, buffer, bufsize/512) ? bufsize : -1; } // Callback invoked when WRITE10 command is completed (status received and accepted by host). // used to flush any pending cache. void msc_flush_cb (void){ // sync with flash flash.syncBlocks(); // clear file system's cache to force refresh fatfs.cacheClear(); digitalWrite(LED_BUILTIN, LOW); }
3,029
1,098
#include "ActorRenderNode.hpp" #include "Actor.hpp" using namespace nima; ActorRenderNode::ActorRenderNode(ComponentType type) : ActorNode(type), m_DrawOrder(0) { } void ActorRenderNode::copy(ActorRenderNode* node, Actor* resetActor) { Base::copy(node, resetActor); m_DrawOrder = node->m_DrawOrder; } int ActorRenderNode::drawOrder() const { return m_DrawOrder; } void ActorRenderNode::drawOrder(int order) { if (m_DrawOrder != order) { m_DrawOrder = order; if(m_Actor != nullptr) { m_Actor->markDrawOrderDirty(); } } }
545
226
#include <iostream> #include <GPM/GPM.h> int main(const int p_argc, char** p_argv) { try { // Try stuff here Matrix4F rot = GPM::Matrix4F::LookAt(GPM::Vector3F(0, 0, 0), GPM::Vector3F(0, 0, 3), GPM::Vector3F(0, 1, 0)); std::cout << rot; } catch (const std::exception & e) { std::cerr << "Exception thrown: " << e.what() << '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; }
393
188
/* Name - Nikhil Ranjan Nayak Regd No - 1641012040 Desc - Closest pair */ #include <stdio.h> #include <float.h> #include <stdlib.h> #include <math.h> // represent a Point in 2D plane struct Point { int x, y; }; // Needed to sort array of points according to X coordinate int compareX(const void* a, const void* b) { Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->x - p2->x); } // Needed to sort array of points according to Y coordinate int compareY(const void* a, const void* b) { Point *p1 = (Point *)a, *p2 = (Point *)b; return (p1->y - p2->y); } // find the distance between two points float dist(Point p1, Point p2) { return sqrt( (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y) ); } // A Brute Force method to return the smallest distance between two points // in P[] of size n float bruteForce(Point P[], int n) { float min = FLT_MAX; for (int i = 0; i < n; ++i) for (int j = i+1; j < n; ++j) if (dist(P[i], P[j]) < min) min = dist(P[i], P[j]); return min; } // find minimum of two float values float min(float x, float y) { return (x < y)? x : y; } // find the distance beween the closest points of // strip of given size. All points in strip[] are sorted according to // y coordinate. They all have an upper bound on minimum distance as d. float stripClosest(Point strip[], int size, float d) { float min = d; // Initialize the minimum distance as d qsort(strip, size, sizeof(Point), compareY); // Pick all points one by one and try the next points till the difference // between y coordinates is smaller than d. // This is a proven fact that this loop runs at most 6 times for (int i = 0; i < size; ++i) for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j) if (dist(strip[i],strip[j]) < min) min = dist(strip[i], strip[j]); return min; } // A recursive function to find the smallest distance. The array P contains // all points sorted according to x coordinate float closestUtil(Point P[], int n) { // If there are 2 or 3 points, then use brute force if (n <= 3) return bruteForce(P, n); // Find the middle point int mid = n/2; Point midPoint = P[mid]; // Consider the vertical line passing through the middle point // calculate the smallest distance dl on left of middle point and // dr on right side float dl = closestUtil(P, mid); float dr = closestUtil(P + mid, n-mid); // Find the smaller of two distances float d = min(dl, dr); // Build an array strip[] that contains points close (closer than d) // to the line passing through the middle point Point strip[n]; int j = 0; for (int i = 0; i < n; i++) if (abs(P[i].x - midPoint.x) < d) strip[j] = P[i], j++; // Find the closest points in strip. Return the minimum of d and closest // distance is strip[] return min(d, stripClosest(strip, j, d) ); } // finds the smallest distance // This method mainly uses closestUtil() float closest(Point P[], int n) { qsort(P, n, sizeof(Point), compareX); // Use recursive function closestUtil() to find the smallest distance return closestUtil(P, n); } int main() { Point P[] = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}}; int n = sizeof(P) / sizeof(P[0]); printf("The smallest distance is %f.", closest(P, n)); printf("\n"); return 0; }
3,283
1,233
#include <iostream> #include <string> using namespace std; int main(){ int dataSets = 0; int rev, exp, adv; cin >> dataSets; for (int i = 0; i < dataSets; i++){ cin >> rev >> exp >> adv; if (rev > (exp - adv)){ cout << "do not advertise\n"; } else if (rev == (exp - adv)){ cout << "does not matter\n"; } else{ cout << "advertise\n"; } } return 0; }
379
172
const int MX = 1e7 int status[(MX/32)+2]; void sieve() { int i, j, sqrtN; sqrtN = int( sqrt( N ) ); for( i = 3; i <= sqrtN; i += 2 ) { if( bitCheck(status[i>>5],i&31)==0) { for( j = i*i; j <= N; j += (i<<1) ) { status[j>>5] = bitOn(status[j>>5],j & 31); } } } puts("2"); for(i=3; i<=N; i+=2) if( Check(status[i>>5],i&31)==0) printf("%d\n",i); }
469
214
// redmine usage: This commit refs #388 @2h // ############################################################################################### // ############################################################################################### // ############################################################################################### /* * KITTI_PLAYER v2. * * Augusto Luis Ballardini, ballardini@disco.unimib.it * * https://github.com/iralabdisco/kitti_player * * WARNING: this package is using some C++11 * */ // ############################################################################################### // ############################################################################################### // ############################################################################################### #include <iostream> #include <fstream> #include <limits> #include <sstream> #include <string> #include <ros/ros.h> #include <boost/algorithm/string.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> //#include <boost/locale.hpp> #include <boost/program_options.hpp> #include <boost/progress.hpp> #include <boost/tokenizer.hpp> #include <boost/tokenizer.hpp> #include <cv_bridge/cv_bridge.h> #include <image_transport/image_transport.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <sensor_msgs/distortion_models.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/NavSatFix.h> #include <sensor_msgs/PointCloud2.h> #include <stereo_msgs/DisparityImage.h> #include <tf/LinearMath/Transform.h> #include <tf/transform_broadcaster.h> #include <tf/transform_listener.h> #include <time.h> /// EXTRA messages, not from KITTI /// Inser here further detectors & features to be published //#include <road_layout_estimation/msg_lines.h> //#include <road_layout_estimation/msg_lineInfo.h> using namespace std; using namespace pcl; using namespace ros; using namespace tf; namespace po = boost::program_options; struct kitti_player_options { string path; float frequency; // publisher frequency. 1 > Kitti default 10Hz bool all_data; // publish everything bool velodyne; // publish velodyne point clouds /as PCL bool gps; // publish GPS sensor_msgs/NavSatFix message bool imu; // publish IMU sensor_msgs/Imu Message message bool grayscale; // publish bool color; // publish bool viewer; // enable CV viewer bool timestamps; // use KITTI timestamps; bool sendTransform; // publish velodyne TF IMU 3DOF orientation wrt fixed frame bool stereoDisp; // use precalculated stereoDisparities bool viewDisparities; // view use precalculated stereoDisparities unsigned int startFrame; // start the replay at frame ... /// Extra parameters bool laneDetections; // send laneDetections; }; /** * @brief publish_velodyne * @param pub The ROS publisher as reference * @param infile file with data to publish * @param header Header to use to publish the message * @return 1 if file is correctly readed, 0 otherwise */ int publish_velodyne(ros::Publisher &pub, string infile, std_msgs::Header *header) { fstream input(infile.c_str(), ios::in | ios::binary); if(!input.good()) { ROS_ERROR_STREAM ( "Could not read file: " << infile ); return 0; } else { ROS_DEBUG_STREAM ("reading " << infile); input.seekg(0, ios::beg); pcl::PointCloud<pcl::PointXYZI>::Ptr points (new pcl::PointCloud<pcl::PointXYZI>); int i; for (i=0; input.good() && !input.eof(); i++) { pcl::PointXYZI point; input.read((char *) &point.x, 3*sizeof(float)); input.read((char *) &point.intensity, sizeof(float)); points->push_back(point); } input.close(); //workaround for the PCL headers... http://wiki.ros.org/hydro/Migration#PCL sensor_msgs::PointCloud2 pc2; pc2.header.frame_id= "velodyne"; //ros::this_node::getName(); pc2.header.stamp=header->stamp; pc2.header.seq=header->seq; points->header = pcl_conversions::toPCL(pc2.header); pub.publish(points); return 1; } } /** * @brief getCalibration * @param dir_root * @param camera_name * @param K double K[9] - Calibration Matrix * @param D double D[5] - Distortion Coefficients * @param R double R[9] - Rectification Matrix * @param P double P[12] - Projection Matrix Rectified (u,v,w) = P * R * (x,y,z,q) * @return 1: file found, 0: file not found * * from: http://kitti.is.tue.mpg.de/kitti/devkit_raw_data.zip * calib_cam_to_cam.txt: Camera-to-camera calibration * * - S_xx: 1x2 size of image xx before rectification * - K_xx: 3x3 calibration matrix of camera xx before rectification * - D_xx: 1x5 distortion vector of camera xx before rectification * - R_xx: 3x3 rotation matrix of camera xx (extrinsic) * - T_xx: 3x1 translation vector of camera xx (extrinsic) * - S_rect_xx: 1x2 size of image xx after rectification * - R_rect_xx: 3x3 rectifying rotation to make image planes co-planar * - P_rect_xx: 3x4 projection matrix after rectification */ int getCalibration(string dir_root, string camera_name, double* K,std::vector<double> & D,double *R,double* P){ string calib_cam_to_cam=dir_root+"calib_cam_to_cam.txt"; ifstream file_c2c(calib_cam_to_cam.c_str()); if (!file_c2c.is_open()) return false; ROS_INFO_STREAM("Reading camera" << camera_name << " calibration from " << calib_cam_to_cam); typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep{" "}; string line=""; char index=0; tokenizer::iterator token_iterator; while (getline(file_c2c,line)) { // Parse string phase 1, tokenize it using Boost. tokenizer tok(line,sep); // Move the iterator at the beginning of the tokenize vector and check for K/D/R/P matrices. token_iterator=tok.begin(); if (strcmp((*token_iterator).c_str(),((string)(string("K_")+camera_name+string(":"))).c_str())==0) //Calibration Matrix { index=0; //should be 9 at the end ROS_DEBUG_STREAM("K_" << camera_name); for (token_iterator++; token_iterator != tok.end(); token_iterator++) { //std::cout << *token_iterator << '\n'; K[index++]=boost::lexical_cast<double>(*token_iterator); } } // EXPERIMENTAL: use with unrectified images // token_iterator=tok.begin(); // if (strcmp((*token_iterator).c_str(),((string)(string("D_")+camera_name+string(":"))).c_str())==0) //Distortion Coefficients // { // index=0; //should be 5 at the end // ROS_DEBUG_STREAM("D_" << camera_name); // for (token_iterator++; token_iterator != tok.end(); token_iterator++) // { //// std::cout << *token_iterator << '\n'; // D[index++]=boost::lexical_cast<double>(*token_iterator); // } // } token_iterator=tok.begin(); if (strcmp((*token_iterator).c_str(),((string)(string("R_")+camera_name+string(":"))).c_str())==0) //Rectification Matrix { index=0; //should be 12 at the end ROS_DEBUG_STREAM("R_" << camera_name); for (token_iterator++; token_iterator != tok.end(); token_iterator++) { //std::cout << *token_iterator << '\n'; R[index++]=boost::lexical_cast<double>(*token_iterator); } } token_iterator=tok.begin(); if (strcmp((*token_iterator).c_str(),((string)(string("P_rect_")+camera_name+string(":"))).c_str())==0) //Projection Matrix Rectified { index=0; //should be 12 at the end ROS_DEBUG_STREAM("P_rect_" << camera_name); for (token_iterator++; token_iterator != tok.end(); token_iterator++) { //std::cout << *token_iterator << '\n'; P[index++]=boost::lexical_cast<double>(*token_iterator); } } } ROS_INFO_STREAM("... ok"); return true; } int getGPS(string filename, sensor_msgs::NavSatFix *ros_msgGpsFix, std_msgs::Header *header) { ifstream file_oxts(filename.c_str()); if (!file_oxts.is_open()){ ROS_ERROR_STREAM("Fail to open " << filename); return 0; } ROS_DEBUG_STREAM("Reading GPS data from oxts file: " << filename ); typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep{" "}; string line=""; getline(file_oxts,line); tokenizer tok(line,sep); vector<string> s(tok.begin(), tok.end()); ros_msgGpsFix->header.frame_id = ros::this_node::getName(); ros_msgGpsFix->header.stamp = header->stamp; ros_msgGpsFix->latitude = boost::lexical_cast<double>(s[0]); ros_msgGpsFix->longitude = boost::lexical_cast<double>(s[1]); ros_msgGpsFix->altitude = boost::lexical_cast<double>(s[2]); ros_msgGpsFix->position_covariance_type = sensor_msgs::NavSatFix::COVARIANCE_TYPE_APPROXIMATED; for (int i=0;i<9;i++) ros_msgGpsFix->position_covariance[i] = 0.0f; ros_msgGpsFix->position_covariance[0] = boost::lexical_cast<double>(s[23]); ros_msgGpsFix->position_covariance[4] = boost::lexical_cast<double>(s[23]); ros_msgGpsFix->position_covariance[8] = boost::lexical_cast<double>(s[23]); ros_msgGpsFix->status.service = sensor_msgs::NavSatStatus::SERVICE_GPS; ros_msgGpsFix->status.status = sensor_msgs::NavSatStatus::STATUS_GBAS_FIX; return 1; } int getIMU(string filename, sensor_msgs::Imu *ros_msgImu, std_msgs::Header *header) { ifstream file_oxts(filename.c_str()); if (!file_oxts.is_open()) { ROS_ERROR_STREAM("Fail to open " << filename); return 0; } ROS_DEBUG_STREAM("Reading IMU data from oxts file: " << filename ); typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep{" "}; string line=""; getline(file_oxts,line); tokenizer tok(line,sep); vector<string> s(tok.begin(), tok.end()); ros_msgImu->header.frame_id = ros::this_node::getName(); ros_msgImu->header.stamp = header->stamp; // - ax: acceleration in x, i.e. in direction of vehicle front (m/s^2) // - ay: acceleration in y, i.e. in direction of vehicle left (m/s^2) // - az: acceleration in z, i.e. in direction of vehicle top (m/s^2) ros_msgImu->linear_acceleration.x = boost::lexical_cast<double>(s[11]); ros_msgImu->linear_acceleration.y = boost::lexical_cast<double>(s[12]); ros_msgImu->linear_acceleration.z = boost::lexical_cast<double>(s[13]); // - vf: forward velocity, i.e. parallel to earth-surface (m/s) // - vl: leftward velocity, i.e. parallel to earth-surface (m/s) // - vu: upward velocity, i.e. perpendicular to earth-surface (m/s) ros_msgImu->angular_velocity.x = boost::lexical_cast<double>(s[8]); ros_msgImu->angular_velocity.y = boost::lexical_cast<double>(s[9]); ros_msgImu->angular_velocity.z = boost::lexical_cast<double>(s[10]); // - roll: roll angle (rad), 0 = level, positive = left side up (-pi..pi) // - pitch: pitch angle (rad), 0 = level, positive = front down (-pi/2..pi/2) // - yaw: heading (rad), 0 = east, positive = counter clockwise (-pi..pi) tf::Quaternion q=tf::createQuaternionFromRPY( boost::lexical_cast<double>(s[3]), boost::lexical_cast<double>(s[4]), boost::lexical_cast<double>(s[5]) ); ros_msgImu->orientation.x = q.getX(); ros_msgImu->orientation.y = q.getY(); ros_msgImu->orientation.z = q.getZ(); ros_msgImu->orientation.w = q.getW(); return 1; } /** * @brief parseTime * @param timestamp in Epoch * @return std_msgs::Header with input timpestamp converted from file input * * Epoch time conversion * http://www.epochconverter.com/programming/functions-c.php */ std_msgs::Header parseTime(string timestamp) { std_msgs::Header header; typedef boost::tokenizer<boost::char_separator<char> > tokenizer; // example: 2011-09-26 13:21:35.134391552 // 01234567891111111111222222222 // 0123456789012345678 struct tm t = {0}; // Initalize to all 0's t.tm_year = boost::lexical_cast<int>(timestamp.substr(0,4)) - 1900; t.tm_mon = boost::lexical_cast<int>(timestamp.substr(5,2)) - 1; t.tm_mday = boost::lexical_cast<int>(timestamp.substr(8,2)); t.tm_hour = boost::lexical_cast<int>(timestamp.substr(11,2)); t.tm_min = boost::lexical_cast<int>(timestamp.substr(14,2)); t.tm_sec = boost::lexical_cast<int>(timestamp.substr(17,2)); t.tm_isdst = -1; time_t timeSinceEpoch = mktime(&t); header.stamp.sec = timeSinceEpoch; header.stamp.nsec = boost::lexical_cast<int>(timestamp.substr(20,8)); return header; } /** * @brief getLaneDetection * @param infile * @param msg_lines * @return */ /* int getLaneDetection(string infile, road_layout_estimation::msg_lines *msg_lines) { ROS_DEBUG_STREAM("Reading lane detections from " << infile); ifstream detection_file(infile); if (!detection_file.is_open()) return false; msg_lines->number_of_lines = 0; msg_lines->goodLines = 0; msg_lines->width = 0; msg_lines->oneway = 0; msg_lines->naive_width = 0; msg_lines->lines.clear(); typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep{"\t"}; // TAB string line=""; char index = 0; double last_right_detection = std::numeric_limits<double>::min(); //uses *ONLY* the valid lines double last_left_detection = std::numeric_limits<double>::max(); //uses *ONLY* the valid lines double naive_last_right_detection = std::numeric_limits<double>::min(); //uses all values, even if the line is not valid double naive_last_left_detection = std::numeric_limits<double>::max(); //uses all values, even if the line is not valid while (getline(detection_file,line)) { // Parse string phase 1, tokenize it using Boost. tokenizer tok(line,sep); if (index==0) { vector<string> s(tok.begin(), tok.end()); msg_lines->goodLines = boost::lexical_cast<int>(s[0]); index++; } else { road_layout_estimation::msg_lineInfo line; vector<string> s(tok.begin(), tok.end()); if (s.size()!=3) { ROS_WARN_STREAM("Unexpected file format, can't read"); return false; } line.isValid = boost::lexical_cast<bool> (s[0]); line.counter = boost::lexical_cast<int> (s[1]); line.offset = boost::lexical_cast<float> (s[2]); msg_lines->lines.push_back(line); if (line.isValid) { if (line.offset > last_right_detection) last_right_detection = line.offset; if (line.offset < last_left_detection) last_left_detection = line.offset; } if (line.offset > naive_last_right_detection) naive_last_right_detection = line.offset; if (line.offset < naive_last_left_detection) naive_last_left_detection = line.offset; index++; } } // Number of lines in the file, 1 line 'in the picture' is one row in the file, minus // one, the first, that is the number of "good" (current tracked in good state) lines. msg_lines->number_of_lines = index -1 ; if (msg_lines->goodLines > 1) msg_lines->width = abs(last_left_detection) + abs(last_right_detection); else msg_lines->width = abs(last_left_detection); msg_lines->naive_width = abs(naive_last_left_detection) + abs(naive_last_right_detection); msg_lines->way_id = 0; ///WARNING this value is not used yet. if (msg_lines->width == std::numeric_limits<double>::max()) msg_lines->width = 0.0f; if (msg_lines->naive_width == std::numeric_limits<double>::max()) msg_lines->naive_width = 0.0f; ROS_DEBUG_STREAM("Number of LANEs: " << msg_lines->number_of_lines << "\tNumber of good LINEs "<<msg_lines->goodLines); ROS_DEBUG_STREAM("... getLaneDetection ok"); return true; } */ /** * @brief main Kitti_player, a player for KITTI raw datasets * @param argc * @param argv * @return 0 and ros::shutdown at the end of the dataset, -1 if errors * * Allowed options: * -h [ --help ] help message * -d [ --directory ] arg *required* - path to the kitti dataset Directory * -f [ --frequency ] arg (=1) set replay Frequency * -a [ --all ] [=arg(=1)] (=0) replay All data * -v [ --velodyne ] [=arg(=1)] (=0) replay Velodyne data * -g [ --gps ] [=arg(=1)] (=0) replay Gps data * -i [ --imu ] [=arg(=1)] (=0) replay Imu data * -G [ --grayscale ] [=arg(=1)] (=0) replay Stereo Grayscale images * -C [ --color ] [=arg(=1)] (=0) replay Stereo Color images * -V [ --viewer ] [=arg(=1)] (=0) enable image viewer * -T [ --timestamps ] [=arg(=1)] (=0) use KITTI timestamps * -s [ --stereoDisp ] [=arg(=1)] (=0) use pre-calculated disparities * -D [ --viewDisp ] [=arg(=1)] (=0) view loaded disparity images * -l [ --laneDetect ] [=arg(=1)] (=0) send extra lanes message * -F [ --frame ] [=arg(=0)] (=0) start playing at frame ... * * Datasets can be downloaded from: http://www.cvlibs.net/datasets/kitti/raw_data.php */ int main(int argc, char **argv) { kitti_player_options options; po::variables_map vm; po::options_description desc("Kitti_player, a player for KITTI raw datasets\nDatasets can be downloaded from: http://www.cvlibs.net/datasets/kitti/raw_data.php\n\nAllowed options",200); desc.add_options() ("help,h" , "help message") ("directory ,d", po::value<string> (&options.path)->required() , "*required* - path to the kitti dataset Directory") ("frequency ,f", po::value<float> (&options.frequency) ->default_value(1.0) , "set replay Frequency") ("all ,a", po::value<bool> (&options.all_data) ->default_value(0) ->implicit_value(1) , "replay All data") ("velodyne ,v", po::value<bool> (&options.velodyne) ->default_value(0) ->implicit_value(1) , "replay Velodyne data") ("gps ,g", po::value<bool> (&options.gps) ->default_value(0) ->implicit_value(1) , "replay Gps data") ("imu ,i", po::value<bool> (&options.imu) ->default_value(0) ->implicit_value(1) , "replay Imu data") ("grayscale ,G", po::value<bool> (&options.grayscale) ->default_value(0) ->implicit_value(1) , "replay Stereo Grayscale images") ("color ,C", po::value<bool> (&options.color) ->default_value(0) ->implicit_value(1) , "replay Stereo Color images") ("viewer ,V", po::value<bool> (&options.viewer) ->default_value(0) ->implicit_value(1) , "enable image viewer") ("timestamps,T", po::value<bool> (&options.timestamps) ->default_value(0) ->implicit_value(1) , "use KITTI timestamps") ("stereoDisp,s", po::value<bool> (&options.stereoDisp) ->default_value(0) ->implicit_value(1) , "use pre-calculated disparities") ("viewDisp ,D ", po::value<bool> (&options.viewDisparities)->default_value(0) ->implicit_value(1) , "view loaded disparity images") ("laneDetect,l", po::value<bool> (&options.laneDetections) ->default_value(0) ->implicit_value(1) , "send extra lanes message") ("frame ,F", po::value<unsigned int> (&options.startFrame) ->default_value(0) ->implicit_value(0) , "start playing at frame...") ; try // parse options { po::parsed_options parsed = po::command_line_parser(argc-2, argv).options(desc).allow_unregistered().run(); po::store(parsed, vm); po::notify(vm); vector<string> to_pass_further = po::collect_unrecognized(parsed.options, po::include_positional); // Can't handle __ros (ROS parameters ... ) // if (to_pass_further.size()>0) // { // ROS_WARN_STREAM("Unknown Options Detected, shutting down node\n"); // cerr << desc << endl; // return 1; // } } catch(...) { cerr << desc << endl; cout << "kitti_player needs a directory tree like the following:" << endl; cout << "โ””โ”€โ”€ 2011_09_26_drive_0001_sync" << endl; cout << " โ”œโ”€โ”€ image_00 " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ image_01 " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ image_02 " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ image_03 " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ oxts " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ velodyne_points " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ””โ”€โ”€ calib_cam_to_cam.txt " << endl << endl; ROS_WARN_STREAM("Parse error, shutting down node\n"); return -1; } ros::init(argc, argv, "kitti_player"); ros::NodeHandle node("kitti_player"); ros::Rate loop_rate(options.frequency); /// This sets the logger level; use this to disable all ROS prints if( ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug) ) ros::console::notifyLoggerLevelsChanged(); else std::cout << "Error while setting the logger level!" << std::endl; DIR *dir; struct dirent *ent; unsigned int total_entries = 0; //number of elements to be played unsigned int entries_played = 0; //number of elements played until now unsigned int len = 0; //counting elements support variable string dir_root ; string dir_image00 ;string full_filename_image00; string dir_timestamp_image00; string dir_image01 ;string full_filename_image01; string dir_timestamp_image01; string dir_image02 ;string full_filename_image02; string dir_timestamp_image02; string dir_image03 ;string full_filename_image03; string dir_timestamp_image03; string dir_image04 ;string full_filename_image04; string dir_laneDetections ;string full_filename_laneDetections; string dir_laneProjected ;string full_filename_laneProjected; string dir_oxts ;string full_filename_oxts; string dir_timestamp_oxts; string dir_velodyne_points ;string full_filename_velodyne; string dir_timestamp_velodyne; //average of start&end (time of scan) string str_support; cv::Mat cv_image00; cv::Mat cv_image01; cv::Mat cv_image02; cv::Mat cv_image03; cv::Mat cv_image04; cv::Mat cv_laneProjected; std_msgs::Header header_support; image_transport::ImageTransport it(node); image_transport::CameraPublisher pub00 = it.advertiseCamera("grayscale/left/image_rect", 1); image_transport::CameraPublisher pub01 = it.advertiseCamera("grayscale/right/image_rect", 1); image_transport::CameraPublisher pub02 = it.advertiseCamera("color/left/image_rect", 1); image_transport::CameraPublisher pub03 = it.advertiseCamera("color/right/image_rect", 1); sensor_msgs::Image ros_msg00; sensor_msgs::Image ros_msg01; sensor_msgs::Image ros_msg02; sensor_msgs::Image ros_msg03; // sensor_msgs::CameraInfo ros_cameraInfoMsg; sensor_msgs::CameraInfo ros_cameraInfoMsg_camera00; sensor_msgs::CameraInfo ros_cameraInfoMsg_camera01; sensor_msgs::CameraInfo ros_cameraInfoMsg_camera02; sensor_msgs::CameraInfo ros_cameraInfoMsg_camera03; cv_bridge::CvImage cv_bridge_img; ros::Publisher map_pub = node.advertise<pcl::PointCloud<pcl::PointXYZ> > ("hdl64e", 1, true); ros::Publisher gps_pub = node.advertise<sensor_msgs::NavSatFix> ("oxts/gps", 1, true); ros::Publisher gps_pub_initial = node.advertise<sensor_msgs::NavSatFix> ("oxts/gps_initial", 1, true); ros::Publisher imu_pub = node.advertise<sensor_msgs::Imu> ("oxts/imu", 1, true); ros::Publisher disp_pub = node.advertise<stereo_msgs::DisparityImage> ("preprocessed_disparity",1,true); //ros::Publisher lanes_pub = node.advertise<road_layout_estimation::msg_lines>("lanes",1,true); sensor_msgs::NavSatFix ros_msgGpsFix; sensor_msgs::NavSatFix ros_msgGpsFixInitial; // This message contains the first reading of the file bool firstGpsData = true; // Flag to store the ros_msgGpsFixInitial message sensor_msgs::Imu ros_msgImu; //road_layout_estimation::msg_lines msgLanes; if (vm.count("help")) { cout << desc << endl; cout << "kitti_player needs a directory tree like the following:" << endl; cout << "โ””โ”€โ”€ 2011_09_26_drive_0001_sync" << endl; cout << " โ”œโ”€โ”€ image_00 " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ image_01 " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ image_02 " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ image_03 " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ oxts " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ”œโ”€โ”€ velodyne_points " << endl; cout << " โ”‚ โ””โ”€โ”€ data " << endl; cout << " โ”‚ โ”” timestamps.txt " << endl; cout << " โ””โ”€โ”€ calib_cam_to_cam.txt " << endl << endl; return 1; } if (!(options.all_data || options.color || options.gps || options.grayscale || options.imu || options.velodyne)) { ROS_WARN_STREAM("Job finished without playing the dataset. No 'publishing' parameters provided"); node.shutdown(); return 1; } dir_root = options.path; dir_image00 = options.path; dir_image01 = options.path; dir_image02 = options.path; dir_image03 = options.path; dir_image04 = options.path; dir_oxts = options.path; dir_velodyne_points = options.path; dir_image04 = options.path; (*(options.path.end()-1) != '/' ? dir_root = options.path+"/" : dir_root = options.path); (*(options.path.end()-1) != '/' ? dir_image00 = options.path+"/image_00/data/" : dir_image00 = options.path+"image_00/data/"); (*(options.path.end()-1) != '/' ? dir_image01 = options.path+"/image_01/data/" : dir_image01 = options.path+"image_01/data/"); (*(options.path.end()-1) != '/' ? dir_image02 = options.path+"/image_02/data/" : dir_image02 = options.path+"image_02/data/"); (*(options.path.end()-1) != '/' ? dir_image03 = options.path+"/image_03/data/" : dir_image03 = options.path+"image_03/data/"); (*(options.path.end()-1) != '/' ? dir_image04 = options.path+"/disparities/" : dir_image04 = options.path+"disparities/"); (*(options.path.end()-1) != '/' ? dir_oxts = options.path+"/oxts/data/" : dir_oxts = options.path+"oxts/data/"); (*(options.path.end()-1) != '/' ? dir_velodyne_points = options.path+"/velodyne_points/data/" : dir_velodyne_points = options.path+"velodyne_points/data/"); (*(options.path.end()-1) != '/' ? dir_timestamp_image00 = options.path+"/image_00/" : dir_timestamp_image00 = options.path+"image_00/"); (*(options.path.end()-1) != '/' ? dir_timestamp_image01 = options.path+"/image_01/" : dir_timestamp_image01 = options.path+"image_01/"); (*(options.path.end()-1) != '/' ? dir_timestamp_image02 = options.path+"/image_02/" : dir_timestamp_image02 = options.path+"image_02/"); (*(options.path.end()-1) != '/' ? dir_timestamp_image03 = options.path+"/image_03/" : dir_timestamp_image03 = options.path+"image_03/"); (*(options.path.end()-1) != '/' ? dir_timestamp_oxts = options.path+"/oxts/" : dir_timestamp_oxts = options.path+"oxts/"); (*(options.path.end()-1) != '/' ? dir_timestamp_velodyne = options.path+"/velodyne_points/" : dir_timestamp_velodyne = options.path+"velodyne_points/"); (*(options.path.end()-1) != '/' ? dir_timestamp_velodyne = options.path+"/velodyne_points/" : dir_timestamp_velodyne = options.path+"velodyne_points/"); /// EXTRA /// 01. Lane detections (*(options.path.end()-1) != '/' ? dir_laneDetections = options.path+"/lane/" : dir_laneDetections = options.path+"lane/"); (*(options.path.end()-1) != '/' ? dir_laneProjected = options.path+"/all/" : dir_laneProjected = options.path+"all/"); // Check all the directories if ( (options.all_data && ( (opendir(dir_image00.c_str()) == NULL) || (opendir(dir_image01.c_str()) == NULL) || (opendir(dir_image02.c_str()) == NULL) || (opendir(dir_image03.c_str()) == NULL) || (opendir(dir_oxts.c_str()) == NULL) || (opendir(dir_velodyne_points.c_str()) == NULL))) || (options.color && ( (opendir(dir_image02.c_str()) == NULL) || (opendir(dir_image03.c_str()) == NULL))) || (options.grayscale && ( (opendir(dir_image00.c_str()) == NULL) || (opendir(dir_image01.c_str()) == NULL))) || (options.imu && ( (opendir(dir_oxts.c_str()) == NULL))) || (options.gps && ( (opendir(dir_oxts.c_str()) == NULL))) //|| //(options.stereoDisp && ( (opendir(dir_image04.c_str()) == NULL))) || (options.velodyne && ( (opendir(dir_velodyne_points.c_str()) == NULL))) //|| //(options.laneDetections && ( (opendir(dir_laneDetections.c_str()) == NULL))) || (options.timestamps && ( (opendir(dir_timestamp_image00.c_str()) == NULL) || (opendir(dir_timestamp_image01.c_str()) == NULL) || (opendir(dir_timestamp_image02.c_str()) == NULL) || (opendir(dir_timestamp_image03.c_str()) == NULL) || (opendir(dir_timestamp_oxts.c_str()) == NULL) || (opendir(dir_timestamp_velodyne.c_str()) == NULL))) ) { ROS_ERROR("Incorrect tree directory , use --help for details"); node.shutdown(); return -1; } else { ROS_INFO_STREAM ("Checking directories..."); ROS_INFO_STREAM (options.path << "\t[OK]"); } //count elements in the folder if (options.all_data) { dir = opendir(dir_image02.c_str()); while(ent = readdir(dir)) { //skip . & .. len = strlen (ent->d_name); //skip . & .. if (len>2) total_entries++; } closedir (dir); } else { bool done=false; if (!done && options.color) { total_entries=0; dir = opendir(dir_image02.c_str()); while(ent = readdir(dir)) { //skip . & .. len = strlen (ent->d_name); //skip . & .. if (len>2) total_entries++; } closedir (dir); done=true; } if (!done && options.grayscale) { total_entries=0; dir = opendir(dir_image00.c_str()); while(ent = readdir(dir)) { //skip . & .. len = strlen (ent->d_name); //skip . & .. if (len>2) total_entries++; } closedir (dir); done=true; } if (!done && options.gps) { total_entries=0; dir = opendir(dir_oxts.c_str()); while(ent = readdir(dir)) { //skip . & .. len = strlen (ent->d_name); //skip . & .. if (len>2) total_entries++; } closedir (dir); done=true; } if (!done && options.imu) { total_entries=0; dir = opendir(dir_oxts.c_str()); while(ent = readdir(dir)) { //skip . & .. len = strlen (ent->d_name); //skip . & .. if (len>2) total_entries++; } closedir (dir); done=true; } if (!done && options.velodyne) { total_entries=0; dir = opendir(dir_oxts.c_str()); while(ent = readdir(dir)) { //skip . & .. len = strlen (ent->d_name); //skip . & .. if (len>2) total_entries++; } closedir (dir); done=true; } if (!done && options.stereoDisp) { total_entries=0; dir = opendir(dir_image04.c_str()); while(ent = readdir(dir)) { //skip . & .. len = strlen (ent->d_name); //skip . & .. if (len>2) total_entries++; } closedir (dir); done=true; } if (!done && options.laneDetections) { total_entries=0; dir = opendir(dir_laneDetections.c_str()); while(ent = readdir(dir)) { //skip . & .. len = strlen (ent->d_name); //skip . & .. if (len>2) total_entries++; } closedir (dir); done=true; } } // Check options.startFrame and total_entries if (options.startFrame > total_entries) { ROS_ERROR("Error, start number > total entries in the dataset"); node.shutdown(); return -1; } else { entries_played = options.startFrame; ROS_INFO_STREAM("The entry point (frame number) is: " << entries_played); } if(options.viewer) { ROS_INFO_STREAM("Opening CV viewer(s)"); if(options.color || options.all_data) { ROS_DEBUG_STREAM("color||all " << options.color << " " << options.all_data); cv::namedWindow("CameraSimulator Color Viewer",CV_WINDOW_AUTOSIZE); full_filename_image02 = dir_image02 + boost::str(boost::format("%010d") % 0 ) + ".png"; cv_image02 = cv::imread(full_filename_image02, CV_LOAD_IMAGE_UNCHANGED); cv::waitKey(5); } if(options.grayscale || options.all_data) { ROS_DEBUG_STREAM("grayscale||all " << options.grayscale << " " << options.all_data); cv::namedWindow("CameraSimulator Grayscale Viewer",CV_WINDOW_AUTOSIZE); full_filename_image00 = dir_image00 + boost::str(boost::format("%010d") % 0 ) + ".png"; cv_image00 = cv::imread(full_filename_image00, CV_LOAD_IMAGE_UNCHANGED); cv::waitKey(5); } if (options.viewDisparities || options.all_data) { ROS_DEBUG_STREAM("viewDisparities||all " << options.grayscale << " " << options.all_data); cv::namedWindow("Reprojection of Detected Lines",CV_WINDOW_AUTOSIZE); full_filename_laneProjected = dir_laneProjected + boost::str(boost::format("%010d") % 0 ) + ".png"; cv_laneProjected = cv::imread(full_filename_laneProjected, CV_LOAD_IMAGE_UNCHANGED); cv::waitKey(5); } ROS_INFO_STREAM("Opening CV viewer(s)... OK"); } // CAMERA INFO SECTION: read one for all ros_cameraInfoMsg_camera00.header.stamp = ros::Time::now(); ros_cameraInfoMsg_camera00.header.frame_id = ros::this_node::getName(); ros_cameraInfoMsg_camera00.height = 0; ros_cameraInfoMsg_camera00.width = 0; //ros_cameraInfoMsg_camera00.D.resize(5); //ros_cameraInfoMsg_camera00.distortion_model=sensor_msgs::distortion_models::PLUMB_BOB; ros_cameraInfoMsg_camera01.header.stamp = ros::Time::now(); ros_cameraInfoMsg_camera01.header.frame_id = ros::this_node::getName(); ros_cameraInfoMsg_camera01.height = 0; ros_cameraInfoMsg_camera01.width = 0; //ros_cameraInfoMsg_camera01.D.resize(5); //ros_cameraInfoMsg_camera00.distortion_model=sensor_msgs::distortion_models::PLUMB_BOB; ros_cameraInfoMsg_camera02.header.stamp = ros::Time::now(); ros_cameraInfoMsg_camera02.header.frame_id = ros::this_node::getName(); ros_cameraInfoMsg_camera02.height = 0; ros_cameraInfoMsg_camera02.width = 0; //ros_cameraInfoMsg_camera02.D.resize(5); //ros_cameraInfoMsg_camera02.distortion_model=sensor_msgs::distortion_models::PLUMB_BOB; ros_cameraInfoMsg_camera03.header.stamp = ros::Time::now(); ros_cameraInfoMsg_camera03.header.frame_id = ros::this_node::getName(); ros_cameraInfoMsg_camera03.height = 0; ros_cameraInfoMsg_camera03.width = 0; //ros_cameraInfoMsg_camera03.D.resize(5); //ros_cameraInfoMsg_camera03.distortion_model=sensor_msgs::distortion_models::PLUMB_BOB; if(options.color || options.all_data) { if( !(getCalibration(dir_root,"02",ros_cameraInfoMsg_camera02.K.data(),ros_cameraInfoMsg_camera02.D,ros_cameraInfoMsg_camera02.R.data(),ros_cameraInfoMsg_camera02.P.data()) && getCalibration(dir_root,"03",ros_cameraInfoMsg_camera03.K.data(),ros_cameraInfoMsg_camera03.D,ros_cameraInfoMsg_camera03.R.data(),ros_cameraInfoMsg_camera03.P.data())) ) { ROS_ERROR_STREAM("Error reading CAMERA02/CAMERA03 calibration"); //node.shutdown(); //return -1; } //Assume same height/width for the camera pair full_filename_image02 = dir_image02 + boost::str(boost::format("%010d") % 0 ) + ".png"; cv_image02 = cv::imread(full_filename_image02, CV_LOAD_IMAGE_UNCHANGED); cv::waitKey(5); ros_cameraInfoMsg_camera03.height = ros_cameraInfoMsg_camera02.height = cv_image02.rows;// -1;TODO: CHECK, qui potrebbe essere -1 ros_cameraInfoMsg_camera03.width = ros_cameraInfoMsg_camera02.width = cv_image02.cols;// -1; } if(options.grayscale || options.all_data) { if( !(getCalibration(dir_root,"00",ros_cameraInfoMsg_camera00.K.data(),ros_cameraInfoMsg_camera00.D,ros_cameraInfoMsg_camera00.R.data(),ros_cameraInfoMsg_camera00.P.data()) && getCalibration(dir_root,"01",ros_cameraInfoMsg_camera01.K.data(),ros_cameraInfoMsg_camera01.D,ros_cameraInfoMsg_camera01.R.data(),ros_cameraInfoMsg_camera01.P.data())) ) { ROS_ERROR_STREAM("Error reading CAMERA00/CAMERA01 calibration"); //node.shutdown(); //return -1; } //Assume same height/width for the camera pair full_filename_image00 = dir_image00 + boost::str(boost::format("%010d") % 0 ) + ".png"; cv_image00 = cv::imread(full_filename_image00, CV_LOAD_IMAGE_UNCHANGED); cv::waitKey(5); ros_cameraInfoMsg_camera01.height = ros_cameraInfoMsg_camera00.height = cv_image00.rows;// -1; TODO: CHECK -1? ros_cameraInfoMsg_camera01.width = ros_cameraInfoMsg_camera00.width = cv_image00.cols;// -1; } boost::progress_display progress(total_entries) ; double cv_min, cv_max=0.0f; // This is the main KITTI_PLAYER Loop do { // single timestamp for all published stuff Time current_timestamp=ros::Time::now(); if(options.stereoDisp) { // Allocate new disparity image message stereo_msgs::DisparityImagePtr disp_msg = boost::make_shared<stereo_msgs::DisparityImage>(); full_filename_image04 = dir_image04 + boost::str(boost::format("%010d") % entries_played ) + ".png"; cv_image04 = cv::imread(full_filename_image04, CV_LOAD_IMAGE_GRAYSCALE); cv::minMaxLoc(cv_image04,&cv_min,&cv_max); disp_msg->min_disparity = (int)cv_min; disp_msg->max_disparity = (int)cv_max; disp_msg->valid_window.x_offset = 0; // should be safe, checked! disp_msg->valid_window.y_offset = 0; // should be safe, checked! disp_msg->valid_window.width = 0; // should be safe, checked! disp_msg->valid_window.height = 0; // should be safe, checked! disp_msg->T = 0; // should be safe, checked! disp_msg->f = 0; // should be safe, checked! disp_msg->delta_d = 0; // should be safe, checked! disp_msg->header.stamp = current_timestamp; disp_msg->header.frame_id = ros::this_node::getName(); disp_msg->header.seq = progress.count(); sensor_msgs::Image& dimage = disp_msg->image; dimage.width = cv_image04.size().width ; dimage.height = cv_image04.size().height ; dimage.encoding = sensor_msgs::image_encodings::TYPE_32FC1; dimage.step = dimage.width * sizeof(float); dimage.data.resize(dimage.step * dimage.height); cv::Mat_<float> dmat(dimage.height, dimage.width, reinterpret_cast<float*>(&dimage.data[0]), dimage.step); cv_image04.convertTo(dmat,dmat.type()); disp_pub.publish(disp_msg); } /* if(options.laneDetections) { //msgLanes; //msgSingleLaneInfo; string file=dir_laneDetections+boost::str(boost::format("%010d") % entries_played )+".txt"; if(getLaneDetection(file,&msgLanes)) { msgLanes.header.stamp = current_timestamp; msgLanes.header.frame_id = ros::this_node::getName(); lanes_pub.publish(msgLanes); } if (options.viewDisparities) { full_filename_laneProjected = dir_laneProjected + boost::str(boost::format("%010d") % entries_played ) + ".png"; cv_laneProjected = cv::imread(full_filename_laneProjected, CV_LOAD_IMAGE_UNCHANGED); cv::imshow("Reprojection of Detected Lines",cv_laneProjected); cv::waitKey(5); } } */ if(options.color || options.all_data) { full_filename_image02 = dir_image02 + boost::str(boost::format("%010d") % entries_played ) + ".png"; full_filename_image03 = dir_image03 + boost::str(boost::format("%010d") % entries_played ) + ".png"; ROS_DEBUG_STREAM ( full_filename_image02 << endl << full_filename_image03 << endl << endl); cv_image02 = cv::imread(full_filename_image02, CV_LOAD_IMAGE_UNCHANGED); cv_image03 = cv::imread(full_filename_image03, CV_LOAD_IMAGE_UNCHANGED); if ( (cv_image02.data == NULL) || (cv_image03.data == NULL) ){ ROS_ERROR_STREAM("Error reading color images (02 & 03)"); ROS_ERROR_STREAM(full_filename_image02 << endl << full_filename_image03); node.shutdown(); return -1; } if(options.viewer) { //display the left image only cv::imshow("CameraSimulator Color Viewer",cv_image02); //give some time to draw images cv::waitKey(5); } cv_bridge_img.encoding = sensor_msgs::image_encodings::BGR8; cv_bridge_img.header.frame_id = "camera"; //ros::this_node::getName(); if (!options.timestamps) { cv_bridge_img.header.stamp = current_timestamp ; ros_msg02.header.stamp = ros_cameraInfoMsg_camera02.header.stamp = cv_bridge_img.header.stamp; } else { str_support = dir_timestamp_image02 + "timestamps.txt"; ifstream timestamps(str_support.c_str()); if (!timestamps.is_open()) { string timestamps_string; timestamps >> timestamps_string; ROS_ERROR_STREAM("Fail to open " << timestamps_string); node.shutdown(); return -1; } timestamps.seekg(30*entries_played); getline(timestamps,str_support); cv_bridge_img.header.stamp = parseTime(str_support).stamp; ros_msg02.header.stamp = ros_cameraInfoMsg_camera02.header.stamp = cv_bridge_img.header.stamp; } cv_bridge_img.image = cv_image02; cv_bridge_img.toImageMsg(ros_msg02); if (!options.timestamps) { cv_bridge_img.header.stamp = current_timestamp; ros_msg03.header.stamp = ros_cameraInfoMsg_camera03.header.stamp = cv_bridge_img.header.stamp; } else { str_support = dir_timestamp_image03 + "timestamps.txt"; ifstream timestamps(str_support.c_str()); if (!timestamps.is_open()) { string timestamps_string; timestamps >> timestamps_string; ROS_ERROR_STREAM("Fail to open " << timestamps_string); node.shutdown(); return -1; } timestamps.seekg(30*entries_played); getline(timestamps,str_support); cv_bridge_img.header.stamp = parseTime(str_support).stamp; ros_msg03.header.stamp = ros_cameraInfoMsg_camera03.header.stamp = cv_bridge_img.header.stamp; } cv_bridge_img.image = cv_image03; cv_bridge_img.toImageMsg(ros_msg03); pub02.publish(ros_msg02,ros_cameraInfoMsg_camera02); pub03.publish(ros_msg03,ros_cameraInfoMsg_camera03); } if(options.grayscale || options.all_data) { full_filename_image00 = dir_image00 + boost::str(boost::format("%010d") % entries_played ) + ".png"; full_filename_image01 = dir_image01 + boost::str(boost::format("%010d") % entries_played ) + ".png"; ROS_DEBUG_STREAM ( full_filename_image00 << endl << full_filename_image01 << endl << endl); cv_image00 = cv::imread(full_filename_image00, CV_LOAD_IMAGE_UNCHANGED); cv_image01 = cv::imread(full_filename_image01, CV_LOAD_IMAGE_UNCHANGED); if ( (cv_image00.data == NULL) || (cv_image01.data == NULL) ){ ROS_ERROR_STREAM("Error reading color images (00 & 01)"); ROS_ERROR_STREAM(full_filename_image00 << endl << full_filename_image01); node.shutdown(); return -1; } if(options.viewer) { //display the left image only cv::imshow("CameraSimulator Grayscale Viewer",cv_image00); //give some time to draw images cv::waitKey(5); } cv_bridge_img.encoding = sensor_msgs::image_encodings::MONO8; cv_bridge_img.header.frame_id = "camera"; //ros::this_node::getName(); if (!options.timestamps) { cv_bridge_img.header.stamp = current_timestamp; ros_msg00.header.stamp = ros_cameraInfoMsg_camera00.header.stamp = cv_bridge_img.header.stamp; } else { str_support = dir_timestamp_image02 + "timestamps.txt"; ifstream timestamps(str_support.c_str()); if (!timestamps.is_open()) { string timestamps_string; timestamps >> timestamps_string; ROS_ERROR_STREAM("Fail to open " << timestamps_string); node.shutdown(); return -1; } timestamps.seekg(30*entries_played); getline(timestamps,str_support); cv_bridge_img.header.stamp = parseTime(str_support).stamp; ros_msg00.header.stamp = ros_cameraInfoMsg_camera00.header.stamp = cv_bridge_img.header.stamp; } cv_bridge_img.image = cv_image00; cv_bridge_img.toImageMsg(ros_msg00); if (!options.timestamps) { cv_bridge_img.header.stamp = current_timestamp; ros_msg01.header.stamp = ros_cameraInfoMsg_camera01.header.stamp = cv_bridge_img.header.stamp; } else { str_support = dir_timestamp_image02 + "timestamps.txt"; ifstream timestamps(str_support.c_str()); if (!timestamps.is_open()) { string timestamps_string; timestamps >> timestamps_string; ROS_ERROR_STREAM("Fail to open " << timestamps_string); node.shutdown(); return -1; } timestamps.seekg(30*entries_played); getline(timestamps,str_support); cv_bridge_img.header.stamp = parseTime(str_support).stamp; ros_msg01.header.stamp = ros_cameraInfoMsg_camera01.header.stamp = cv_bridge_img.header.stamp; } cv_bridge_img.image = cv_image01; cv_bridge_img.toImageMsg(ros_msg01); pub00.publish(ros_msg00,ros_cameraInfoMsg_camera00); pub01.publish(ros_msg01,ros_cameraInfoMsg_camera01); } if(options.velodyne || options.all_data) { header_support.stamp = current_timestamp; full_filename_velodyne = dir_velodyne_points + boost::str(boost::format("%010d") % entries_played ) + ".bin"; if (!options.timestamps) publish_velodyne(map_pub, full_filename_velodyne,&header_support); else { str_support = dir_timestamp_velodyne + "timestamps.txt"; ifstream timestamps(str_support.c_str()); if (!timestamps.is_open()) { string timestamps_string; timestamps >> timestamps_string; ROS_ERROR_STREAM("Fail to open " << timestamps_string); node.shutdown(); return -1; } timestamps.seekg(30*entries_played); getline(timestamps,str_support); header_support.stamp = parseTime(str_support).stamp; header_support.seq = progress.count(); publish_velodyne(map_pub, full_filename_velodyne,&header_support); } } if(options.gps || options.all_data) { header_support.stamp = current_timestamp; //ros::Time::now(); if (options.timestamps) { str_support = dir_timestamp_oxts + "timestamps.txt"; ifstream timestamps(str_support.c_str()); if (!timestamps.is_open()) { string timestamps_string; timestamps >> timestamps_string; ROS_ERROR_STREAM("Fail to open " << timestamps_string); node.shutdown(); return -1; } timestamps.seekg(30*entries_played); getline(timestamps,str_support); header_support.stamp = parseTime(str_support).stamp; } full_filename_oxts = dir_oxts + boost::str(boost::format("%010d") % entries_played ) + ".txt"; if (!getGPS(full_filename_oxts,&ros_msgGpsFix,&header_support)) { ROS_ERROR_STREAM("Fail to open " << full_filename_oxts); node.shutdown(); return -1; } if (firstGpsData) { ROS_DEBUG_STREAM("Setting initial GPS fix at " << endl << ros_msgGpsFix); firstGpsData = false; ros_msgGpsFixInitial = ros_msgGpsFix; ros_msgGpsFixInitial.header.frame_id = "/local_map"; ros_msgGpsFixInitial.altitude = 0.0f; } gps_pub.publish(ros_msgGpsFix); gps_pub_initial.publish(ros_msgGpsFixInitial); } if(options.imu || options.all_data) { header_support.stamp = current_timestamp; //ros::Time::now(); if (options.timestamps) { str_support = dir_timestamp_oxts + "timestamps.txt"; ifstream timestamps(str_support.c_str()); if (!timestamps.is_open()) { string timestamps_string; timestamps >> timestamps_string; ROS_ERROR_STREAM("Fail to open " << timestamps_string); node.shutdown(); return -1; } timestamps.seekg(30*entries_played); getline(timestamps,str_support); header_support.stamp = parseTime(str_support).stamp; } full_filename_oxts = dir_oxts + boost::str(boost::format("%010d") % entries_played ) + ".txt"; if (!getIMU(full_filename_oxts,&ros_msgImu,&header_support)) { ROS_ERROR_STREAM("Fail to open " << full_filename_oxts); node.shutdown(); return -1; } imu_pub.publish(ros_msgImu); } ++progress; entries_played++; loop_rate.sleep(); } while(entries_played<=total_entries-1 && ros::ok()); if(options.viewer) { ROS_INFO_STREAM(" Closing CV viewer(s)"); if(options.color || options.all_data) cv::destroyWindow("CameraSimulator Color Viewer"); if(options.grayscale || options.all_data) cv::destroyWindow("CameraSimulator Grayscale Viewer"); if (options.viewDisparities) cv::destroyWindow("Reprojection of Detected Lines"); ROS_INFO_STREAM(" Closing CV viewer(s)... OK"); } ROS_INFO_STREAM("Done!"); node.shutdown(); return 0; }
57,751
18,809
/* * Logger.cpp * * function: Logger Singleton for logging with different log levels to a file * * author: Jannik Beyerstedt */ #include "Logger.h" #include <iomanip> Logger::Logger() { logfile.open("logfile.txt", std::ios::trunc); logfile << std::setprecision(3) << std::fixed; time_start = std::chrono::high_resolution_clock::now(); logLevel = ERROR; } Logger::~Logger() { logfile.close(); } void Logger::setLogLevel(log_t logLevel) { this->logLevel = logLevel; } log_t Logger::getLogLevel() { return logLevel; } std::ofstream& Logger::log(log_t logType) { std::chrono::duration<double, std::milli> timediff_ms = std::chrono::high_resolution_clock::now() - time_start; auto time = std::chrono::system_clock::now(); logfile << std::chrono::system_clock::to_time_t(time) << " (" << timediff_ms.count() << ") [" << logType << "] "; return logfile; } std::ofstream& Logger::log() { std::chrono::duration<double, std::milli> timediff_ms = std::chrono::high_resolution_clock::now() - time_start; auto time = std::chrono::system_clock::now(); logfile << std::chrono::system_clock::to_time_t(time) << " (" << timediff_ms.count() << ") "; return logfile; } LogScope::LogScope(const std::string& s) : logger(Logger::getLogger()), s_(s) { if (!(Logger::getLogger().getLogLevel() < DEBUG)) { logger.log(DEBUG) << "entering function " << s_ << "\n"; } } LogScope::~LogScope() { if (!(Logger::getLogger().getLogLevel() < DEBUG)) { logger.log(DEBUG) << "exiting function " << s_ << "\n"; } }
1,548
569
// https://www.urionlinejudge.com.br/judge/en/problems/view/1789 #include <iostream> using namespace std; int main() { int n, x, faster = 0; while (scanf("%d", &n) != EOF) { while (n--) { cin >> x; if (x > faster) faster = x; } if (faster < 10) cout << 1 << endl; else if (faster < 20) cout << 2 << endl; else cout << 3 << endl; faster = 0; } return 0; }
386
190
//###include "../01_cpp_lib/hongyulib.h" #include <iostream> // std::cout #include <algorithm> // std::unique, std::distance #include <vector> // std::vector bool myfunction (int i, int j) { return (i==j); } using namespace std; int main () { int myints[] = {10,20,20,20,30,30,20,20,10}; // 10 20 20 20 30 30 20 20 10 string mystrings[] = {"me", "the_me", "me", "me","me", "the_me"}; //##std::vector<int> myvector (myints,myints+9); //##vector<string> mystringvector ( mystrings, mystrings+5); vector<string> mystringvector(mystrings,mystrings+6); // using default comparison: //##std::vector<int>::iterator it; vector<string>:: iterator it; //it = std::unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 ? ? ? ? // ^ //it = unique( mystringvector.begin(), mystringvector.end()); it = unique( mystringvector.begin(), mystringvector.end()); //yvector.resize( std::distance(myvector.begin(),it) ); // 10 20 30 20 10 mystringvector.resize(distance(mystringvector.begin() , it)); // using predicate comparison: //##std::unique (myvector.begin(), myvector.end(), myfunction); // (no changes) // print out content: std::cout << "myvector contains:"; for (it=mystringvector.begin(); it!=mystringvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; }
1,421
525
/******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "jit_avx2_kernel_sgemm_kern.hpp" #ifdef _WIN32 static const bool is_windows = true; #else static const bool is_windows = false; #endif namespace mkldnn { namespace impl { namespace cpu { int jit_avx2_kernel_sgemm_kern::next_acc(int idx, int um, int un) { while (!(((idx / unroll_n_) < std::max(1, um / nelt_per_vecreg_)) || ((idx % unroll_n_) < un))) idx++; return idx; } void jit_avx2_kernel_sgemm_kern::prefetchB_beforeBload( int um, int un, int k_idx, int n_idx) { if (!mayiuse(avx512_core)) { if ((n_idx == 0) && (k_idx == 0) && (un == unroll_n_) && (um != 16)) { prefetcht0(ptr[BO_ + elt_size_ * (PREFETCHSIZEB_ + offb_)]); offb_ += 16; } } } void jit_avx2_kernel_sgemm_kern::prefetchB_beforeFMA( int um, int un, int k_idx, int n_idx, int m_idx) { if (!mayiuse(avx512_core)) { if ((um == 16) || (un < unroll_n_)) { if ((k_idx + m_idx + n_idx) == 0) { prefetcht0(ptr[BO_ + elt_size_ * (PREFETCHSIZEB_ + offb_)]); offb_ += 16; } if ((um == 16) && (un == 4) && (k_idx == 2) && ((m_idx + n_idx) == 0)) { prefetcht0(ptr[BO_ + elt_size_ * (PREFETCHSIZEB_ + offb_)]); offb_ += 16; } } } } void jit_avx2_kernel_sgemm_kern::prefetchA_afterFMA( int um, int un, int k_idx, int n_idx, int m_idx) { if (mayiuse(avx512_core)) { if ((um < unroll_m_) && (m_idx == 0)) { if (((k_idx % (nb_zmm_a_ / unroll_m_reg_) == 0) && (n_idx % 6 == 0)) || ((k_idx % (nb_zmm_a_ / unroll_m_reg_) == 1) && (n_idx == 3))) { prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } } } else { if (un == unroll_n_) { if (((um < nelt_per_vecreg_) && (n_idx == 0) && (k_idx == std::min(2, nelt_per_vecreg_ / um - 1))) || ((um == nelt_per_vecreg_) && (un == unroll_n_) && (n_idx == 1) && (k_idx == 0))) { prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } } } } void jit_avx2_kernel_sgemm_kern::prefetchA_afterBload( int um, int un, int k_idx, int n_idx) { if (!mayiuse(avx512_core)) { if ((um == unroll_m_) && (un == 2)) { if (k_idx % 3 == 0) { if (n_idx == 1) { if (k_idx == 0) off_ += 16; prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } if ((k_idx == 0) && (n_idx == 0)) { prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } } else { if (n_idx == 1) { prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } } } } } void jit_avx2_kernel_sgemm_kern::prefetchB_afterFMA( int k_idx, int n_idx, int m_idx) { if (mayiuse(avx512_core)) { if (((m_idx + (k_idx % (nb_zmm_a_ / unroll_m_reg_)) * unroll_m_reg_) == 0) && (n_idx == 1)) { prefetcht0(ptr[BO_ + elt_size_ * (PREFETCHSIZEB_ + nelt_per_vecreg_ * k_idx / (nb_zmm_a_ / unroll_m_reg_))]); } } } void jit_avx2_kernel_sgemm_kern::prefetchA_beforeFMA( int um, int un, int k_idx, int n_idx, int m_idx) { if (!mayiuse(avx512_core)) { if ((um == unroll_m_) && (un == unroll_n_)) { if (((k_idx == 0) && (n_idx % 2 == 1) && (m_idx == 0)) || ((k_idx == 1) && (n_idx == 2) && (m_idx == 0)) || ((k_idx == 2) && (n_idx == 0) && (m_idx == 2)) || ((k_idx == 2) && (n_idx == 3) && (m_idx == 0)) || ((k_idx == 3) && (n_idx == 1) && (m_idx == 0))) { prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } } if ((um == unroll_m_) && (un == 1)) { if (m_idx == 2) { prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } else if ((m_idx == 0) && ((k_idx == 1) || (k_idx == 2))) { prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } } if ((um == 16) && (un == unroll_n_) && (m_idx == 0) && (n_idx == 2)) { prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } if ((um == 8) && (un == unroll_n_) && (m_idx == 0) && (n_idx == 1) && (k_idx == 2)) { prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]); off_ += 16; } } } void jit_avx2_kernel_sgemm_kern::prefetchC_afterBload( int um, int un, int k_idx, int n_idx) { if (mayiuse(avx512_core)) { if (um == unroll_m_) { if (n_idx == std::min(1, un - 1)) { if (k_idx == unroll_k_ - 1) lea(CO2_, ptr[CO2_ + LDC_]); else prefetchw(ptr[CO2_ + elt_size_ * k_idx * nelt_per_vecreg_]); } } } } void jit_avx2_kernel_sgemm_kern::prefetchC_beforeKloop(int um) { if (mayiuse(avx512_core)) { if (um < unroll_m_) { prefetchw(ptr[CO2_ + elt_size_ * 0]); prefetchw(ptr[CO2_ + elt_size_ * 8]); if (um <= 16) prefetchw(ptr[CO2_ + elt_size_ * 16]); lea(CO2_, ptr[CO2_ + LDC_]); } } else { prefetcht2(ptr[AA_ - 16 * elt_size_]); prefetcht0(ptr[CO1_ + 7 * elt_size_]); prefetcht0(ptr[CO1_ + LDC_ + 7 * elt_size_]); prefetcht0(ptr[CO2_ + 7 * elt_size_]); prefetcht0(ptr[CO2_ + LDC_ + 7 * elt_size_]); prefetcht0(ptr[CO1_ + 23 * elt_size_]); prefetcht0(ptr[CO1_ + LDC_ + 23 * elt_size_]); prefetcht0(ptr[CO2_ + 23 * elt_size_]); prefetcht0(ptr[CO2_ + LDC_ + 23 * elt_size_]); add(LL_, second_fetch_); prefetcht2(ptr[AA_]); } } void jit_avx2_kernel_sgemm_kern::generate() { int i, unroll_x, unroll_y, uy_bin, ux_bin; int C_off = is_windows ? 56 : 8; int LDC_off = is_windows ? 64 : 16; int sepload = 0; Xbyak::Label unroll_x_label[MAX_UNROLL_M], unroll_y_label[(MAX_UNROLL_N_BIN + 1) * MAX_UNROLL_M]; Xbyak::Label end_n_loop_label[MAX_UNROLL_M], end_m_loop_label; preamble(); if (is_windows) { mov(M_, ptr[rcx]); mov(N_, ptr[rdx]); mov(K_, ptr[r8]); mov(A_, ptr[rsp + get_size_of_abi_save_regs() + 40]); mov(B_, ptr[rsp + get_size_of_abi_save_regs() + 48]); } else { mov(M_, ptr[M_]); mov(N_, ptr[N_]); mov(K_, ptr[K_]); } mov(C_, ptr[rsp + get_size_of_abi_save_regs() + C_off]); mov(LDC_, ptr[rsp + get_size_of_abi_save_regs() + LDC_off]); if (mayiuse(avx512_core)) { for (i = zmm_acc_idx_; i < unroll_m_reg_ * unroll_n_ + zmm_acc_idx_; i++) vpxorq(Xbyak::Zmm(i), Xbyak::Zmm(i), Xbyak::Zmm(i)); } sub(A_, -addr_off_ * elt_size_); sub(B_, -addr_off_ * elt_size_); sal(LDC_, elt_size_bin_); for (unroll_x = unroll_m_, i = 0, ux_bin = unroll_m_bin_; unroll_x >= 1; unroll_x -= std::min(nelt_per_vecreg_, std::max(1, unroll_x / 2)), i++, ux_bin--) { if (unroll_x == unroll_m_) { mov(J_, M_); cmp(J_, unroll_m_); jl(unroll_x_label[i + 1], T_NEAR); L_aligned(unroll_x_label[i]); } else { L_aligned(unroll_x_label[i]); test(J_, unroll_x); if (unroll_x > 1) jle(unroll_x_label[i + 1], T_NEAR); else jle(end_m_loop_label, T_NEAR); } mov(AA_, KK_); if ((1 << ux_bin) > unroll_x) imul(AA_, AA_, unroll_x * elt_size_); else sal(AA_, elt_size_bin_ + ux_bin); add(AA_, A_); mov(CO1_, C_); if ((unroll_x == unroll_m_) || (!mayiuse(avx512_core))) lea(CO2_, ptr[C_ + LDC_ * 2]); add(C_, unroll_x * elt_size_); mov(BO_, B_); for (unroll_y = unroll_n_, uy_bin = unroll_n_bin_; unroll_y >= 1; unroll_y /= 2, uy_bin--) { if (unroll_y == unroll_n_) { mov(I_, N_); sar(I_, uy_bin); jle(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin - 1], T_NEAR); L_aligned(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin]); } else { L_aligned(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin]); test(N_, unroll_y); if (uy_bin == 0) jle(end_n_loop_label[i], T_NEAR); else jle(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin - 1], T_NEAR); } if (!mayiuse(avx512_core)) prefetcht2(ptr[AA_ - addr_off_ * elt_size_]); switch (unroll_x) { case 8: if (mayiuse(avx512_core)) { loop<Xbyak::Zmm, Xbyak::Zmm, Xbyak::Address, Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vbroadcastf64x4, &Xbyak::CodeGenerator::vbroadcastss); update<Xbyak::Ymm, Xbyak::Operand>(unroll_x, unroll_y, 0, beta_zero_, &Xbyak::CodeGenerator::vaddps, &Xbyak::CodeGenerator::vmovups, &Xbyak::CodeGenerator::vmovups); } else { loop<Xbyak::Ymm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vmovups, &Xbyak::CodeGenerator::vbroadcastss); update<Xbyak::Ymm, Xbyak::Operand>(unroll_x, unroll_y, 1, beta_zero_, &Xbyak::CodeGenerator::vaddps, &Xbyak::CodeGenerator::vmovups, &Xbyak::CodeGenerator::vmovups); } break; case 4: if (mayiuse(avx512_core)) { loop<Xbyak::Zmm, Xbyak::Ymm, Xbyak::Address, Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vbroadcastf32x4, &Xbyak::CodeGenerator::vbroadcastss); sepload = 0; } else { loop<Xbyak::Xmm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vmovups, &Xbyak::CodeGenerator::vbroadcastss); sepload = 1; } update<Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, sepload, beta_zero_, &Xbyak::CodeGenerator::vaddps, &Xbyak::CodeGenerator::vmovups, &Xbyak::CodeGenerator::vmovups); break; case 2: if (mayiuse(avx512_core)) { loop<Xbyak::Zmm, Xbyak::Ymm, Xbyak::Operand, Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vbroadcastsd, &Xbyak::CodeGenerator::vbroadcastss); } else { loop<Xbyak::Xmm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vmovddup, &Xbyak::CodeGenerator::vbroadcastss); } update<Xbyak::Xmm, Xbyak::Address>(unroll_x, unroll_y, 1, beta_zero_, &Xbyak::CodeGenerator::vaddps, &Xbyak::CodeGenerator::vmovlps, &Xbyak::CodeGenerator::vmovsd); break; case 1: if (mayiuse(avx512_core)) { loop<Xbyak::Zmm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vbroadcastss, &Xbyak::CodeGenerator::vbroadcastss); sepload = 0; } else { loop<Xbyak::Xmm, Xbyak::Xmm, Xbyak::Address, Xbyak::Xmm, Xbyak::Address>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vmovss, &Xbyak::CodeGenerator::vmovss); sepload = 1; } update<Xbyak::Xmm, Xbyak::Address>(unroll_x, unroll_y, sepload, beta_zero_, &Xbyak::CodeGenerator::vaddss, &Xbyak::CodeGenerator::vmovss, &Xbyak::CodeGenerator::vmovss); break; default: if (mayiuse(avx512_core)) { loop<Xbyak::Zmm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vmovups, &Xbyak::CodeGenerator::vbroadcastss); update<Xbyak::Zmm, Xbyak::Operand>(unroll_x, unroll_y, 0, beta_zero_, &Xbyak::CodeGenerator::vaddps, &Xbyak::CodeGenerator::vmovups, &Xbyak::CodeGenerator::vmovups); } else { loop<Xbyak::Ymm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, &Xbyak::CodeGenerator::vmovups, &Xbyak::CodeGenerator::vbroadcastss); update<Xbyak::Ymm, Xbyak::Operand>(unroll_x, unroll_y, 1, beta_zero_, &Xbyak::CodeGenerator::vaddps, &Xbyak::CodeGenerator::vmovups, &Xbyak::CodeGenerator::vmovups); } break; } if (mayiuse(avx512_core)) { sub(AA_, -16 * elt_size_); } else { if ((unroll_y != unroll_n_) || (unroll_x <= 4)) { if (unroll_x == unroll_m_) sub(AA_, -16 * elt_size_); else sub(AA_, -32 * elt_size_); } else sub(AA_, -48 * elt_size_); } if (unroll_y == unroll_n_) { dec(I_); jg(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin], T_NEAR); } } L_aligned(end_n_loop_label[i]); mov(A_, AO_); if (unroll_x == unroll_m_) { sub(J_, unroll_x); cmp(J_, unroll_x); jge(unroll_x_label[i], T_NEAR); } } L_aligned(end_m_loop_label); postamble(); } jit_avx2_kernel_sgemm_kern::jit_avx2_kernel_sgemm_kern(bool beta_zero) : jit_generator(nullptr, 65536) { beta_zero_ = beta_zero; generate(); } } } }
16,716
6,237
// Copyright (c) 2001-2011 Hartmut Kaiser // // 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) #if !defined(SPIRIT_LEX_SUPPORT_FUNCTIONS_JUN_08_2009_0211PM) #define SPIRIT_LEX_SUPPORT_FUNCTIONS_JUN_08_2009_0211PM #if defined(_MSC_VER) #pragma once #endif #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/home/support/detail/scoped_enum_emulation.hpp> #include <boost/spirit/home/lex/lexer/pass_flags.hpp> #include <boost/spirit/home/lex/lexer/support_functions_expression.hpp> /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { namespace lex { /////////////////////////////////////////////////////////////////////////// // The function object less_type is used by the implementation of the // support function lex::less(). Its functionality is equivalent to flex' // function yyless(): it returns an iterator positioned to the nth input // character beyond the current start iterator (i.e. by assigning the // return value to the placeholder '_end' it is possible to return all but // the first n characters of the current token back to the input stream. // // This Phoenix actor is invoked whenever the function lex::less(n) is // used inside a lexer semantic action: // // lex::token_def<> identifier = "[a-zA-Z_][a-zA-Z0-9_]*"; // this->self = identifier [ _end = lex::less(4) ]; // // The example shows how to limit the length of the matched identifier to // four characters. // // Note: the function lex::less() has no effect if used on it's own, you // need to use the returned result in order to make use of its // functionality. template <typename Actor> struct less_type { typedef mpl::true_ no_nullary; template <typename Env> struct result { typedef typename remove_const< typename mpl::at_c<typename Env::args_type, 4>::type >::type context_type; typedef typename context_type::base_iterator_type type; }; template <typename Env> typename result<Env>::type eval(Env const& env) const { typename result<Env>::type it; return fusion::at_c<4>(env.args()).less(it, actor_()); } less_type(Actor const& actor) : actor_(actor) {} Actor actor_; }; // The function lex::less() is used to create a Phoenix actor allowing to // implement functionality similar to flex' function yyless(). template <typename T> inline typename expression::less< typename phoenix::as_actor<T>::type >::type const less(T const& v) { return expression::less<T>::make(phoenix::as_actor<T>::convert(v)); } /////////////////////////////////////////////////////////////////////////// // The function object more_type is used by the implementation of the // support function lex::more(). Its functionality is equivalent to flex' // function yymore(): it tells the lexer that the next time it matches a // rule, the corresponding token should be appended onto the current token // value rather than replacing it. // // This Phoenix actor is invoked whenever the function lex::more(n) is // used inside a lexer semantic action: // // lex::token_def<> identifier = "[a-zA-Z_][a-zA-Z0-9_]*"; // this->self = identifier [ lex::more() ]; // // The example shows how prefix the next matched token with the matched // identifier. struct more_type { typedef mpl::true_ no_nullary; template <typename Env> struct result { typedef void type; }; template <typename Env> void eval(Env const& env) const { fusion::at_c<4>(env.args()).more(); } }; // The function lex::more() is used to create a Phoenix actor allowing to // implement functionality similar to flex' function yymore(). //inline expression::more<mpl::void_>::type const inline phoenix::actor<more_type> more() { return phoenix::actor<more_type>(); } /////////////////////////////////////////////////////////////////////////// // The function object lookahead_type is used by the implementation of the // support function lex::lookahead(). Its functionality is needed to // emulate the flex' lookahead operator a/b. Use lex::lookahead() inside // of lexer semantic actions to test whether the argument to this function // matches the current look ahead input. lex::lookahead() can be used with // either a token id or a token_def instance as its argument. It returns // a bool indicating whether the look ahead has been matched. template <typename IdActor, typename StateActor> struct lookahead_type { typedef mpl::true_ no_nullary; template <typename Env> struct result { typedef bool type; }; template <typename Env> bool eval(Env const& env) const { return fusion::at_c<4>(env.args()). lookahead(id_actor_(), state_actor_()); } lookahead_type(IdActor const& id_actor, StateActor const& state_actor) : id_actor_(id_actor), state_actor_(state_actor) {} IdActor id_actor_; StateActor state_actor_; }; // The function lex::lookahead() is used to create a Phoenix actor // allowing to implement functionality similar to flex' lookahead operator // a/b. template <typename T> inline typename expression::lookahead< typename phoenix::as_actor<T>::type , typename phoenix::as_actor<std::size_t>::type >::type const lookahead(T const& id) { typedef typename phoenix::as_actor<T>::type id_actor_type; typedef typename phoenix::as_actor<std::size_t>::type state_actor_type; return expression::lookahead<id_actor_type, state_actor_type>::make( phoenix::as_actor<T>::convert(id), phoenix::as_actor<std::size_t>::convert(std::size_t(~0))); } template <typename Attribute, typename Char, typename Idtype> inline typename expression::lookahead< typename phoenix::as_actor<Idtype>::type , typename phoenix::as_actor<std::size_t>::type >::type const lookahead(token_def<Attribute, Char, Idtype> const& tok) { typedef typename phoenix::as_actor<Idtype>::type id_actor_type; typedef typename phoenix::as_actor<std::size_t>::type state_actor_type; std::size_t state = tok.state(); // The following assertion fires if you pass a token_def instance to // lex::lookahead without first associating this instance with the // lexer. BOOST_ASSERT(std::size_t(~0) != state && "token_def instance not associated with lexer yet"); return expression::lookahead<id_actor_type, state_actor_type>::make( phoenix::as_actor<Idtype>::convert(tok.id()), phoenix::as_actor<std::size_t>::convert(state)); } /////////////////////////////////////////////////////////////////////////// inline BOOST_SCOPED_ENUM(pass_flags) ignore() { return pass_flags::pass_ignore; } }}} #endif
7,577
2,195
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora, Radu Serban, Jay Taves // ============================================================================= // // Deformable terrain based on SCM (Soil Contact Model) from DLR // (Krenn & Hirzinger) // // ============================================================================= #include <cstdio> #include <cmath> #include <queue> #include <unordered_set> #include <limits> #include <omp.h> #include "chrono/physics/ChMaterialSurfaceNSC.h" #include "chrono/physics/ChMaterialSurfaceSMC.h" #include "chrono/assets/ChTexture.h" #include "chrono/assets/ChBoxShape.h" #include "chrono/utils/ChConvexHull.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/terrain/SCMDeformableTerrain.h" #include "chrono_thirdparty/stb/stb.h" namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- // Implementation of the SCMDeformableTerrain wrapper class // ----------------------------------------------------------------------------- SCMDeformableTerrain::SCMDeformableTerrain(ChSystem* system, bool visualization_mesh) { m_ground = chrono_types::make_shared<SCMDeformableSoil>(system, visualization_mesh); system->Add(m_ground); } // Get the initial terrain height below the specified location. double SCMDeformableTerrain::GetInitHeight(const ChVector<>& loc) const { return m_ground->GetInitHeight(loc); } // Get the initial terrain normal at the point below the specified location. ChVector<> SCMDeformableTerrain::GetInitNormal(const ChVector<>& loc) const { return m_ground->GetInitNormal(loc); } // Get the terrain height below the specified location. double SCMDeformableTerrain::GetHeight(const ChVector<>& loc) const { return m_ground->GetHeight(loc); } // Get the terrain normal at the point below the specified location. ChVector<> SCMDeformableTerrain::GetNormal(const ChVector<>& loc) const { return m_ground->GetNormal(loc); } // Return the terrain coefficient of friction at the specified location. float SCMDeformableTerrain::GetCoefficientFriction(const ChVector<>& loc) const { return m_friction_fun ? (*m_friction_fun)(loc) : 0.8f; } // Set the color of the visualization assets. void SCMDeformableTerrain::SetColor(const ChColor& color) { if (m_ground->m_color) m_ground->m_color->SetColor(color); } // Set the texture and texture scaling. void SCMDeformableTerrain::SetTexture(const std::string tex_file, float tex_scale_x, float tex_scale_y) { std::shared_ptr<ChTexture> texture(new ChTexture); texture->SetTextureFilename(tex_file); texture->SetTextureScale(tex_scale_x, tex_scale_y); m_ground->AddAsset(texture); } // Set the SCM reference plane. void SCMDeformableTerrain::SetPlane(const ChCoordsys<>& plane) { m_ground->m_plane = plane; m_ground->m_Z = plane.rot.GetZaxis(); } // Get the SCM reference plane. const ChCoordsys<>& SCMDeformableTerrain::GetPlane() const { return m_ground->m_plane; } // Set the visualization mesh as wireframe or as solid. void SCMDeformableTerrain::SetMeshWireframe(bool val) { if (m_ground->m_trimesh_shape) m_ground->m_trimesh_shape->SetWireframe(val); } // Get the trimesh that defines the ground shape. std::shared_ptr<ChTriangleMeshShape> SCMDeformableTerrain::GetMesh() const { return m_ground->m_trimesh_shape; } // Save the visualization mesh as a Wavefront OBJ file. void SCMDeformableTerrain::WriteMesh(const std::string& filename) const { if (!m_ground->m_trimesh_shape) { std::cout << "SCMDeformableTerrain::WriteMesh -- visualization mesh not created."; return; } auto trimesh = m_ground->m_trimesh_shape->GetMesh(); std::vector<geometry::ChTriangleMeshConnected> meshes = {*trimesh}; trimesh->WriteWavefront(filename, meshes); } // Set properties of the SCM soil model. void SCMDeformableTerrain::SetSoilParameters( double Bekker_Kphi, // Kphi, frictional modulus in Bekker model double Bekker_Kc, // Kc, cohesive modulus in Bekker model double Bekker_n, // n, exponent of sinkage in Bekker model (usually 0.6...1.8) double Mohr_cohesion, // Cohesion for shear failure [Pa] double Mohr_friction, // Friction angle for shear failure [degree] double Janosi_shear, // Shear parameter in Janosi-Hanamoto formula [m] double elastic_K, // elastic stiffness K per unit area, [Pa/m] (must be larger than Kphi) double damping_R // vertical damping R per unit area [Pa.s/m] (proportional to vertical speed) ) { m_ground->m_Bekker_Kphi = Bekker_Kphi; m_ground->m_Bekker_Kc = Bekker_Kc; m_ground->m_Bekker_n = Bekker_n; m_ground->m_Mohr_cohesion = Mohr_cohesion; m_ground->m_Mohr_mu = std::tan(Mohr_friction * CH_C_DEG_TO_RAD); m_ground->m_Janosi_shear = Janosi_shear; m_ground->m_elastic_K = ChMax(elastic_K, Bekker_Kphi); m_ground->m_damping_R = damping_R; } // Enable/disable bulldozing effect. void SCMDeformableTerrain::EnableBulldozing(bool val) { m_ground->m_bulldozing = val; } // Set parameters controlling the creation of side ruts (bulldozing effects). void SCMDeformableTerrain::SetBulldozingParameters( double erosion_angle, // angle of erosion of the displaced material [degrees] double flow_factor, // growth of lateral volume relative to pressed volume int erosion_iterations, // number of erosion refinements per timestep int erosion_propagations // number of concentric vertex selections subject to erosion ) { m_ground->m_flow_factor = flow_factor; m_ground->m_erosion_slope = std::tan(erosion_angle * CH_C_DEG_TO_RAD); m_ground->m_erosion_iterations = erosion_iterations; m_ground->m_erosion_propagations = erosion_propagations; } void SCMDeformableTerrain::SetTestHeight(double offset) { m_ground->m_test_offset_up = offset; } double SCMDeformableTerrain::GetTestHeight() const { return m_ground->m_test_offset_up; } // Set the color plot type. void SCMDeformableTerrain::SetPlotType(DataPlotType plot_type, double min_val, double max_val) { m_ground->m_plot_type = plot_type; m_ground->m_plot_v_min = min_val; m_ground->m_plot_v_max = max_val; } // Enable moving patch. void SCMDeformableTerrain::AddMovingPatch(std::shared_ptr<ChBody> body, const ChVector<>& OOBB_center, const ChVector<>& OOBB_dims) { SCMDeformableSoil::MovingPatchInfo pinfo; pinfo.m_body = body; pinfo.m_center = OOBB_center; pinfo.m_hdims = OOBB_dims / 2; m_ground->m_patches.push_back(pinfo); // Moving patch monitoring is now enabled m_ground->m_moving_patch = true; } // Set user-supplied callback for evaluating location-dependent soil parameters. void SCMDeformableTerrain::RegisterSoilParametersCallback(std::shared_ptr<SoilParametersCallback> cb) { m_ground->m_soil_fun = cb; } // Initialize the terrain as a flat grid. void SCMDeformableTerrain::Initialize(double sizeX, double sizeY, double delta) { m_ground->Initialize(sizeX, sizeY, delta); } // Initialize the terrain from a specified height map. void SCMDeformableTerrain::Initialize(const std::string& heightmap_file, double sizeX, double sizeY, double hMin, double hMax, double delta) { m_ground->Initialize(heightmap_file, sizeX, sizeY, hMin, hMax, delta); } // Get the heights of modified grid nodes. std::vector<SCMDeformableTerrain::NodeLevel> SCMDeformableTerrain::GetModifiedNodes(bool all_nodes) const { return m_ground->GetModifiedNodes(all_nodes); } // Modify the level of grid nodes from the given list. void SCMDeformableTerrain::SetModifiedNodes(const std::vector<NodeLevel>& nodes) { m_ground->SetModifiedNodes(nodes); } // Return the current cumulative contact force on the specified body (due to interaction with the SCM terrain). TerrainForce SCMDeformableTerrain::GetContactForce(std::shared_ptr<ChBody> body) const { auto itr = m_ground->m_contact_forces.find(body.get()); if (itr != m_ground->m_contact_forces.end()) return itr->second; TerrainForce frc; frc.point = body->GetPos(); frc.force = ChVector<>(0, 0, 0); frc.moment = ChVector<>(0, 0, 0); return frc; } // Return the number of rays cast at last step. int SCMDeformableTerrain::GetNumRayCasts() const { return m_ground->m_num_ray_casts; } // Return the number of ray hits at last step. int SCMDeformableTerrain::GetNumRayHits() const { return m_ground->m_num_ray_hits; } // Return the number of contact patches at last step. int SCMDeformableTerrain::GetNumContactPatches() const { return m_ground->m_num_contact_patches; } // Return the number of nodes in the erosion domain at last step (bulldosing effects). int SCMDeformableTerrain::GetNumErosionNodes() const { return m_ground->m_num_erosion_nodes; } // Timer information double SCMDeformableTerrain::GetTimerMovingPatches() const { return 1e3 * m_ground->m_timer_moving_patches(); } double SCMDeformableTerrain::GetTimerRayTesting() const { return 1e3 * m_ground->m_timer_ray_testing(); } double SCMDeformableTerrain::GetTimerRayCasting() const { return 1e3 * m_ground->m_timer_ray_casting(); } double SCMDeformableTerrain::GetTimerContactPatches() const { return 1e3 * m_ground->m_timer_contact_patches(); } double SCMDeformableTerrain::GetTimerContactForces() const { return 1e3 * m_ground->m_timer_contact_forces(); } double SCMDeformableTerrain::GetTimerBulldozing() const { return 1e3 * m_ground->m_timer_bulldozing(); } double SCMDeformableTerrain::GetTimerVisUpdate() const { return 1e3 * m_ground->m_timer_visualization(); } // Print timing and counter information for last step. void SCMDeformableTerrain::PrintStepStatistics(std::ostream& os) const { os << " Timers (ms):" << std::endl; os << " Moving patches: " << 1e3 * m_ground->m_timer_moving_patches() << std::endl; os << " Ray testing: " << 1e3 * m_ground->m_timer_ray_testing() << std::endl; os << " Ray casting: " << 1e3 * m_ground->m_timer_ray_casting() << std::endl; os << " Contact patches: " << 1e3 * m_ground->m_timer_contact_patches() << std::endl; os << " Contact forces: " << 1e3 * m_ground->m_timer_contact_forces() << std::endl; os << " Bulldozing: " << 1e3 * m_ground->m_timer_bulldozing() << std::endl; os << " Raise boundary: " << 1e3 * m_ground->m_timer_bulldozing_boundary() << std::endl; os << " Compute domain: " << 1e3 * m_ground->m_timer_bulldozing_domain() << std::endl; os << " Apply erosion: " << 1e3 * m_ground->m_timer_bulldozing_erosion() << std::endl; os << " Visualization: " << 1e3 * m_ground->m_timer_visualization() << std::endl; os << " Counters:" << std::endl; os << " Number ray casts: " << m_ground->m_num_ray_casts << std::endl; os << " Number ray hits: " << m_ground->m_num_ray_hits << std::endl; os << " Number contact patches: " << m_ground->m_num_contact_patches << std::endl; os << " Number erosion nodes: " << m_ground->m_num_erosion_nodes << std::endl; } // ----------------------------------------------------------------------------- // Contactable user-data (contactable-soil parameters) // ----------------------------------------------------------------------------- SCMContactableData::SCMContactableData(double area_ratio, double Mohr_cohesion, double Mohr_friction, double Janosi_shear) : area_ratio(area_ratio), Mohr_cohesion(Mohr_cohesion), Mohr_mu(std::tan(Mohr_friction * CH_C_DEG_TO_RAD)), Janosi_shear(Janosi_shear) {} // ----------------------------------------------------------------------------- // Implementation of SCMDeformableSoil // ----------------------------------------------------------------------------- // Constructor. SCMDeformableSoil::SCMDeformableSoil(ChSystem* system, bool visualization_mesh) : m_soil_fun(nullptr) { this->SetSystem(system); if (visualization_mesh) { // Create the visualization mesh and asset m_trimesh_shape = std::shared_ptr<ChTriangleMeshShape>(new ChTriangleMeshShape); m_trimesh_shape->SetWireframe(true); m_trimesh_shape->SetFixedConnectivity(); this->AddAsset(m_trimesh_shape); // Create the default mesh asset m_color = std::shared_ptr<ChColorAsset>(new ChColorAsset); m_color->SetColor(ChColor(0.3f, 0.3f, 0.3f)); this->AddAsset(m_color); } // Default SCM plane and plane normal m_plane = ChCoordsys<>(VNULL, QUNIT); m_Z = m_plane.rot.GetZaxis(); // Bulldozing effects m_bulldozing = false; m_flow_factor = 1.2; m_erosion_slope = std::tan(40.0 * CH_C_DEG_TO_RAD); m_erosion_iterations = 3; m_erosion_propagations = 10; // Default soil parameters m_Bekker_Kphi = 2e6; m_Bekker_Kc = 0; m_Bekker_n = 1.1; m_Mohr_cohesion = 50; m_Mohr_mu = std::tan(20.0 * CH_C_DEG_TO_RAD); m_Janosi_shear = 0.01; m_elastic_K = 50000000; m_damping_R = 0; m_plot_type = SCMDeformableTerrain::PLOT_NONE; m_plot_v_min = 0; m_plot_v_max = 0.2; m_test_offset_up = 0.1; m_test_offset_down = 0.5; m_moving_patch = false; } // Initialize the terrain as a flat grid void SCMDeformableSoil::Initialize(double sizeX, double sizeY, double delta) { m_type = PatchType::FLAT; m_nx = static_cast<int>(std::ceil((sizeX / 2) / delta)); // half number of divisions in X direction m_ny = static_cast<int>(std::ceil((sizeY / 2) / delta)); // number of divisions in Y direction m_delta = sizeX / (2 * m_nx); // grid spacing m_area = std::pow(m_delta, 2); // area of a cell // Return now if no visualization if (!m_trimesh_shape) return; int nvx = 2 * m_nx + 1; // number of grid vertices in X direction int nvy = 2 * m_ny + 1; // number of grid vertices in Y direction int n_verts = nvx * nvy; // total number of vertices for initial visualization trimesh int n_faces = 2 * (2 * m_nx) * (2 * m_ny); // total number of faces for initial visualization trimesh double x_scale = 0.5 / m_nx; // scale for texture coordinates (U direction) double y_scale = 0.5 / m_ny; // scale for texture coordinates (V direction) // Readability aliases auto trimesh = m_trimesh_shape->GetMesh(); trimesh->Clear(); std::vector<ChVector<>>& vertices = trimesh->getCoordsVertices(); std::vector<ChVector<>>& normals = trimesh->getCoordsNormals(); std::vector<ChVector<int>>& idx_vertices = trimesh->getIndicesVertexes(); std::vector<ChVector<int>>& idx_normals = trimesh->getIndicesNormals(); std::vector<ChVector<>>& uv_coords = trimesh->getCoordsUV(); std::vector<ChVector<float>>& colors = trimesh->getCoordsColors(); // Resize mesh arrays vertices.resize(n_verts); normals.resize(n_verts); uv_coords.resize(n_verts); colors.resize(n_verts); idx_vertices.resize(n_faces); idx_normals.resize(n_faces); // Load mesh vertices. // We order the vertices starting at the bottom-left corner, row after row. // The bottom-left corner corresponds to the point (-sizeX/2, -sizeY/2). // UV coordinates are mapped in [0,1] x [0,1]. int iv = 0; for (int iy = 0; iy < nvy; iy++) { double y = iy * m_delta - 0.5 * sizeY; for (int ix = 0; ix < nvx; ix++) { double x = ix * m_delta - 0.5 * sizeX; // Set vertex location vertices[iv] = m_plane * ChVector<>(x, y, 0); // Initialize vertex normal to Y up normals[iv] = m_plane.TransformDirectionLocalToParent(ChVector<>(0, 0, 1)); // Assign color white to all vertices colors[iv] = ChVector<float>(1, 1, 1); // Set UV coordinates in [0,1] x [0,1] uv_coords[iv] = ChVector<>(ix * x_scale, iy * y_scale, 0.0); ++iv; } } // Specify triangular faces (two at a time). // Specify the face vertices counter-clockwise. // Set the normal indices same as the vertex indices. int it = 0; for (int iy = 0; iy < nvy - 1; iy++) { for (int ix = 0; ix < nvx - 1; ix++) { int v0 = ix + nvx * iy; idx_vertices[it] = ChVector<int>(v0, v0 + 1, v0 + nvx + 1); idx_normals[it] = ChVector<int>(v0, v0 + 1, v0 + nvx + 1); ++it; idx_vertices[it] = ChVector<int>(v0, v0 + nvx + 1, v0 + nvx); idx_normals[it] = ChVector<int>(v0, v0 + nvx + 1, v0 + nvx); ++it; } } } // Initialize the terrain from a specified height map. void SCMDeformableSoil::Initialize(const std::string& heightmap_file, double sizeX, double sizeY, double hMin, double hMax, double delta) { m_type = PatchType::HEIGHT_MAP; // Read the image file (request only 1 channel) and extract number of pixels. STB hmap; if (!hmap.ReadFromFile(heightmap_file, 1)) { std::cout << "STB error in reading height map file " << heightmap_file << std::endl; throw ChException("Cannot read height map image file"); } int nx_img = hmap.GetWidth(); int ny_img = hmap.GetHeight(); double dx_img = 1.0 / (nx_img - 1.0); double dy_img = 1.0 / (ny_img - 1.0); m_nx = static_cast<int>(std::ceil((sizeX / 2) / delta)); // half number of divisions in X direction m_ny = static_cast<int>(std::ceil((sizeY / 2) / delta)); // number of divisions in Y direction m_delta = sizeX / (2.0 * m_nx); // grid spacing m_area = std::pow(m_delta, 2); // area of a cell double dx_grid = 0.5 / m_nx; double dy_grid = 0.5 / m_ny; int nvx = 2 * m_nx + 1; // number of grid vertices in X direction int nvy = 2 * m_ny + 1; // number of grid vertices in Y direction int n_verts = nvx * nvy; // total number of vertices for initial visualization trimesh int n_faces = 2 * (2 * m_nx) * (2 * m_ny); // total number of faces for initial visualization trimesh double x_scale = 0.5 / m_nx; // scale for texture coordinates (U direction) double y_scale = 0.5 / m_ny; // scale for texture coordinates (V direction) // Resample image and calculate interpolated gray levels and then map it to the height range, with black // corresponding to hMin and white corresponding to hMax. Entry (0,0) corresponds to bottom-left grid vertex. // Note that pixels in the image start at top-left corner. double h_scale = (hMax - hMin) / hmap.GetRange(); m_heights = ChMatrixDynamic<>(nvx, nvy); for (int ix = 0; ix < nvx; ix++) { double x = ix * dx_grid; // x location in image (in [0,1], 0 at left) int jx1 = (int)std::floor(x / dx_img); // Left pixel int jx2 = (int)std::ceil(x / dx_img); // Right pixel double ax = (x - jx1 * dx_img) / dx_img; // Scaled offset from left pixel assert(ax < 1.0); assert(jx1 < nx_img); assert(jx2 < nx_img); assert(jx1 <= jx2); for (int iy = 0; iy < nvy; iy++) { double y = (2 * m_ny - iy) * dy_grid; // y location in image (in [0,1], 0 at top) int jy1 = (int)std::floor(y / dy_img); // Up pixel int jy2 = (int)std::ceil(y / dy_img); // Down pixel double ay = (y - jy1 * dy_img) / dy_img; // Scaled offset from down pixel assert(ay < 1.0); assert(jy1 < ny_img); assert(jy2 < ny_img); assert(jy1 <= jy2); // Gray levels at left-up, left-down, right-up, and right-down pixels double g11 = hmap.Gray(jx1, jy1); double g12 = hmap.Gray(jx1, jy2); double g21 = hmap.Gray(jx2, jy1); double g22 = hmap.Gray(jx2, jy2); // Bilinear interpolation (gray level) m_heights(ix, iy) = (1 - ax) * (1 - ay) * g11 + (1 - ax) * ay * g12 + ax * (1 - ay) * g21 + ax * ay * g22; // Map into height range m_heights(ix, iy) = hMin + m_heights(ix, iy) * h_scale; } } // Return now if no visualization if (!m_trimesh_shape) return; // Readability aliases auto trimesh = m_trimesh_shape->GetMesh(); trimesh->Clear(); std::vector<ChVector<>>& vertices = trimesh->getCoordsVertices(); std::vector<ChVector<>>& normals = trimesh->getCoordsNormals(); std::vector<ChVector<int>>& idx_vertices = trimesh->getIndicesVertexes(); std::vector<ChVector<int>>& idx_normals = trimesh->getIndicesNormals(); std::vector<ChVector<>>& uv_coords = trimesh->getCoordsUV(); std::vector<ChVector<float>>& colors = trimesh->getCoordsColors(); // Resize mesh arrays. vertices.resize(n_verts); normals.resize(n_verts); uv_coords.resize(n_verts); colors.resize(n_verts); idx_vertices.resize(n_faces); idx_normals.resize(n_faces); // Load mesh vertices. // We order the vertices starting at the bottom-left corner, row after row. // The bottom-left corner corresponds to the point (-sizeX/2, -sizeY/2). // UV coordinates are mapped in [0,1] x [0,1]. Use smoothed vertex normals. int iv = 0; for (int iy = 0; iy < nvy; iy++) { double y = iy * m_delta - 0.5 * sizeY; for (int ix = 0; ix < nvx; ix++) { double x = ix * m_delta - 0.5 * sizeX; // Set vertex location vertices[iv] = m_plane * ChVector<>(x, y, m_heights(ix, iy)); // Initialize vertex normal to Y up normals[iv] = m_plane.TransformDirectionLocalToParent(ChVector<>(0, 0, 1)); // Assign color white to all vertices colors[iv] = ChVector<float>(1, 1, 1); // Set UV coordinates in [0,1] x [0,1] uv_coords[iv] = ChVector<>(ix * x_scale, iy * y_scale, 0.0); ++iv; } } // Specify triangular faces (two at a time). // Specify the face vertices counter-clockwise. // Set the normal indices same as the vertex indices. int it = 0; for (int iy = 0; iy < nvy - 1; iy++) { for (int ix = 0; ix < nvx - 1; ix++) { int v0 = ix + nvx * iy; idx_vertices[it] = ChVector<int>(v0, v0 + 1, v0 + nvx + 1); idx_normals[it] = ChVector<int>(v0, v0 + 1, v0 + nvx + 1); ++it; idx_vertices[it] = ChVector<int>(v0, v0 + nvx + 1, v0 + nvx); idx_normals[it] = ChVector<int>(v0, v0 + nvx + 1, v0 + nvx); ++it; } } // Initialize the array of accumulators (number of adjacent faces to a vertex) std::vector<int> accumulators(n_verts, 0); // Calculate normals and then average the normals from all adjacent faces. for (it = 0; it < n_faces; it++) { // Calculate the triangle normal as a normalized cross product. ChVector<> nrm = Vcross(vertices[idx_vertices[it][1]] - vertices[idx_vertices[it][0]], vertices[idx_vertices[it][2]] - vertices[idx_vertices[it][0]]); nrm.Normalize(); // Increment the normals of all incident vertices by the face normal normals[idx_normals[it][0]] += nrm; normals[idx_normals[it][1]] += nrm; normals[idx_normals[it][2]] += nrm; // Increment the count of all incident vertices by 1 accumulators[idx_normals[it][0]] += 1; accumulators[idx_normals[it][1]] += 1; accumulators[idx_normals[it][2]] += 1; } // Set the normals to the average values. for (int in = 0; in < n_verts; in++) { normals[in] /= (double)accumulators[in]; } } void SCMDeformableSoil::SetupInitial() { // If no user-specified moving patches, create one that will encompass all collision shapes in the system if (!m_moving_patch) { SCMDeformableSoil::MovingPatchInfo pinfo; pinfo.m_body = nullptr; m_patches.push_back(pinfo); } } bool SCMDeformableSoil::CheckMeshBounds(const ChVector2<int>& loc) const { return loc.x() >= -m_nx && loc.x() <= m_nx && loc.y() >= -m_ny && loc.y() <= m_ny; } // Get index of trimesh vertex corresponding to the specified grid vertex. int SCMDeformableSoil::GetMeshVertexIndex(const ChVector2<int>& loc) { assert(loc.x() >= -m_nx); assert(loc.x() <= +m_nx); assert(loc.y() >= -m_ny); assert(loc.y() <= +m_ny); return (loc.x() + m_nx) + (2 * m_nx + 1) * (loc.y() + m_ny); } // Get indices of trimesh faces incident to the specified grid vertex. std::vector<int> SCMDeformableSoil::GetMeshFaceIndices(const ChVector2<int>& loc) { int i = loc.x(); int j = loc.y(); // Ignore boundary vertices if (i == -m_nx || i == m_nx || j == -m_ny || j == m_ny) return std::vector<int>(); // Load indices of 6 adjacent faces i += m_nx; j += m_ny; int nx = 2 * m_nx; std::vector<int> faces(6); faces[0] = 2 * ((i - 1) + nx * (j - 1)); faces[1] = 2 * ((i - 1) + nx * (j - 1)) + 1; faces[2] = 2 * ((i - 1) + nx * (j - 0)); faces[3] = 2 * ((i - 0) + nx * (j - 0)); faces[4] = 2 * ((i - 0) + nx * (j - 0)) + 1; faces[5] = 2 * ((i - 0) + nx * (j - 1)) + 1; return faces; } // Get the initial undeformed terrain height (relative to the SCM plane) at the specified grid vertex. double SCMDeformableSoil::GetInitHeight(const ChVector2<int>& loc) const { switch (m_type) { case PatchType::FLAT: return 0; case PatchType::HEIGHT_MAP: { auto x = ChClamp(loc.x(), -m_nx, +m_nx); auto y = ChClamp(loc.y(), -m_ny, +m_ny); return m_heights(x + m_nx, y + m_ny); } default: return 0; } } // Get the initial undeformed terrain normal (relative to the SCM plane) at the specified grid node. ChVector<> SCMDeformableSoil::GetInitNormal(const ChVector2<int>& loc) const { switch (m_type) { case PatchType::HEIGHT_MAP: { // Average normals of 4 triangular faces incident to given grid node auto hE = GetInitHeight(loc + ChVector2<int>(1, 0)); // east auto hW = GetInitHeight(loc - ChVector2<int>(1, 0)); // west auto hN = GetInitHeight(loc + ChVector2<int>(0, 1)); // north auto hS = GetInitHeight(loc - ChVector2<int>(0, 1)); // south return ChVector<>(hW - hE, hS - hN, 2 * m_delta).GetNormalized(); } case PatchType::FLAT: default: return ChVector<>(0, 0, 1); } } // Get the terrain height (relative to the SCM plane) at the specified grid vertex. double SCMDeformableSoil::GetHeight(const ChVector2<int>& loc) const { // First query the hash-map auto p = m_grid_map.find(loc); if (p != m_grid_map.end()) return p->second.level; // Else return undeformed height return GetInitHeight(loc); } // Get the terrain normal (relative to the SCM plane) at the specified grid vertex. ChVector<> SCMDeformableSoil::GetNormal(const ChVector2<>& loc) const { switch (m_type) { case PatchType::HEIGHT_MAP: { // Average normals of 4 triangular faces incident to given grid node auto hE = GetHeight(loc + ChVector2<int>(1, 0)); // east auto hW = GetHeight(loc - ChVector2<int>(1, 0)); // west auto hN = GetHeight(loc + ChVector2<int>(0, 1)); // north auto hS = GetHeight(loc - ChVector2<int>(0, 1)); // south return ChVector<>(hW - hE, hS - hN, 2 * m_delta).GetNormalized(); } case PatchType::FLAT: default: return ChVector<>(0, 0, 1); } } // Get the initial terrain height below the specified location. double SCMDeformableSoil::GetInitHeight(const ChVector<>& loc) const { // Express location in the SCM frame ChVector<> loc_loc = m_plane.TransformPointParentToLocal(loc); // Get height (relative to SCM plane) at closest grid vertex (approximation) int i = static_cast<int>(std::round(loc_loc.x() / m_delta)); int j = static_cast<int>(std::round(loc_loc.y() / m_delta)); loc_loc.z() = GetInitHeight(ChVector2<int>(i, j)); // Express in global frame ChVector<> loc_abs = m_plane.TransformPointLocalToParent(loc_loc); return ChWorldFrame::Height(loc_abs); } // Get the initial terrain normal at the point below the specified location. ChVector<> SCMDeformableSoil::GetInitNormal(const ChVector<>& loc) const { // Express location in the SCM frame ChVector<> loc_loc = m_plane.TransformPointParentToLocal(loc); // Get height (relative to SCM plane) at closest grid vertex (approximation) int i = static_cast<int>(std::round(loc_loc.x() / m_delta)); int j = static_cast<int>(std::round(loc_loc.y() / m_delta)); auto nrm_loc = GetInitNormal(ChVector2<int>(i, j)); // Express in global frame auto nrm_abs = m_plane.TransformDirectionLocalToParent(nrm_loc); return ChWorldFrame::FromISO(nrm_abs); } // Get the terrain height below the specified location. double SCMDeformableSoil::GetHeight(const ChVector<>& loc) const { // Express location in the SCM frame ChVector<> loc_loc = m_plane.TransformPointParentToLocal(loc); // Get height (relative to SCM plane) at closest grid vertex (approximation) int i = static_cast<int>(std::round(loc_loc.x() / m_delta)); int j = static_cast<int>(std::round(loc_loc.y() / m_delta)); loc_loc.z() = GetHeight(ChVector2<int>(i, j)); // Express in global frame ChVector<> loc_abs = m_plane.TransformPointLocalToParent(loc_loc); return ChWorldFrame::Height(loc_abs); } // Get the terrain normal at the point below the specified location. ChVector<> SCMDeformableSoil::GetNormal(const ChVector<>& loc) const { // Express location in the SCM frame ChVector<> loc_loc = m_plane.TransformPointParentToLocal(loc); // Get height (relative to SCM plane) at closest grid vertex (approximation) int i = static_cast<int>(std::round(loc_loc.x() / m_delta)); int j = static_cast<int>(std::round(loc_loc.y() / m_delta)); auto nrm_loc = GetNormal(ChVector2<int>(i, j)); // Express in global frame auto nrm_abs = m_plane.TransformDirectionLocalToParent(nrm_loc); return ChWorldFrame::FromISO(nrm_abs); } // Synchronize information for a moving patch void SCMDeformableSoil::UpdateMovingPatch(MovingPatchInfo& p, const ChVector<>& Z) { ChVector2<> p_min(+std::numeric_limits<double>::max()); ChVector2<> p_max(-std::numeric_limits<double>::max()); // Loop over all corners of the OOBB for (int j = 0; j < 8; j++) { int ix = j % 2; int iy = (j / 2) % 2; int iz = (j / 4); // OOBB corner in body frame ChVector<> c_body = p.m_center + p.m_hdims * ChVector<>(2.0 * ix - 1, 2.0 * iy - 1, 2.0 * iz - 1); // OOBB corner in absolute frame ChVector<> c_abs = p.m_body->GetFrame_REF_to_abs().TransformPointLocalToParent(c_body); // OOBB corner expressed in SCM frame ChVector<> c_scm = m_plane.TransformPointParentToLocal(c_abs); // Update AABB of patch projection onto SCM plane p_min.x() = std::min(p_min.x(), c_scm.x()); p_min.y() = std::min(p_min.y(), c_scm.y()); p_max.x() = std::max(p_max.x(), c_scm.x()); p_max.y() = std::max(p_max.y(), c_scm.y()); } // Find index ranges for grid vertices contained in the patch projection AABB int x_min = static_cast<int>(std::ceil(p_min.x() / m_delta)); int y_min = static_cast<int>(std::ceil(p_min.y() / m_delta)); int x_max = static_cast<int>(std::floor(p_max.x() / m_delta)); int y_max = static_cast<int>(std::floor(p_max.y() / m_delta)); int n_x = x_max - x_min + 1; int n_y = y_max - y_min + 1; p.m_range.resize(n_x * n_y); for (int i = 0; i < n_x; i++) { for (int j = 0; j < n_y; j++) { p.m_range[j * n_x + i] = ChVector2<int>(i + x_min, j + y_min); } } // Calculate inverse of SCM normal expressed in body frame (for optimization of ray-OBB test) ChVector<> dir = p.m_body->TransformDirectionParentToLocal(Z); p.m_ooN.x() = (dir.x() == 0) ? 1e10 : 1.0 / dir.x(); p.m_ooN.y() = (dir.y() == 0) ? 1e10 : 1.0 / dir.y(); p.m_ooN.z() = (dir.z() == 0) ? 1e10 : 1.0 / dir.z(); } // Synchronize information for fixed patch void SCMDeformableSoil::UpdateFixedPatch(MovingPatchInfo& p) { ChVector2<> p_min(+std::numeric_limits<double>::max()); ChVector2<> p_max(-std::numeric_limits<double>::max()); // Get current bounding box (AABB) of all collision shapes ChVector<> aabb_min; ChVector<> aabb_max; GetSystem()->GetCollisionSystem()->GetBoundingBox(aabb_min, aabb_max); // Loop over all corners of the AABB for (int j = 0; j < 8; j++) { int ix = j % 2; int iy = (j / 2) % 2; int iz = (j / 4); // AABB corner in absolute frame ChVector<> c_abs = aabb_max * ChVector<>(ix, iy, iz) + aabb_min * ChVector<>(1.0 - ix, 1.0 - iy, 1.0 - iz); // AABB corner in SCM frame ChVector<> c_scm = m_plane.TransformPointParentToLocal(c_abs); // Update AABB of patch projection onto SCM plane p_min.x() = std::min(p_min.x(), c_scm.x()); p_min.y() = std::min(p_min.y(), c_scm.y()); p_max.x() = std::max(p_max.x(), c_scm.x()); p_max.y() = std::max(p_max.y(), c_scm.y()); } // Find index ranges for grid vertices contained in the patch projection AABB int x_min = static_cast<int>(std::ceil(p_min.x() / m_delta)); int y_min = static_cast<int>(std::ceil(p_min.y() / m_delta)); int x_max = static_cast<int>(std::floor(p_max.x() / m_delta)); int y_max = static_cast<int>(std::floor(p_max.y() / m_delta)); int n_x = x_max - x_min + 1; int n_y = y_max - y_min + 1; p.m_range.resize(n_x * n_y); for (int i = 0; i < n_x; i++) { for (int j = 0; j < n_y; j++) { p.m_range[j * n_x + i] = ChVector2<int>(i + x_min, j + y_min); } } } // Ray-OBB intersection test bool SCMDeformableSoil::RayOBBtest(const MovingPatchInfo& p, const ChVector<>& from, const ChVector<>& Z) { // Express ray origin in OBB frame ChVector<> orig = p.m_body->TransformPointParentToLocal(from) - p.m_center; // Perform ray-AABB test (slab tests) double t1 = (-p.m_hdims.x() - orig.x()) * p.m_ooN.x(); double t2 = (+p.m_hdims.x() - orig.x()) * p.m_ooN.x(); double t3 = (-p.m_hdims.y() - orig.y()) * p.m_ooN.y(); double t4 = (+p.m_hdims.y() - orig.y()) * p.m_ooN.y(); double t5 = (-p.m_hdims.z() - orig.z()) * p.m_ooN.z(); double t6 = (+p.m_hdims.z() - orig.z()) * p.m_ooN.z(); double tmin = std::max(std::max(std::min(t1, t2), std::min(t3, t4)), std::min(t5, t6)); double tmax = std::min(std::min(std::max(t1, t2), std::max(t3, t4)), std::max(t5, t6)); if (tmax < 0) return false; if (tmin > tmax) return false; return true; } // Offsets for the 8 neighbors of a grid vertex static const std::vector<ChVector2<int>> neighbors8{ ChVector2<int>(-1, -1), // SW ChVector2<int>(0, -1), // S ChVector2<int>(1, -1), // SE ChVector2<int>(-1, 0), // W ChVector2<int>(1, 0), // E ChVector2<int>(-1, 1), // NW ChVector2<int>(0, 1), // N ChVector2<int>(1, 1) // NE }; static const std::vector<ChVector2<int>> neighbors4{ ChVector2<int>(0, -1), // S ChVector2<int>(-1, 0), // W ChVector2<int>(1, 0), // E ChVector2<int>(0, 1) // N }; // Default implementation uses Map-Reduce for collecting ray intersection hits. // The alternative is to simultaenously load the global map of hits while ray casting (using a critical section). ////#define RAY_CASTING_WITH_CRITICAL_SECTION // Reset the list of forces, and fills it with forces from a soil contact model. void SCMDeformableSoil::ComputeInternalForces() { // Initialize list of modified visualization mesh vertices (use any externally modified vertices) std::vector<int> modified_vertices = m_external_modified_vertices; m_external_modified_vertices.clear(); // Reset quantities at grid nodes modified over previous step // (required for bulldozing effects and for proper visualization coloring) for (const auto& ij : m_modified_nodes) { auto& nr = m_grid_map.at(ij); nr.sigma = 0; nr.sinkage_elastic = 0; nr.step_plastic_flow = 0; nr.erosion = false; nr.hit_level = 1e9; // Update visualization (only color changes relevant here) if (m_trimesh_shape && CheckMeshBounds(ij)) { int iv = GetMeshVertexIndex(ij); // mesh vertex index UpdateMeshVertexCoordinates(ij, iv, nr); // update vertex coordinates and color modified_vertices.push_back(iv); } } m_modified_nodes.clear(); // Reset timers m_timer_moving_patches.reset(); m_timer_ray_testing.reset(); m_timer_ray_casting.reset(); m_timer_contact_patches.reset(); m_timer_contact_forces.reset(); m_timer_bulldozing.reset(); m_timer_bulldozing_boundary.reset(); m_timer_bulldozing_domain.reset(); m_timer_bulldozing_erosion.reset(); m_timer_visualization.reset(); // Reset the load list and map of contact forces this->GetLoadList().clear(); m_contact_forces.clear(); // --------------------- // Update moving patches // --------------------- m_timer_moving_patches.start(); // Update patch information (find range of grid indices) if (m_moving_patch) { for (auto& p : m_patches) UpdateMovingPatch(p, m_Z); } else { assert(m_patches.size() == 1); UpdateFixedPatch(m_patches[0]); } m_timer_moving_patches.stop(); // ------------------------- // Perform ray casting tests // ------------------------- // Information of vertices with ray-cast hits struct HitRecord { ChContactable* contactable; // pointer to hit object ChVector<> abs_point; // hit point, expressed in global frame int patch_id; // index of associated patch id }; // Hash-map for vertices with ray-cast hits std::unordered_map<ChVector2<int>, HitRecord, CoordHash> hits; m_num_ray_casts = 0; m_num_ray_hits = 0; m_timer_ray_casting.start(); #ifdef RAY_CASTING_WITH_CRITICAL_SECTION int nthreads = GetSystem()->GetNumThreadsChrono(); // Loop through all moving patches (user-defined or default one) for (auto& p : m_patches) { // Loop through all vertices in the patch range int num_ray_casts = 0; #pragma omp parallel for num_threads(nthreads) reduction(+ : num_ray_casts) for (int k = 0; k < p.m_range.size(); k++) { ChVector2<int> ij = p.m_range[k]; // Move from (i, j) to (x, y, z) representation in the world frame double x = ij.x() * m_delta; double y = ij.y() * m_delta; double z; #pragma omp critical(SCM_ray_casting) z = GetHeight(ij); ChVector<> vertex_abs = m_plane.TransformPointLocalToParent(ChVector<>(x, y, z)); // Create ray at current grid location collision::ChCollisionSystem::ChRayhitResult mrayhit_result; ChVector<> to = vertex_abs + m_Z * m_test_offset_up; ChVector<> from = to - m_Z * m_test_offset_down; // Ray-OBB test (quick rejection) if (m_moving_patch && !RayOBBtest(p, from, m_Z)) continue; // Cast ray into collision system GetSystem()->GetCollisionSystem()->RayHit(from, to, mrayhit_result); num_ray_casts++; if (mrayhit_result.hit) { #pragma omp critical(SCM_ray_casting) { // If this is the first hit from this node, initialize the node record if (m_grid_map.find(ij) == m_grid_map.end()) { m_grid_map.insert(std::make_pair(ij, NodeRecord(z, z, GetInitNormal(ij)))); } // Add to our map of hits to process HitRecord record = {mrayhit_result.hitModel->GetContactable(), mrayhit_result.abs_hitPoint, -1}; hits.insert(std::make_pair(ij, record)); m_num_ray_hits++; } } } m_num_ray_casts += num_ray_casts; } #else // Map-reduce approach (to eliminate critical section) const int nthreads = GetSystem()->GetNumThreadsChrono(); std::vector<std::unordered_map<ChVector2<int>, HitRecord, CoordHash>> t_hits(nthreads); // Loop through all moving patches (user-defined or default one) for (auto& p : m_patches) { m_timer_ray_testing.start(); // Loop through all vertices in the patch range int num_ray_casts = 0; #pragma omp parallel for num_threads(nthreads) reduction(+:num_ray_casts) for (int k = 0; k < p.m_range.size(); k++) { int t_num = omp_get_thread_num(); ChVector2<int> ij = p.m_range[k]; // Move from (i, j) to (x, y, z) representation in the world frame double x = ij.x() * m_delta; double y = ij.y() * m_delta; double z = GetHeight(ij); ChVector<> vertex_abs = m_plane.TransformPointLocalToParent(ChVector<>(x, y, z)); // Create ray at current grid location collision::ChCollisionSystem::ChRayhitResult mrayhit_result; ChVector<> to = vertex_abs + m_Z * m_test_offset_up; ChVector<> from = to - m_Z * m_test_offset_down; // Ray-OBB test (quick rejection) if (m_moving_patch && !RayOBBtest(p, from, m_Z)) continue; // Cast ray into collision system GetSystem()->GetCollisionSystem()->RayHit(from, to, mrayhit_result); num_ray_casts++; if (mrayhit_result.hit) { // Add to our map of hits to process HitRecord record = {mrayhit_result.hitModel->GetContactable(), mrayhit_result.abs_hitPoint, -1}; t_hits[t_num].insert(std::make_pair(ij, record)); } } m_timer_ray_testing.stop(); m_num_ray_casts += num_ray_casts; // Sequential insertion in global hits for (int t_num = 0; t_num < nthreads; t_num++) { for (auto& h : t_hits[t_num]) { // If this is the first hit from this node, initialize the node record if (m_grid_map.find(h.first) == m_grid_map.end()) { double z = GetInitHeight(h.first); m_grid_map.insert(std::make_pair(h.first, NodeRecord(z, z, GetInitNormal(h.first)))); } ////hits.insert(h); } hits.insert(t_hits[t_num].begin(), t_hits[t_num].end()); t_hits[t_num].clear(); } m_num_ray_hits = (int)hits.size(); } #endif m_timer_ray_casting.stop(); // -------------------- // Find contact patches // -------------------- m_timer_contact_patches.start(); // Collect hit vertices assigned to each contact patch. struct ContactPatchRecord { std::vector<ChVector2<>> points; // points in contact patch (in reference plane) std::vector<ChVector2<int>> nodes; // grid nodes in the contact patch double area; // contact patch area double perimeter; // contact patch perimeter double oob; // approximate value of 1/b }; std::vector<ContactPatchRecord> contact_patches; // Loop through all hit nodes and determine to which contact patch they belong. // Use a queue-based flood-filling algorithm based on the neighbors of each hit node. m_num_contact_patches = 0; for (auto& h : hits) { if (h.second.patch_id != -1) continue; ChVector2<int> ij = h.first; // Make a new contact patch and add this hit node to it h.second.patch_id = m_num_contact_patches++; ContactPatchRecord patch; patch.nodes.push_back(ij); patch.points.push_back(ChVector2<>(m_delta * ij.x(), m_delta * ij.y())); // Add current node to the work queue std::queue<ChVector2<int>> todo; todo.push(ij); while (!todo.empty()) { auto crt = hits.find(todo.front()); // Current hit node is first element in queue todo.pop(); // Remove first element from queue ChVector2<int> crt_ij = crt->first; int crt_patch = crt->second.patch_id; // Loop through the neighbors of the current hit node for (int k = 0; k < 4; k++) { ChVector2<int> nbr_ij = crt_ij + neighbors4[k]; // If neighbor is not a hit node, move on auto nbr = hits.find(nbr_ij); if (nbr == hits.end()) continue; // If neighbor already assigned to a contact patch, move on if (nbr->second.patch_id != -1) continue; // Assign neighbor to the same contact patch nbr->second.patch_id = crt_patch; // Add neighbor point to patch lists patch.nodes.push_back(nbr_ij); patch.points.push_back(ChVector2<>(m_delta * nbr_ij.x(), m_delta * nbr_ij.y())); // Add neighbor to end of work queue todo.push(nbr_ij); } } contact_patches.push_back(patch); } // Calculate area and perimeter of each contact patch. // Calculate approximation to Beker term 1/b. for (auto& p : contact_patches) { utils::ChConvexHull2D ch(p.points); p.area = ch.GetArea(); p.perimeter = ch.GetPerimeter(); if (p.area < 1e-6) { p.oob = 0; } else { p.oob = p.perimeter / (2 * p.area); } } m_timer_contact_patches.stop(); // ---------------------- // Compute contact forces // ---------------------- m_timer_contact_forces.start(); // Initialize local values for the soil parameters double Bekker_Kphi = m_Bekker_Kphi; double Bekker_Kc = m_Bekker_Kc; double Bekker_n = m_Bekker_n; double Mohr_cohesion = m_Mohr_cohesion; double Mohr_mu = m_Mohr_mu; double Janosi_shear = m_Janosi_shear; double elastic_K = m_elastic_K; double damping_R = m_damping_R; // Process only hit nodes for (auto& h : hits) { ChVector2<> ij = h.first; auto& nr = m_grid_map.at(ij); // node record const double& ca = nr.normal.z(); // cosine of angle between local normal and SCM plane vertical ChContactable* contactable = h.second.contactable; const ChVector<>& hit_point_abs = h.second.abs_point; int patch_id = h.second.patch_id; auto hit_point_loc = m_plane.TransformPointParentToLocal(hit_point_abs); if (m_soil_fun) { double Mohr_friction; m_soil_fun->Set(hit_point_loc, Bekker_Kphi, Bekker_Kc, Bekker_n, Mohr_cohesion, Mohr_friction, Janosi_shear, elastic_K, damping_R); Mohr_mu = std::tan(Mohr_friction * CH_C_DEG_TO_RAD); } nr.hit_level = hit_point_loc.z(); // along SCM z axis double p_hit_offset = ca * (nr.level_initial - nr.hit_level); // along local normal direction // Elastic try (along local normal direction) nr.sigma = elastic_K * (p_hit_offset - nr.sinkage_plastic); // Handle unilaterality if (nr.sigma < 0) { nr.sigma = 0; continue; } // Mark current node as modified m_modified_nodes.push_back(ij); // Calculate velocity at touched grid node ChVector<> point_local(ij.x() * m_delta, ij.y() * m_delta, nr.level); ChVector<> point_abs = m_plane.TransformPointLocalToParent(point_local); ChVector<> speed_abs = contactable->GetContactPointSpeed(point_abs); // Calculate normal and tangent directions (expressed in absolute frame) ChVector<> N = m_plane.TransformDirectionLocalToParent(nr.normal); double Vn = Vdot(speed_abs, N); ChVector<> T = -(speed_abs - Vn * N); T.Normalize(); // Update total sinkage and current level for this hit node nr.sinkage = p_hit_offset; nr.level = nr.hit_level; // Accumulate shear for Janosi-Hanamoto (along local tangent direction) nr.kshear += Vdot(speed_abs, -T) * GetSystem()->GetStep(); // Plastic correction (along local normal direction) if (nr.sigma > nr.sigma_yield) { // Bekker formula nr.sigma = (contact_patches[patch_id].oob * Bekker_Kc + Bekker_Kphi) * pow(nr.sinkage, Bekker_n); nr.sigma_yield = nr.sigma; double old_sinkage_plastic = nr.sinkage_plastic; nr.sinkage_plastic = nr.sinkage - nr.sigma / elastic_K; nr.step_plastic_flow = (nr.sinkage_plastic - old_sinkage_plastic) / GetSystem()->GetStep(); } // Elastic sinkage (along local normal direction) nr.sinkage_elastic = nr.sinkage - nr.sinkage_plastic; // Add compressive speed-proportional damping (not clamped by pressure yield) ////if (Vn < 0) { nr.sigma += -Vn * damping_R; ////} // Mohr-Coulomb double tau_max = Mohr_cohesion + nr.sigma * Mohr_mu; // Janosi-Hanamoto (along local tangent direction) nr.tau = tau_max * (1.0 - exp(-(nr.kshear / Janosi_shear))); // Calculate normal and tangential forces (in local node directions). // If specified, combine properties for soil-contactable interaction and soil-soil interaction. ChVector<> Fn = N * m_area * nr.sigma; ChVector<> Ft; //// TODO: take into account "tread height" (add to SCMContactableData)? if (auto cprops = contactable->GetUserData<vehicle::SCMContactableData>()) { // Use weighted sum of soil-contactable and soil-soil parameters double c_tau_max = cprops->Mohr_cohesion + nr.sigma * cprops->Mohr_mu; double c_tau = c_tau_max * (1.0 - exp(-(nr.kshear / cprops->Janosi_shear))); double ratio = cprops->area_ratio; Ft = T * m_area * ((1 - ratio) * nr.tau + ratio * c_tau); } else { // Use only soil-soil parameters Ft = T * m_area * nr.tau; } if (ChBody* rigidbody = dynamic_cast<ChBody*>(contactable)) { // [](){} Trick: no deletion for this shared ptr, since 'rigidbody' was not a new ChBody() // object, but an already used pointer because mrayhit_result.hitModel->GetPhysicsItem() // cannot return it as shared_ptr, as needed by the ChLoadBodyForce: std::shared_ptr<ChBody> srigidbody(rigidbody, [](ChBody*) {}); std::shared_ptr<ChLoadBodyForce> mload(new ChLoadBodyForce(srigidbody, Fn + Ft, false, point_abs, false)); this->Add(mload); // Accumulate contact force for this rigid body. // The resultant force is assumed to be applied at the body COM. // All components of the generalized terrain force are expressed in the global frame. auto itr = m_contact_forces.find(contactable); if (itr == m_contact_forces.end()) { // Create new entry and initialize generalized force. ChVector<> force = Fn + Ft; TerrainForce frc; frc.point = srigidbody->GetPos(); frc.force = force; frc.moment = Vcross(Vsub(point_abs, srigidbody->GetPos()), force); m_contact_forces.insert(std::make_pair(contactable, frc)); } else { // Update generalized force. ChVector<> force = Fn + Ft; itr->second.force += force; itr->second.moment += Vcross(Vsub(point_abs, srigidbody->GetPos()), force); } } else if (ChLoadableUV* surf = dynamic_cast<ChLoadableUV*>(contactable)) { // [](){} Trick: no deletion for this shared ptr std::shared_ptr<ChLoadableUV> ssurf(surf, [](ChLoadableUV*) {}); std::shared_ptr<ChLoad<ChLoaderForceOnSurface>> mload(new ChLoad<ChLoaderForceOnSurface>(ssurf)); mload->loader.SetForce(Fn + Ft); mload->loader.SetApplication(0.5, 0.5); //***TODO*** set UV, now just in middle this->Add(mload); // Accumulate contact forces for this surface. //// TODO } // Update grid node height (in local SCM frame, along SCM z axis) nr.level = nr.level_initial - nr.sinkage / ca; } // end loop on ray hits m_timer_contact_forces.stop(); // -------------------------------------------------- // Flow material to the side of rut, using heuristics // -------------------------------------------------- m_timer_bulldozing.start(); m_num_erosion_nodes = 0; if (m_bulldozing) { typedef std::unordered_set<ChVector2<int>, CoordHash> NodeSet; // Maximum level change between neighboring nodes (smoothing phase) double dy_lim = m_delta * m_erosion_slope; // (1) Raise boundaries of each contact patch m_timer_bulldozing_boundary.start(); NodeSet boundary; // union of contact patch boundaries for (auto p : contact_patches) { NodeSet p_boundary; // boundary of effective contact patch // Calculate the displaced material from all touched nodes and identify boundary double tot_step_flow = 0; for (const auto& ij : p.nodes) { // for each node in contact patch const auto& nr = m_grid_map.at(ij); // get node record if (nr.sigma <= 0) // if node not touched continue; // skip (not in effective patch) tot_step_flow += nr.step_plastic_flow; // accumulate displaced material for (int k = 0; k < 4; k++) { // check each node neighbor ChVector2<int> nbr_ij = ij + neighbors4[k]; // neighbor node coordinates ////if (!CheckMeshBounds(nbr_ij)) // if neighbor out of bounds //// continue; // skip neighbor if (m_grid_map.find(nbr_ij) == m_grid_map.end()) // if neighbor not yet recorded p_boundary.insert(nbr_ij); // set neighbor as boundary else if (m_grid_map.at(nbr_ij).sigma <= 0) // if neighbor not touched p_boundary.insert(nbr_ij); // set neighbor as boundary } } tot_step_flow *= GetSystem()->GetStep(); // Target raise amount for each boundary node (unless clamped) double diff = m_flow_factor * tot_step_flow / p_boundary.size(); // Raise boundary (create a sharp spike which will be later smoothed out with erosion) for (const auto& ij : p_boundary) { // for each node in bndry m_modified_nodes.push_back(ij); // mark as modified if (m_grid_map.find(ij) == m_grid_map.end()) { // if not yet recorded double z = GetInitHeight(ij); // undeformed height const ChVector<>& n = GetInitNormal(ij); // terrain normal m_grid_map.insert(std::make_pair(ij, NodeRecord(z, z, n))); // add new node record m_modified_nodes.push_back(ij); // mark as modified } // auto& nr = m_grid_map.at(ij); // node record nr.erosion = true; // add to erosion domain AddMaterialToNode(diff, nr); // add raise amount } // Accumulate boundary boundary.insert(p_boundary.begin(), p_boundary.end()); } // end for contact_patches m_timer_bulldozing_boundary.stop(); // (2) Calculate erosion domain (dilate boundary) m_timer_bulldozing_domain.start(); NodeSet erosion_domain = boundary; NodeSet erosion_front = boundary; // initialize erosion front to boundary nodes for (int i = 0; i < m_erosion_propagations; i++) { NodeSet front; // new erosion front for (const auto& ij : erosion_front) { // for each node in current erosion front for (int k = 0; k < 4; k++) { // check each of its neighbors ChVector2<int> nbr_ij = ij + neighbors4[k]; // neighbor node coordinates ////if (!CheckMeshBounds(nbr_ij)) // if out of bounds //// continue; // ignore neighbor if (m_grid_map.find(nbr_ij) == m_grid_map.end()) { // if neighbor not yet recorded double z = GetInitHeight(nbr_ij); // undeformed height at neighbor location const ChVector<>& n = GetInitNormal(nbr_ij); // terrain normal at neighbor location NodeRecord nr(z, z, n); // create new record nr.erosion = true; // include in erosion domain m_grid_map.insert(std::make_pair(nbr_ij, nr)); // add new node record front.insert(nbr_ij); // add neighbor to new front m_modified_nodes.push_back(nbr_ij); // mark as modified } else { // if neighbor previously recorded NodeRecord& nr = m_grid_map.at(nbr_ij); // get existing record if (!nr.erosion && nr.sigma <= 0) { // if neighbor not touched nr.erosion = true; // include in erosion domain front.insert(nbr_ij); // add neighbor to new front m_modified_nodes.push_back(nbr_ij); // mark as modified } } } } erosion_domain.insert(front.begin(), front.end()); // add current front to erosion domain erosion_front = front; // advance erosion front } m_num_erosion_nodes = static_cast<int>(erosion_domain.size()); m_timer_bulldozing_domain.stop(); // (3) Erosion algorithm on domain m_timer_bulldozing_erosion.start(); for (int iter = 0; iter < m_erosion_iterations; iter++) { for (const auto& ij : erosion_domain) { auto& nr = m_grid_map.at(ij); for (int k = 0; k < 4; k++) { ChVector2<int> nbr_ij = ij + neighbors4[k]; auto rec = m_grid_map.find(nbr_ij); if (rec == m_grid_map.end()) continue; auto& nbr_nr = rec->second; // (3.1) Flow remaining material to neighbor double diff = 0.5 * (nr.massremainder - nbr_nr.massremainder) / 4; //// TODO: rethink this! if (diff > 0) { RemoveMaterialFromNode(diff, nr); AddMaterialToNode(diff, nbr_nr); } // (3.2) Smoothing if (nbr_nr.sigma == 0) { double dy = (nr.level + nr.massremainder) - (nbr_nr.level + nbr_nr.massremainder); diff = 0.5 * (std::abs(dy) - dy_lim) / 4; //// TODO: rethink this! if (diff > 0) { if (dy > 0) { RemoveMaterialFromNode(diff, nr); AddMaterialToNode(diff, nbr_nr); } else { RemoveMaterialFromNode(diff, nbr_nr); AddMaterialToNode(diff, nr); } } } } } } m_timer_bulldozing_erosion.stop(); } // end do_bulldozing m_timer_bulldozing.stop(); // -------------------- // Update visualization // -------------------- m_timer_visualization.start(); if (m_trimesh_shape) { // Loop over list of modified nodes and adjust corresponding mesh vertices. // If not rendering a wireframe mesh, also update normals. for (const auto& ij : m_modified_nodes) { if (!CheckMeshBounds(ij)) // if node outside mesh continue; // do nothing const auto& nr = m_grid_map.at(ij); // grid node record int iv = GetMeshVertexIndex(ij); // mesh vertex index UpdateMeshVertexCoordinates(ij, iv, nr); // update vertex coordinates and color modified_vertices.push_back(iv); // cache in list of modified mesh vertices if (!m_trimesh_shape->IsWireframe()) // if not wireframe UpdateMeshVertexNormal(ij, iv); // update vertex normal } m_trimesh_shape->SetModifiedVertices(modified_vertices); } m_timer_visualization.stop(); } void SCMDeformableSoil::AddMaterialToNode(double amount, NodeRecord& nr) { if (amount > nr.hit_level - nr.level) { // if not possible to assign all mass nr.massremainder += amount - (nr.hit_level - nr.level); // material to be further propagated amount = nr.hit_level - nr.level; // clamp raise amount } // nr.level += amount; // modify node level nr.level_initial += amount; // reset node initial level } void SCMDeformableSoil::RemoveMaterialFromNode(double amount, NodeRecord& nr) { if (nr.massremainder > amount) { // if too much remainder material nr.massremainder -= amount; // decrease remainder material /*amount = 0;*/ // ??? } else if (nr.massremainder < amount && nr.massremainder > 0) { // if not enough remainder material amount -= nr.massremainder; // clamp removed amount nr.massremainder = 0; // remainder material exhausted } // nr.level -= amount; // modify node level nr.level_initial -= amount; // reset node initial level } // Update vertex position and color in visualization mesh void SCMDeformableSoil::UpdateMeshVertexCoordinates(const ChVector2<int> ij, int iv, const NodeRecord& nr) { auto& trimesh = *m_trimesh_shape->GetMesh(); std::vector<ChVector<>>& vertices = trimesh.getCoordsVertices(); std::vector<ChVector<float>>& colors = trimesh.getCoordsColors(); // Update visualization mesh vertex position vertices[iv] = m_plane.TransformPointLocalToParent(ChVector<>(ij.x() * m_delta, ij.y() * m_delta, nr.level)); // Update visualization mesh vertex color if (m_plot_type != SCMDeformableTerrain::PLOT_NONE) { ChColor mcolor; switch (m_plot_type) { case SCMDeformableTerrain::PLOT_LEVEL: mcolor = ChColor::ComputeFalseColor(nr.level, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_LEVEL_INITIAL: mcolor = ChColor::ComputeFalseColor(nr.level_initial, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_SINKAGE: mcolor = ChColor::ComputeFalseColor(nr.sinkage, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_SINKAGE_ELASTIC: mcolor = ChColor::ComputeFalseColor(nr.sinkage_elastic, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_SINKAGE_PLASTIC: mcolor = ChColor::ComputeFalseColor(nr.sinkage_plastic, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_STEP_PLASTIC_FLOW: mcolor = ChColor::ComputeFalseColor(nr.step_plastic_flow, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_K_JANOSI: mcolor = ChColor::ComputeFalseColor(nr.kshear, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_PRESSURE: mcolor = ChColor::ComputeFalseColor(nr.sigma, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_PRESSURE_YELD: mcolor = ChColor::ComputeFalseColor(nr.sigma_yield, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_SHEAR: mcolor = ChColor::ComputeFalseColor(nr.tau, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_MASSREMAINDER: mcolor = ChColor::ComputeFalseColor(nr.massremainder, m_plot_v_min, m_plot_v_max); break; case SCMDeformableTerrain::PLOT_ISLAND_ID: if (nr.erosion) mcolor = ChColor(0, 0, 0); if (nr.sigma > 0) mcolor = ChColor(1, 0, 0); break; case SCMDeformableTerrain::PLOT_IS_TOUCHED: if (nr.sigma > 0) mcolor = ChColor(1, 0, 0); else mcolor = ChColor(0, 0, 1); break; case SCMDeformableTerrain::PLOT_NONE: break; } colors[iv] = {mcolor.R, mcolor.G, mcolor.B}; } } // Update vertex normal in visualization mesh. void SCMDeformableSoil::UpdateMeshVertexNormal(const ChVector2<int> ij, int iv) { auto& trimesh = *m_trimesh_shape->GetMesh(); std::vector<ChVector<>>& vertices = trimesh.getCoordsVertices(); std::vector<ChVector<>>& normals = trimesh.getCoordsNormals(); std::vector<ChVector<int>>& idx_normals = trimesh.getIndicesNormals(); // Average normals from adjacent faces normals[iv] = ChVector<>(0, 0, 0); auto faces = GetMeshFaceIndices(ij); for (auto f : faces) { ChVector<> nrm = Vcross(vertices[idx_normals[f][1]] - vertices[idx_normals[f][0]], vertices[idx_normals[f][2]] - vertices[idx_normals[f][0]]); nrm.Normalize(); normals[iv] += nrm; } normals[iv] /= (double)faces.size(); } // Get the heights of modified grid nodes. std::vector<SCMDeformableTerrain::NodeLevel> SCMDeformableSoil::GetModifiedNodes(bool all_nodes) const { std::vector<SCMDeformableTerrain::NodeLevel> nodes; if (all_nodes) { for (const auto& nr : m_grid_map) { nodes.push_back(std::make_pair(nr.first, nr.second.level)); } } else { for (const auto& ij : m_modified_nodes) { auto rec = m_grid_map.find(ij); assert(rec != m_grid_map.end()); nodes.push_back(std::make_pair(ij, rec->second.level)); } } return nodes; } // Modify the level of grid nodes from the given list. // NOTE: We set only the level of the specified nodes and none of the other soil properties. // As such, some plot types may be incorrect at these nodes. void SCMDeformableSoil::SetModifiedNodes(const std::vector<SCMDeformableTerrain::NodeLevel>& nodes) { for (const auto& n : nodes) { // Modify existing entry in grid map or insert new one m_grid_map[n.first] = SCMDeformableSoil::NodeRecord(n.second, n.second, GetInitNormal(n.first)); } // Update visualization if (m_trimesh_shape) { for (const auto& n : nodes) { auto ij = n.first; // grid location if (!CheckMeshBounds(ij)) // if outside mesh continue; // do nothing const auto& nr = m_grid_map.at(ij); // grid node record int iv = GetMeshVertexIndex(ij); // mesh vertex index UpdateMeshVertexCoordinates(ij, iv, nr); // update vertex coordinates and color if (!m_trimesh_shape->IsWireframe()) // if not in wireframe mode UpdateMeshVertexNormal(ij, iv); // update vertex normal m_external_modified_vertices.push_back(iv); // cache in list } } } } // end namespace vehicle } // end namespace chrono
71,494
23,389
// Copyright Carl Philipp Reh 2009 - 2018. // 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) #include <fcppt/noncopyable.hpp> #include <fcppt/record/element.hpp> #include <fcppt/record/get.hpp> #include <fcppt/record/make_label.hpp> #include <fcppt/record/set.hpp> #include <fcppt/record/variadic.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <utility> #include <fcppt/config/external_end.hpp> TEST_CASE( "record::object", "[record]" ) { class copy_only { public: explicit copy_only( int const _value ) : value_( _value ) { } copy_only( copy_only const & ) = default; int value() const { return value_; } private: int value_; }; class move_only { FCPPT_NONCOPYABLE( move_only ); public: explicit move_only( int const _value ) : value_{ _value }, valid_{ true } { } move_only( move_only &&_other ) : value_{ _other.value_ }, valid_{ _other.valid_ } { _other.valid_ = false; } move_only & operator=( move_only &&_other ) { value_ = _other.value_; valid_ = _other.valid_; _other.valid_ = false; return *this; } ~move_only() { } int value() const { CHECK( valid_ ); return value_; } private: int value_; bool valid_; }; FCPPT_RECORD_MAKE_LABEL( int_label ); FCPPT_RECORD_MAKE_LABEL( bool_label ); FCPPT_RECORD_MAKE_LABEL( copy_only_label ); FCPPT_RECORD_MAKE_LABEL( move_only_label ); typedef fcppt::record::variadic< fcppt::record::element< int_label, int >, fcppt::record::element< bool_label, bool >, fcppt::record::element< copy_only_label, copy_only >, fcppt::record::element< move_only_label, move_only > > my_record; int const arg1{ 4 }; my_record test{ int_label{} = arg1, bool_label{} = true, copy_only_label{} = copy_only( 42 ), move_only_label{} = move_only{ 10 } }; CHECK( fcppt::record::get< int_label >( test ) == 4 ); CHECK( fcppt::record::get< bool_label >( test ) ); CHECK( fcppt::record::get< copy_only_label >( test ).value() == 42 ); CHECK( fcppt::record::get< move_only_label >( test ).value() == 10 ); my_record test2( std::move( test ) ); CHECK( fcppt::record::get< int_label >( test2 ) == 4 ); CHECK( fcppt::record::get< bool_label >( test2 ) ); CHECK( fcppt::record::get< move_only_label >( test2 ).value() == 10 ); fcppt::record::set< bool_label >( test2, false ); CHECK_FALSE( fcppt::record::get< bool_label >( test2 ) ); fcppt::record::set< move_only_label >( test2, move_only{ 100 } ); CHECK( fcppt::record::get< move_only_label >( test2 ).value() == 100 ); fcppt::record::get< int_label >( test2 ) = 42; CHECK( fcppt::record::get< int_label >( test2 ) == 42 ); }
3,220
1,774
//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2013/10/9 // Author: Mike Ovsiannikov // // Copyright 2013,2016 Quantcast Corporation. All rights reserved. // // This file is part of Kosmos File System (KFS). // // 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 "ChunkAccessToken.h" #include "common/MsgLogger.h" namespace KFS { using std::ostream; class ChunkAccessToken::Subject : public DelegationToken::Subject { public: Subject( kfsChunkId_t inChunkId, int64_t inId) { char* thePtr = mBuf; const char* const theEndPtr = thePtr + kSubjectLength; *thePtr++ = 'C'; *thePtr++ = 'A'; kfsChunkId_t theId = inChunkId; while (thePtr < theEndPtr - sizeof(inId)) { *thePtr++ = (char)(theId & 0xFF); theId >>= 8; } int64_t theWId = inId; while (thePtr < theEndPtr) { *thePtr++ = (char)(theWId & 0xFF); theWId >>= 8; } } virtual int Get( const DelegationToken& inToken, const char*& outPtr) { outPtr = mBuf; return (((inToken.GetFlags() & (kUsesWriteIdFlag | kUsesLeaseIdFlag)) != 0) ? kSubjectLength : kSubjectLength - (int)sizeof(int64_t)); } operator DelegationToken::Subject* () { return this; } private: enum { kSubjectLength = 2 + (int)sizeof(kfsChunkId_t) + (int)sizeof(int64_t) }; char mBuf[kSubjectLength]; }; ChunkAccessToken::ChunkAccessToken( kfsChunkId_t inChunkId, kfsUid_t inUid, TokenSeq inSeq, kfsKeyId_t inKeyId, int64_t inIssueTime, uint16_t inFlags, uint32_t inValidForSec, const char* inKeyPtr, int inKeyLen, int64_t inId) : mChunkId(inChunkId), mDelegationToken( inUid, inSeq, inKeyId, inIssueTime, inFlags, inValidForSec, inKeyPtr, inKeyLen, Subject(inChunkId, inId) ) { } bool ChunkAccessToken::Process( kfsChunkId_t inChunkId, const char* inBufPtr, int inBufLen, int64_t inTimeNowSec, const CryptoKeys& inKeys, string* outErrMsgPtr, int64_t inId) { Subject theSubject(inChunkId, inId); return (0 <= mDelegationToken.Process( inBufPtr, inBufLen, inTimeNowSec, inKeys, 0, // inSessionKeyPtr -1, // inMaxSessionKeyLength outErrMsgPtr, &theSubject )); } bool ChunkAccessToken::Process( kfsChunkId_t inChunkId, kfsUid_t inUid, const char* inBufPtr, int inBufLen, int64_t inTimeNowSec, const CryptoKeys& inKeys, string* outErrMsgPtr, int64_t inId) { if (! Process( inChunkId, inUid, inBufPtr, inBufLen, inTimeNowSec, inKeys, outErrMsgPtr, inId)) { return false; } if (inUid != mDelegationToken.GetUid()) { if (outErrMsgPtr) { *outErrMsgPtr = "user id mismatch"; } else { KFS_LOG_STREAM_ERROR << "user id mismatch: uid: " << inUid << " token uid: " << mDelegationToken.GetUid() << KFS_LOG_EOM; } return false; } return true; } ostream& ChunkAccessToken::ShowSelf( ostream& inStream) const { return (inStream << "chunkId: " << mChunkId << " " << mDelegationToken.Show() ); } /* static */ bool ChunkAccessToken::WriteToken( IOBufferWriter& inWriter, kfsChunkId_t inChunkId, kfsUid_t inUid, TokenSeq inSeq, kfsKeyId_t inKeyId, int64_t inIssuedTime, uint16_t inFlags, uint32_t inValidForSec, const char* inKeyPtr, int inKeyLen, int64_t inId) { Subject theSubject(inChunkId, inId); return DelegationToken::WriteToken( inWriter, inUid, inSeq, inKeyId, inIssuedTime, inFlags, inValidForSec, inKeyPtr, inKeyLen, &theSubject ); } /* static */ bool ChunkAccessToken::WriteToken( ostream& inStream, kfsChunkId_t inChunkId, kfsUid_t inUid, TokenSeq inSeq, kfsKeyId_t inKeyId, int64_t inIssuedTime, uint16_t inFlags, uint32_t inValidForSec, const char* inKeyPtr, int inKeyLen, int64_t inId) { Subject theSubject(inChunkId, inId); return DelegationToken::WriteToken( inStream, inUid, inSeq, inKeyId, inIssuedTime, inFlags, inValidForSec, inKeyPtr, inKeyLen, &theSubject ); } }
5,593
1,921
/*------------------------------------------------------------------------------ * Copyright 2016 Sensirion AG, Switzerland. All rights reserved. * * Software source code and Compensation Algorithms are Sensirion Confidential * Information and trade secrets. Licensee shall protect confidentiality of * Software source code and Compensation Algorithms. * * Licensee shall not distribute Software and/or Compensation Algorithms other * than in binary form incorporated in Products. DISTRIBUTION OF SOURCE CODE * AND/OR COMPENSATION ALGORITHMS IS NOT ALLOWED. * * Software and Compensation Algorithms are licensed for use with Sensirion * sensors only. * * Licensee shall not change the source code unless otherwise stated by * Sensirion. * * Software and Compensation Algorithms are provided "AS IS" and any and all * express or implied warranties are disclaimed. * * THIS SOFTWARE IS PROVIDED BY SENSIRION "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 SENSIRION 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 "Perspiration.h" #include <cmath> #include "LowPassFilter.h" #define REMOVE_OFFSET_AND_CAP_DATA 1 void initPerspirationEngine() { } static float absoluteHumidity(float temperature, float relativeHumidity) { static const float A = 6.112f; // hPa static const float Tn = 243.12f; // ยฐC static const float m = 17.62f; return 216.7f * (relativeHumidity * 0.01f * A * std::exp(m * temperature / (Tn + temperature)) / (273.15f + temperature)); } void perspirationEngine(unsigned long timeStampMs, float temperatureAmbientSensor, float relativeHumidityAmbientSensor, float temperatureSkinSensor, float relativeHumiditySkinSensor, float *perspiration) { /* compute the time delta from the timestamp, the time delta will slightly vary but this is desireable for the filter computation */ static unsigned long timeStampMsLastCall = 0; static float delta_t = int(timeStampMs - timeStampMsLastCall) / 1000.0f; timeStampMsLastCall = timeStampMs; /* relative humidity offset of ambient sensor */ static const float RH_OFFSET = 0; /* temperature offset of ambient sensor */ static const float T_OFFSET = 0; /* distance between sensors in m */ static const float D_SHT = 0.008f; /* diffusion coefficient @ 25ยฐC in m^2/s */ static const float DIFF_COEF_25_DEGREES = 2.6e-5f; /* emperical constant, slope of temperature vs calibration factor */ static const float T_CORRECTION_FACTOR = 0.04f; /* diffusion coefficient temperature dependent */ float DIFF_COEF = DIFF_COEF_25_DEGREES * T_CORRECTION_FACTOR * temperatureSkinSensor; float CONVERSION_FACTOR = 1.0f / D_SHT * DIFF_COEF * 3600.0f; /* calibration factor of device */ static const float CALIBRATION_FACTOR = 1.5f; /* define time constant for low pass filter and apply filtering on both temperature values */ static const float TAU = 30; temperatureAmbientSensor = firstOrder_lowPassFilter(temperatureAmbientSensor, TAU, delta_t); temperatureSkinSensor = firstOrder_lowPassFilter(temperatureSkinSensor, TAU, delta_t); #if REMOVE_OFFSET_AND_CAP_DATA /* use adjusted temperature and relative humidity to calculate absolute humidity */ temperatureAmbientSensor += T_OFFSET; relativeHumidityAmbientSensor += RH_OFFSET; #endif /* REMOVE_OFFSET_AND_CAP_DATA */ float absoluteHumidityAmbientSensor = absoluteHumidity(temperatureAmbientSensor, relativeHumidityAmbientSensor); float absoluteHumiditySkinSensor = absoluteHumidity(temperatureSkinSensor, relativeHumiditySkinSensor); #if REMOVE_OFFSET_AND_CAP_DATA if (absoluteHumiditySkinSensor > absoluteHumidityAmbientSensor) { #endif /* REMOVE_OFFSET_AND_CAP_DATA */ *perspiration = CALIBRATION_FACTOR * CONVERSION_FACTOR * (absoluteHumiditySkinSensor - absoluteHumidityAmbientSensor); #if REMOVE_OFFSET_AND_CAP_DATA } else { *perspiration = 0.0f; } #endif /* REMOVE_OFFSET_AND_CAP_DATA */ }
4,737
1,610
#include "XML_Node.h" #include "../Parser/Parser.h" String XML_Node::getTag() const { return this->data.tag; } void XML_Node::addArgument(Argument arg) { this->data.arguments.push(arg); } List<Argument> &XML_Node::getArguments() { return this->data.arguments; } Argument XML_Node::removeArgument(int index) { return this->data.arguments.deleteAt(index); } void XML_Node::setTag(String tag) { this->data.tag.set(tag); } void XML_Node::setId(String id) { this->data.id.set(id); } String XML_Node::getId() const { return this->data.id; } void XML_Node::setContent(String content) { this->data.content = content; } String XML_Node::getContent() const { return this->data.content; } XML_Node *XML_Node::findById(String id) { if (this->getId() == id) return this; List<TreeNode *> children = this->getChildren(); for (int i = 0; i < children.getSize(); i++) { XML_Node *result = ((XML_Node *) children[i])->findById(id); if (result != nullptr) return result; } return nullptr; } String XML_Node::toString() { return Parser::nodeTreeToString(this); }
1,136
399
#include "stdafx.h" #include "WrpConsole.h" #include <malloc.h> #include <string.h> #include <sstream> #include <iomanip> #include <windows.h> // WrpConCommand /////////////////////////////////////////////////////////////// WrpConCommand::WrpConCommand(char const * name, WrpCommandCallback callback, char const * helpString) { m_Callback = callback; if(!helpString) helpString = ""; m_HelpString =(char *) malloc((1+strlen(helpString))*sizeof(char)); strcpy(m_HelpString, helpString); m_Name = (char *)malloc((1+strlen(name))*sizeof(char)); strcpy(m_Name, name); WrpConCommands::WrpConCommand_Register(this); } WrpConCommand::~WrpConCommand() { WrpConCommands::WrpConCommand_Unregister(this); delete m_Name; delete m_HelpString; } WrpCommandCallback WrpConCommand::GetCallback() { return m_Callback; } char const * WrpConCommand::GetHelpString() { return m_HelpString; } char const * WrpConCommand::GetName() { return m_Name; } // WrpConCommands ////////////////////////////////////////////////////////////// SOURCESDK::ICvar_003 * WrpConCommands::m_CvarIface_003 = 0; SOURCESDK::ICvar_004 * WrpConCommands::m_CvarIface_004 = 0; SOURCESDK::CSGO::ICvar * WrpConCommands::m_CvarIface_CSGO = 0; SOURCESDK::SWARM::ICvar * WrpConCommands::m_CvarIface_SWARM = 0; SOURCESDK::L4D2::ICvar * WrpConCommands::m_CvarIface_L4D2 = 0; SOURCESDK::BM::ICvar * WrpConCommands::m_CvarIface_BM = 0; WrpConCommandsListEntry * WrpConCommands::m_CommandListRoot = 0; SOURCESDK::IVEngineClient_012 * WrpConCommands::m_VEngineClient_012 = 0; SOURCESDK::IVEngineClient_012 * WrpConCommands::GetVEngineClient_012() { return m_VEngineClient_012; } SOURCESDK::CSGO::ICvar * WrpConCommands::GetVEngineCvar_CSGO() { return m_CvarIface_CSGO; } void WrpConCommands::RegisterCommands(SOURCESDK::ICvar_003 * cvarIface, SOURCESDK::IVEngineClient_012 * vEngineClientInterface) { if(m_CvarIface_003) // already registered the current list return; m_CvarIface_003 = cvarIface; m_VEngineClient_012 = vEngineClientInterface; SOURCESDK::ConCommandBase_003::s_pAccessor = new WrpConCommandsRegistrar_003(); for(WrpConCommandsListEntry * entry = m_CommandListRoot; entry; entry = entry->Next) { WrpConCommand * cmd = entry->Command; // will init themself since s_pAccessor is set: new SOURCESDK::ConCommand_003(cmd->GetName(), cmd->GetCallback(), cmd->GetHelpString(), FCVAR_CLIENTDLL); } } void WrpConCommands::RegisterCommands(SOURCESDK::ICvar_004 * cvarIface) { if(m_CvarIface_004) // already registered the current list return; m_CvarIface_004 = cvarIface; SOURCESDK::ConCommandBase_004::s_pAccessor = new WrpConCommandsRegistrar_004(); for(WrpConCommandsListEntry * entry = m_CommandListRoot; entry; entry = entry->Next) { WrpConCommand * cmd = entry->Command; // will init themself since s_pAccessor is set: new SOURCESDK::ConCommand_004(cmd->GetName(), cmd->GetCallback(), cmd->GetHelpString(), FCVAR_CLIENTDLL); } } void WrpConCommands::RegisterCommands(SOURCESDK::CSGO::ICvar * cvarIface) { if(m_CvarIface_CSGO) // already registered the current list return; m_CvarIface_CSGO = cvarIface; SOURCESDK::CSGO::ConVar_Register(0, new WrpConCommandsRegistrar_CSGO()); for(WrpConCommandsListEntry * entry = m_CommandListRoot; entry; entry = entry->Next) { WrpConCommand * cmd = entry->Command; // will init themself since s_pAccessor is set: new SOURCESDK::CSGO::ConCommand(cmd->GetName(), cmd, cmd->GetHelpString(), SOURCESDK_CSGO_FCVAR_CLIENTDLL); } } void WrpConCommands::RegisterCommands(SOURCESDK::SWARM::ICvar * cvarIface) { if (m_CvarIface_SWARM) // already registered the current list return; m_CvarIface_SWARM = cvarIface; SOURCESDK::SWARM::ConVar_Register(0, new WrpConCommandsRegistrar_SWARM()); for (WrpConCommandsListEntry * entry = m_CommandListRoot; entry; entry = entry->Next) { WrpConCommand * cmd = entry->Command; // will init themself since s_pAccessor is set: new SOURCESDK::SWARM::ConCommand(cmd->GetName(), cmd, cmd->GetHelpString(), SOURCESDK_SWARM_FCVAR_CLIENTDLL); } } void WrpConCommands::RegisterCommands(SOURCESDK::L4D2::ICvar * cvarIface) { if (m_CvarIface_L4D2) // already registered the current list return; m_CvarIface_L4D2 = cvarIface; SOURCESDK::L4D2::ConVar_Register(0, new WrpConCommandsRegistrar_L4D2()); for (WrpConCommandsListEntry * entry = m_CommandListRoot; entry; entry = entry->Next) { WrpConCommand * cmd = entry->Command; // will init themself since s_pAccessor is set: new SOURCESDK::L4D2::ConCommand(cmd->GetName(), cmd, cmd->GetHelpString(), SOURCESDK_L4D2_FCVAR_CLIENTDLL); } } void WrpConCommands::RegisterCommands(SOURCESDK::BM::ICvar * cvarIface) { if (m_CvarIface_BM) // already registered the current list return; m_CvarIface_BM = cvarIface; SOURCESDK::BM::ConVar_Register(0, new WrpConCommandsRegistrar_BM()); for (WrpConCommandsListEntry * entry = m_CommandListRoot; entry; entry = entry->Next) { WrpConCommand * cmd = entry->Command; // will init themself since s_pAccessor is set: new SOURCESDK::BM::ConCommand(cmd->GetName(), cmd, cmd->GetHelpString(), SOURCESDK_BM_FCVAR_CLIENTDLL); } } void WrpConCommands::WrpConCommand_Register(WrpConCommand * cmd) { WrpConCommandsListEntry * entry = new WrpConCommandsListEntry(); entry->Command = cmd; entry->Next = m_CommandListRoot; m_CommandListRoot = entry; // if the list is already live, create (and thus register) the command instantly // in the engine: if(m_CvarIface_CSGO) new SOURCESDK::CSGO::ConCommand(cmd->GetName(), cmd, cmd->GetHelpString(), SOURCESDK_CSGO_FCVAR_CLIENTDLL); else if (m_CvarIface_SWARM) new SOURCESDK::SWARM::ConCommand(cmd->GetName(), cmd, cmd->GetHelpString(), SOURCESDK_SWARM_FCVAR_CLIENTDLL); else if (m_CvarIface_L4D2) new SOURCESDK::L4D2::ConCommand(cmd->GetName(), cmd, cmd->GetHelpString(), SOURCESDK_L4D2_FCVAR_CLIENTDLL); else if (m_CvarIface_BM) new SOURCESDK::BM::ConCommand(cmd->GetName(), cmd, cmd->GetHelpString(), SOURCESDK_BM_FCVAR_CLIENTDLL); else if(m_CvarIface_004) new SOURCESDK::ConCommand_004(cmd->GetName(), cmd->GetCallback(), cmd->GetHelpString()); else if(m_CvarIface_003) new SOURCESDK::ConCommand_003(cmd->GetName(), cmd->GetCallback(), cmd->GetHelpString()); } void WrpConCommands::WrpConCommand_Unregister(WrpConCommand * cmd) { WrpConCommandsListEntry ** pLastNext = &m_CommandListRoot; for(WrpConCommandsListEntry * entry = m_CommandListRoot; entry; entry = entry->Next) { if(cmd == entry->Command) { *pLastNext = entry->Next; delete entry; break; } pLastNext = &(entry->Next); } } bool WrpConCommands::WrpConCommandsRegistrar_003_Register(SOURCESDK::ConCommandBase_003 *pVar ) { if(!m_CvarIface_003) return false; // MessageBox(0, "WrpConCommands::WrpConCommandsRegistrar_003_Register", "AFX_DEBUG", MB_OK); m_CvarIface_003->RegisterConCommandBase(pVar); return true; } bool WrpConCommands::WrpConCommandsRegistrar_004_Register(SOURCESDK::ConCommandBase_004 *pVar ) { if(!m_CvarIface_004) return false; // MessageBox(0, "WrpConCommands::WrpConCommandsRegistrar_004_Register", "AFX_DEBUG", MB_OK); m_CvarIface_004->RegisterConCommand(pVar); return true; } bool WrpConCommands::WrpConCommandsRegistrar_CSGO_Register(SOURCESDK::CSGO::ConCommandBase *pVar ) { if(!m_CvarIface_CSGO) return false; // MessageBox(0, "WrpConCommands::WrpConCommandsRegistrar_007_Register", "AFX_DEBUG", MB_OK); m_CvarIface_CSGO->RegisterConCommand(pVar); return true; } bool WrpConCommands::WrpConCommandsRegistrar_SWARM_Register(SOURCESDK::SWARM::ConCommandBase *pVar) { if (!m_CvarIface_SWARM) return false; // MessageBox(0, "WrpConCommands::WrpConCommandsRegistrar_007_Register", "AFX_DEBUG", MB_OK); m_CvarIface_SWARM->RegisterConCommand(pVar); return true; } bool WrpConCommands::WrpConCommandsRegistrar_L4D2_Register(SOURCESDK::L4D2::ConCommandBase *pVar) { if (!m_CvarIface_L4D2) return false; // MessageBox(0, "WrpConCommands::WrpConCommandsRegistrar_007_Register", "AFX_DEBUG", MB_OK); m_CvarIface_L4D2->RegisterConCommand(pVar); return true; } bool WrpConCommands::WrpConCommandsRegistrar_BM_Register(SOURCESDK::BM::ConCommandBase *pVar) { if (!m_CvarIface_BM) return false; // MessageBox(0, "WrpConCommands::WrpConCommandsRegistrar_007_Register", "AFX_DEBUG", MB_OK); m_CvarIface_BM->RegisterConCommand(pVar); return true; } // WrpConCommandsRegistrar_003 //////////////////////////////////////////////////// bool WrpConCommandsRegistrar_003::RegisterConCommandBase(SOURCESDK::ConCommandBase_003 *pVar ) { return WrpConCommands::WrpConCommandsRegistrar_003_Register(pVar); } // WrpConCommandsRegistrar_004 //////////////////////////////////////////////////// bool WrpConCommandsRegistrar_004::RegisterConCommandBase(SOURCESDK::ConCommandBase_004 *pVar ) { return WrpConCommands::WrpConCommandsRegistrar_004_Register(pVar); } // WrpConCommandsRegistrar_CSGO //////////////////////////////////////////////////// bool WrpConCommandsRegistrar_CSGO::RegisterConCommandBase(SOURCESDK::CSGO::ConCommandBase *pVar ) { return WrpConCommands::WrpConCommandsRegistrar_CSGO_Register(pVar); } // WrpConCommandsRegistrar_SWARM //////////////////////////////////////////////////// bool WrpConCommandsRegistrar_SWARM::RegisterConCommandBase(SOURCESDK::SWARM::ConCommandBase *pVar) { return WrpConCommands::WrpConCommandsRegistrar_SWARM_Register(pVar); } // WrpConCommandsRegistrar_L4D2 //////////////////////////////////////////////////// bool WrpConCommandsRegistrar_L4D2::RegisterConCommandBase(SOURCESDK::L4D2::ConCommandBase *pVar) { return WrpConCommands::WrpConCommandsRegistrar_L4D2_Register(pVar); } // WrpConCommandsRegistrar_BM //////////////////////////////////////////////////// bool WrpConCommandsRegistrar_BM::RegisterConCommandBase(SOURCESDK::BM::ConCommandBase *pVar) { return WrpConCommands::WrpConCommandsRegistrar_BM_Register(pVar); } // WrpConVar /////////////////////////////////////////////////////////////////// WrpConVarRef::WrpConVarRef(char const * pName) : m_pConVar007(0) { if(SOURCESDK::CSGO::g_pCVar) { m_pConVar007 = SOURCESDK::CSGO::g_pCVar->FindVar(pName); } if(!m_pConVar007) { Tier0_Warning("AfxError: WrpConVarRef::WrpConVarRef(%s): Could not get ConVar.\n", pName); } } typedef union { DWORD d; float f; int i; } xor_helper_t; float WrpConVarRef::GetFloat(void) const { if(m_pConVar007) { //return m_pConVar007->GetFloat(); xor_helper_t h; h.f = m_pConVar007->m_Value.m_fValue; h.d ^= (DWORD)m_pConVar007; return h.f; } return 0; } int WrpConVarRef::GetInt(void) const { if (m_pConVar007) { //return m_pConVar007->GetInt(); xor_helper_t h; h.i = m_pConVar007->m_Value.m_nValue; h.d ^= (DWORD)m_pConVar007; return h.i; } return 0; } void WrpConVarRef::SetValue(float value) { if(m_pConVar007) m_pConVar007->SetValue(value); } void WrpConVarRef::SetValueFastHack(float value) { SetDirectHack(value); SetValue(value); } void WrpConVarRef::SetDirectHack(float value) { if(m_pConVar007) { xor_helper_t h; h.f = value; h.d ^= (DWORD)m_pConVar007; m_pConVar007->m_Value.m_fValue = h.f; h.i = (int)value; h.d ^= (DWORD)m_pConVar007; m_pConVar007->m_Value.m_nValue = h.i; } } // CSubWrpCommandArgs ////////////////////////////////////////////////////////// CSubWrpCommandArgs::CSubWrpCommandArgs(IWrpCommandArgs * commandArgs, int offset) : m_Offset(offset) , m_CommandArgs(commandArgs) { std::ostringstream oss; for (int i = 0; i<m_Offset; ++i) { if (0 < i) oss << " "; oss << m_CommandArgs->ArgV(i); } m_Prefix = oss.str(); } int CSubWrpCommandArgs::ArgC() { return m_CommandArgs->ArgC() -m_Offset +1; } char const * CSubWrpCommandArgs::ArgV(int i) { if(0 == i) { return m_Prefix.c_str(); } return m_CommandArgs->ArgV(i +m_Offset -1); }
12,242
5,004
module; #include <Windows.h> module main_window; LRESULT MainWindow::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_DESTROY: PostQuitMessage(0); return 0; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(m_hwnd, &ps); FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1)); EndPaint(m_hwnd, &ps); } return 0; default: return DefWindowProc(m_hwnd, uMsg, wParam, lParam); } return TRUE; }
605
221
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // #include "stdafx.h" #include "Common/ReaderTestHelper.h" using namespace Microsoft::MSR::CNTK; namespace Microsoft { namespace MSR { namespace CNTK { namespace Test { struct ImageReaderFixture : ReaderFixture { ImageReaderFixture() : ReaderFixture("/Data") { } }; BOOST_FIXTURE_TEST_SUITE(ReaderTestSuite, ImageReaderFixture) BOOST_AUTO_TEST_CASE(ImageReaderSimple) { HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderSimple_Config.cntk", testDataPath() + "/Control/ImageReaderSimple_Control.txt", testDataPath() + "/Control/ImageReaderSimple_Output.txt", "Simple_Test", "reader", 4, 4, 1, 1, 0, 0, 1); } BOOST_AUTO_TEST_CASE(ImageAndTextReaderSimple) { HelperRunReaderTest<float>( testDataPath() + "/Config/ImageAndTextReaderSimple_Config.cntk", testDataPath() + "/Control/ImageAndTextReaderSimple_Control.txt", testDataPath() + "/Control/ImageAndTextReaderSimple_Output.txt", "Simple_Test", "reader", 4, 4, 1, 1, 0, 0, 1); } BOOST_AUTO_TEST_CASE(ImageReaderBadMap) { BOOST_REQUIRE_EXCEPTION( HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderBadMap_Config.cntk", testDataPath() + "/Control/ImageReaderSimple_Control.txt", testDataPath() + "/Control/ImageReaderSimple_Output.txt", "Simple_Test", "reader", 4, 4, 1, 1, 0, 0, 1), std::runtime_error, [](std::runtime_error const& ex) { return string("Invalid map file format, must contain 2 or 3 tab-delimited columns, line 2 in file ./ImageReaderBadMap_map.txt.") == ex.what(); }); } BOOST_AUTO_TEST_CASE(ImageReaderBadLabel) { BOOST_REQUIRE_EXCEPTION( HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderBadLabel_Config.cntk", testDataPath() + "/Control/ImageReaderSimple_Control.txt", testDataPath() + "/Control/ImageReaderSimple_Output.txt", "Simple_Test", "reader", 4, 4, 1, 1, 0, 0, 1), std::runtime_error, [](std::runtime_error const& ex) { return string("Cannot parse label value on line 1, second column, in file ./ImageReaderBadLabel_map.txt.") == ex.what(); }); } BOOST_AUTO_TEST_CASE(ImageReaderLabelOutOfRange) { BOOST_REQUIRE_EXCEPTION( HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderLabelOutOfRange_Config.cntk", testDataPath() + "/Control/ImageReaderSimple_Control.txt", testDataPath() + "/Control/ImageReaderSimple_Output.txt", "Simple_Test", "reader", 4, 4, 1, 1, 0, 0, 1), std::runtime_error, [](std::runtime_error const& ex) { return string("Image 'images\\red.jpg' has invalid class id '10'. Expected label dimension is '4'. Line 3 in file ./ImageReaderLabelOutOfRange_map.txt.") == ex.what(); }); } BOOST_AUTO_TEST_CASE(ImageReaderZip) { HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderZip_Config.cntk", testDataPath() + "/Control/ImageReaderZip_Control.txt", testDataPath() + "/Control/ImageReaderZip_Output.txt", "Zip_Test", "reader", 4, 4, 1, 1, 0, 0, 1); } BOOST_AUTO_TEST_CASE(ImageReaderZipMissingFile) { BOOST_REQUIRE_EXCEPTION( HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderZipMissing_Config.cntk", testDataPath() + "/Control/ImageReaderZip_Control.txt", testDataPath() + "/Control/ImageReaderZip_Output.txt", "ZipMissing_Test", "reader", 4, 4, 1, 1, 0, 0, 1), std::runtime_error, [](std::runtime_error const& ex) { return string("Failed to get file info of missing.jpg, zip library error: Unknown error -1") == ex.what(); }); } BOOST_AUTO_TEST_CASE(ImageReaderMultiView) { HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderMultiView_Config.cntk", testDataPath() + "/Control/ImageReaderMultiView_Control.txt", testDataPath() + "/Control/ImageReaderMultiView_Output.txt", "MultiView_Test", "reader", 10, 10, 1, 1, 0, 0, 1); } BOOST_AUTO_TEST_CASE(ImageReaderIntensityTransform) { HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderIntensityTransform_Config.cntk", testDataPath() + "/Control/ImageReaderIntensityTransform_Control.txt", testDataPath() + "/Control/ImageReaderIntensityTransform_Output.txt", "IntensityTransform_Test", "reader", 1, 1, 2, 1, 0, 0, 1); } BOOST_AUTO_TEST_CASE(ImageReaderColorTransform) { HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderColorTransform_Config.cntk", testDataPath() + "/Control/ImageReaderColorTransform_Control.txt", testDataPath() + "/Control/ImageReaderColorTransform_Output.txt", "ColorTransform_Test", "reader", 1, 1, 2, 1, 0, 0, 1); } BOOST_AUTO_TEST_CASE(ImageReaderGrayscale) { HelperRunReaderTest<float>( testDataPath() + "/Config/ImageReaderGrayscale_Config.cntk", testDataPath() + "/Control/ImageReaderGrayscale_Control.txt", testDataPath() + "/Control/ImageReaderGrayscale_Output.txt", "Grayscale_Test", "reader", 1, 1, 1, 1, 0, 0, 1); } BOOST_AUTO_TEST_SUITE_END() } } } }
6,266
1,922
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/allocator/allocator_shim.h" #include <malloc.h> // This translation unit defines a default dispatch for the allocator shim which // routes allocations to libc functions. // The code here is strongly inspired from tcmalloc's libc_override_glibc.h. extern "C" { void* __libc_malloc(size_t size); void* __libc_calloc(size_t n, size_t size); void* __libc_realloc(void* address, size_t size); void* __libc_memalign(size_t alignment, size_t size); void __libc_free(void* ptr); } // extern "C" namespace { using base::allocator::AllocatorDispatch; void* GlibcMalloc(const AllocatorDispatch*, size_t size) { return __libc_malloc(size); } void* GlibcCalloc(const AllocatorDispatch*, size_t n, size_t size) { return __libc_calloc(n, size); } void* GlibcRealloc(const AllocatorDispatch*, void* address, size_t size) { return __libc_realloc(address, size); } void* GlibcMemalign(const AllocatorDispatch*, size_t alignment, size_t size) { return __libc_memalign(alignment, size); } void GlibcFree(const AllocatorDispatch*, void* address) { __libc_free(address); } size_t GlibcGetSizeEstimate(const AllocatorDispatch*, void* address) { // TODO(siggi, primiano): malloc_usable_size may need redirection in the // presence of interposing shims that divert allocations. return malloc_usable_size(address); } } // namespace const AllocatorDispatch AllocatorDispatch::default_dispatch = { &GlibcMalloc, /* alloc_function */ &GlibcCalloc, /* alloc_zero_initialized_function */ &GlibcMemalign, /* alloc_aligned_function */ &GlibcRealloc, /* realloc_function */ &GlibcFree, /* free_function */ &GlibcGetSizeEstimate, /* get_size_estimate_function */ nullptr, /* next */ };
1,953
657
#pragma once template <typename T> struct Schoenhage_Strassen_radix2 { T* buf = nullptr; void rot(T* dst, T* src, int s, int d) { assert(0 <= d and d < 2 * s); bool f = s <= d; if (s <= d) d -= s; int i = 0; if (f) { for (; i < s - d; i++) dst[i + d] = -src[i]; for (; i < s; i++) dst[i + d - s] = src[i]; } else { for (; i < s - d; i++) dst[i + d] = src[i]; for (; i < s; i++) dst[i + d - s] = -src[i]; } } void in_add(T* dst, T* src, int s) { for (int i = 0; i < s; i++) dst[i] += src[i]; } void in_sub(T* dst, T* src, int s) { for (int i = 0; i < s; i++) dst[i] -= src[i]; } void cp(T* dst, T* src, int s) { memcpy(dst, src, s * sizeof(T)); } void reset(T* dst, int s) { fill(dst, dst + s, T()); } // R[x] / (1 + x^(2^m)) ไธŠใฎ้•ทใ•2^LใฎFFT void fft(T* a, int l, int m) { if (l == 0) return; int L = 1 << l, M = 1 << m; assert(M * 2 >= L); assert(buf != nullptr); vector<int> dw(l - 1); for (int i = 0; i < l - 1; i++) { dw[i] = (1 << (l - 2 - i)) + (1 << (l - 1 - i)) - (1 << (l - 1)); if (dw[i] < 0) dw[i] += L; if (L == M) dw[i] *= 2; if (2 * L == M) dw[i] *= 4; } for (int d = L; d >>= 1;) { int w = 0; for (int s = 0, k = 0;;) { for (int i = s, j = s + d; i < s + d; ++i, ++j) { T *ai = a + i * M, *aj = a + j * M; rot(buf, aj, M, w); cp(aj, ai, M); in_add(ai, buf, M); in_sub(aj, buf, M); } if ((s += 2 * d) >= L) break; w += dw[__builtin_ctz(++k)]; if (w >= 2 * M) w -= 2 * M; } } } // R[x] / (1 + x^(2^m)) ไธŠใฎ้•ทใ•2^LใฎIFFT void ifft(T* a, int l, int m) { if (l == 0) return; int L = 1 << l, M = 1 << m; assert(M * 2 >= L); assert(buf != nullptr); vector<int> dw(l - 1); for (int i = 0; i < l - 1; i++) { dw[i] = (1 << (l - 2 - i)) + (1 << (l - 1 - i)) - (1 << (l - 1)); if (dw[i] < 0) dw[i] += L; if (L == M) dw[i] *= 2; if (2 * L == M) dw[i] *= 4; } for (int d = 1; d < L; d *= 2) { int w = 0; for (int s = 0, k = 0;;) { for (int i = s, j = s + d; i < s + d; ++i, ++j) { T *ai = a + i * M, *aj = a + j * M; cp(buf, ai, M); in_add(ai, aj, M); in_sub(buf, aj, M); rot(aj, buf, M, w); } if ((s += 2 * d) >= L) break; w -= dw[__builtin_ctz(++k)]; if (w < 0) w += 2 * M; } } } // a <- ab / (x^(2^n)+1) int naive_mul(T* a, T* b, int n) { int N = 1 << n; reset(buf, N); for (int i = 0; i < N; i++) { int j = 0; for (; j < N - i; j++) buf[i + j] += a[i] * b[j]; for (; j < N; j++) buf[i + j - N] -= a[i] * b[j]; } cp(a, buf, N); return 0; } // a <- ab / (x^(2^n)+1) int inplace_mul(T* a, T* b, int n) { if (n <= 5) { naive_mul(a, b, n); return 0; } int l = (n + 1) / 2; int m = n / 2; int L = 1 << l, M = 1 << m, N = 1 << n; int cnt = 0; // R[x] (x^(2^(m+1))-1) R[y] (y^(2^l)-1) vector<T> A(N * 2), B(N * 2); reset(buf + M, M); for (int i = 0, s = 0, ds = 2 * M / L; i < L; i++) { // y -> x^{2m/r} y cp(buf, a + i * M, M); rot(A.data() + i * M * 2, buf, 2 * M, s); cp(buf, b + i * M, M); rot(B.data() + i * M * 2, buf, 2 * M, s); s += ds; if (s >= 4 * M) s -= 4 * M; } fft(A.data(), l, m + 1); fft(B.data(), l, m + 1); for (int i = 0; i < L; i++) { cnt = inplace_mul(A.data() + i * M * 2, B.data() + i * M * 2, m + 1); } ifft(A.data(), l, m + 1); for (int i = 0, s = 0, ds = 2 * M / L; i < L; i++) { // y -> x^{-2m/r} y cp(buf, A.data() + i * M * 2, 2 * M); rot(A.data() + i * M * 2, buf, 2 * M, s); s -= ds; if (s < 0) s += 4 * M; } for (int i = 0; i < L; i++) { for (int j = 0; j < M; j++) { a[i * M + j] = A[i * M * 2 + j]; if (i == 0) { a[i * M + j] -= A[(L - 1) * M * 2 + M + j]; } else { a[i * M + j] += A[(i - 1) * M * 2 + M + j]; } } } return cnt + l; } // a <- ab / (x^(2^n)-1) int inplace_mul2(T* a, T* b, int n) { if (n <= 5) { naive_mul(a, b, n); return 0; } int l = (n + 1) / 2; int m = n / 2; int L = 1 << l, M = 1 << m, N = 1 << n; int cnt = 0; // R[x] (x^(2^(m+1))-1) R[y] (y^(2^l)-1) vector<T> A(N * 2), B(N * 2); for (int i = 0; i < L; i++) { cp(A.data() + i * M * 2, a + i * M, M); cp(B.data() + i * M * 2, b + i * M, M); } fft(A.data(), l, m + 1); fft(B.data(), l, m + 1); for (int i = 0; i < L; i++) { cnt = inplace_mul(A.data() + i * M * 2, B.data() + i * M * 2, m + 1); } ifft(A.data(), l, m + 1); for (int i = 0; i < L; i++) { for (int j = 0; j < M; j++) { a[i * M + j] = A[i * M * 2 + j]; a[i * M + j] += A[(i ? i - 1 : L - 1) * M * 2 + M + j]; } } return cnt + l; } pair<vector<T>, int> multiply(const vector<T>& a, const vector<T>& b) { int L = a.size() + b.size() - 1; int M = 1, m = 0; while (M < L) M *= 2, m++; buf = new T[M]; vector<T> s(M), t(M); for (int i = 0; i < (int)a.size(); i++) s[i] = a[i]; for (int i = 0; i < (int)b.size(); i++) t[i] = b[i]; int cnt = inplace_mul2(s.data(), t.data(), m); vector<T> u(L); for (int i = 0; i < L; i++) u[i] = s[i]; delete[] buf; return make_pair(u, cnt); } }; /** * @brief Schรถnhage-Strassen Algorithm(radix-2) */
5,612
2,823
#include <iostream> using namespace std; class Animal { public: Animal(const string &st) : Name(st) {} // ะฒะฐัˆ ะบะพะด const string Name; }; class Dog: public Animal { public: Dog(const string &st): Animal(st) {} void Bark() { cout << Name << " barks: woof!" << endl; } };
312
111
#define DETOURS_ARM64_OFFLINE_LIBRARY #include "disasm.cpp"
60
29
#include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> P; typedef pair<ll, ll> Pll; typedef vector<int> Vi; typedef tuple<int, int, int> T; #define FOR(i,s,x) for(int i=s;i<(int)(x);i++) #define REP(i,x) FOR(i,0,x) #define ALL(c) c.begin(), c.end() #define MP make_pair #define DUMP( x ) cerr << #x << " = " << ( x ) << endl #define fst first #define snd second const int dx[6] = {0, 1, 1, 0, -1, -1}; const int dy[6] = {1, 1, 0, -1, -1, 0}; int board[128][128]; int geta = 64; int main() { ios_base::sync_with_stdio(false); while (1) { int t, n; cin >> t >> n; if (t == 0 && n == 0) break; memset(board, 0, sizeof(board)); REP(i, n) { int x, y; cin >> x >> y; board[y+geta][x+geta] = -1; } int sx, sy; cin >> sx >> sy; queue<T> que; que.push(T(sx, sy, t)); while (!que.empty()) { int x, y, rest; tie(x, y, rest) = que.front(); que.pop(); if (rest < 0 || board[y+geta][x+geta] != 0) continue; board[y+geta][x+geta] = 1; REP(i, 6) { int nx = x + dx[i], ny = y + dy[i]; que.push(T(nx, ny, rest - 1)); } } int ans = 0; REP(i, 128) REP(j, 128) ans += board[i][j] > 0; cout << ans << endl; } return 0; }
1,298
623
// NOAA POES Monte Carlo Simulation v1.3, 17/09/2008e // MEPED (Medium Energy Proton and Electron Detector) // Karl Yando, Professor Robyn Millan // Dartmouth College, 2008 // // "MEPED_DetectorMessenger.hh" - (generic) #ifndef MEPED_DetectorMessenger_h #define MEPED_DetectorMessenger_h 1 #include "globals.hh" #include "G4UImessenger.hh" class MEPED_DetectorConstruction; class G4UIdirectory; class G4UIcmdWithAString; class G4UIcmdWithAnInteger; class G4UIcmdWithADoubleAndUnit; class G4UIcmdWithoutParameter; class MEPED_DetectorMessenger: public G4UImessenger { public: MEPED_DetectorMessenger(MEPED_DetectorConstruction* ); ~MEPED_DetectorMessenger(); void SetNewValue(G4UIcommand*, G4String); private: MEPED_DetectorConstruction* MEPED_Detector; G4UIdirectory* MEPEDDir; G4UIdirectory* detDir; G4UIcmdWithAString* DeteMaterCmd; G4UIcmdWithAString* ShieldMaterCmd; G4UIcmdWithAString* HouseMaterCmd; G4UIcmdWithAString* ContactMaterCmd; G4UIcmdWithAString* BelvilleMaterCmd; G4UIcmdWithAString* InsulatorMaterCmd; G4UIcmdWithAString* FoilMaterCmd; G4UIcmdWithADoubleAndUnit* DetectorThickCmd; G4UIcmdWithoutParameter* UpdateCmd; }; #endif
1,304
494
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include "engine/core/image/image.hpp" #include "engine/core/tensor/tensor.hpp" #include "third_party/nlohmann/json.hpp" namespace isaac { // Convert the image encoded in yuyv to rgb. // The yuyv format is described here: // https://www.linuxtv.org/downloads/v4l-dvb-apis-old/V4L2-PIX-FMT-YUYV.html void ConvertYuyvToRgb(const Image2ub& yuyv, Image3ub& rgb); // Convert a pixels colorspace from rgb to hsv. // The rgb values are expected to be in [0, 1]. // The result will have H in [0, 360], S in [0, 255], V in [0, 255]. // https://en.wikipedia.org/wiki/HSL_and_HSV Pixel3f RgbToHsv(const Pixel3f& rgb); // Convert a float32 RGBA image to a uint8 RGB image // Input RGBA pixel values are expected to be in [0, 1]. // Result RGB pixel values will be in [0, 255]. void ConvertRgbaToRgb(ImageConstView4f source, ImageView3ub target); // Convert a uint8 RGBA image to a uint8 RGB image dropping the alpha channel void ConvertRgbaToRgb(ImageConstView4ub source, ImageView3ub target); // Convert a uint8 BGRA image to a uint8 RGB image dropping the alpha channel void ConvertBgraToRgb(ImageConstView4ub source, ImageView3ub target); // Convert a uint8 RGB image to a uint8 RGBA image and sets the alpha channel to `alpha`. void ConvertRgbToRgba(ImageConstView3ub source, ImageView4ub target, uint8_t alpha = 255); // Converts a uint16_t image to a 1f image using a scale factor void ConvertUi16ToF32(ImageConstView1ui16 source, ImageView1f target, float scale); // Converts a 1f image to a uint16_t image using a scale factor void ConvertF32ToUi16(ImageConstView1f source, ImageView1ui16 target, float scale); // The indexing order for row, column, channel can be specified by the ImageToTensorIndexOrder // enum. enum class ImageToTensorIndexOrder { k012 = 1, // Specifies ordering as row, column, channel k201 = 2 // Specifies ordering as channel, row, column }; // Use strings when serializing ImageToTensorIndexOrder enum NLOHMANN_JSON_SERIALIZE_ENUM(ImageToTensorIndexOrder, { {ImageToTensorIndexOrder::k012, "012"}, {ImageToTensorIndexOrder::k201, "201"}, }); // The normalization method for row, column, channel can be specified by the // ImageToTensorNormalization enum. enum class ImageToTensorNormalization { kNone = 1, kUnit = 2, // Normalize each pixel intensity into a range [0, 1] or vice versa kPositiveNegative = 3, // Normalize each pixel intensity into a range [-1, 1] or vice versa kHalfAndHalf = 4 // Normalize each pixel intensity into a range [-0.5, 0.5] or vice versa }; // Use strings when serializing ImageToTensorNormalization enum NLOHMANN_JSON_SERIALIZE_ENUM(ImageToTensorNormalization, { {ImageToTensorNormalization::kNone, "None"}, {ImageToTensorNormalization::kUnit, "Unit"}, {ImageToTensorNormalization::kPositiveNegative, "PositiveNegative"}, {ImageToTensorNormalization::kHalfAndHalf, "HalfAndHalf"}, }); // Copy an image into a tensor and normalize each pixel intensity into a given range. void ImageToNormalizedTensor( ImageConstView3ub rgb_image, Tensor3f& tensor, ImageToTensorIndexOrder index_order = ImageToTensorIndexOrder::k012, ImageToTensorNormalization normalization = ImageToTensorNormalization::kPositiveNegative); // Converts a 3-channel 8-bit image to a 32-bit floating point tensor. void ImageToNormalizedTensor( CudaImageConstView3ub rgb_image, CudaTensorView3f result, ImageToTensorIndexOrder index_order = ImageToTensorIndexOrder::k012, ImageToTensorNormalization normalization = ImageToTensorNormalization::kPositiveNegative); // Copy a tensor into an image and normalize each pixel intensity into into a given range. void NormalizedTensorToImage( TensorConstView3f tensor, ImageToTensorNormalization normalization, Image3ub& rgb_image); } // namespace isaac
4,281
1,411
#include <fstream> #include <vector> #include <string> #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <vector> #include <algorithm> #include <numeric> #include <iterator> #include <valarray> #include <climits> #include <sstream> #include <sys/stat.h> #include <bitset> #include "SurfaceSource.hpp" /* Adapated from https://wiki.calculquebec.ca/w/C%2B%2B_:_fichier_Fortran_binaire/en */ void SurfaceSource::Init(){ // init paramters strncpy(id, " \0" , 9 ); strncpy(kods, " \0" , 9 ); strncpy(vers, " \0" , 6 ); strncpy(lods, " \0" , 9 ); strncpy(idtms, " \0" , 20 ); strncpy(probs, " \0" , 20 ); strncpy(aids, " \0" , 81 ); knods = 0; np1 = 0; nrss = 0; nrcd = 0; njsw = 0; niss = 0; niwr = 0; mipts = 0; kjaq = 0; surface_count = 0; // init particle lookup table strncpy(particles[ 1-1].name , "neutron\0" , 8); strncpy(particles[ 5-1].name , "anti-neutron\0" ,13); strncpy(particles[ 2-1].name , "photon\0" , 7); strncpy(particles[ 3-1].name , "electron\0" , 9); strncpy(particles[ 8-1].name , "positron\0" , 9); strncpy(particles[ 4-1].name , "muon-\0" , 6); strncpy(particles[ 16-1].name , "muon+\0" , 6); strncpy(particles[ 6-1].name , "electron neutrino\0" ,18); strncpy(particles[ 17-1].name , "anti-electron neutrino\0" ,23); strncpy(particles[ 7-1].name , "muon neutrino\0" ,14); strncpy(particles[ 18-1].name , "anti muon neutrino\0" ,19); strncpy(particles[ 9-1].name , "proton\0" , 7); strncpy(particles[ 19-1].name , "anti-proton\0" ,12); strncpy(particles[ 10-1].name , "lambda baryon\0" ,14); strncpy(particles[ 25-1].name , "anti lambda baryon\0" ,19); strncpy(particles[ 11-1].name , "positive sigma baryon\0" ,22); strncpy(particles[ 26-1].name , "anti positive sigma baryon\0" ,17); strncpy(particles[ 12-1].name , "negative sigma baryon\0" ,22); strncpy(particles[ 27-1].name , "anti negative sigma baryon\0" ,27); strncpy(particles[ 13-1].name , "cascade\0" , 8); strncpy(particles[ 28-1].name , "anti cascade\0" ,13); strncpy(particles[ 14-1].name , "negative cascade\0" ,17); strncpy(particles[ 29-1].name , "positive cascade\0" ,17); strncpy(particles[ 15-1].name , "omega baryon\0" ,13); strncpy(particles[ 30-1].name , "anti omega baryon\0" ,18); strncpy(particles[ 20-1].name , "positive pion\0" ,14); strncpy(particles[ 35-1].name , "negative pion\0" ,14); strncpy(particles[ 21-1].name , "neutral pion\0" ,13); strncpy(particles[ 22-1].name , "positive kaon\0" ,14); strncpy(particles[ 36-1].name , "negative kaon\0" ,14); strncpy(particles[ 23-1].name , "kaon, short\0" ,12); strncpy(particles[ 24-1].name , "kaon, long\0" ,11); strncpy(particles[ 31-1].name , "deuteron\0" , 9); strncpy(particles[ 32-1].name , "triton\0" , 7); strncpy(particles[ 33-1].name , "helion\0" , 7); strncpy(particles[ 34-1].name , "alpha\0" , 6); strncpy(particles[ 37-1].name , "heavy ions\0" ,11); // strncpy(particles[ 1-1].symbol , "n\0", 2); strncpy(particles[ 5-1].symbol , "q\0", 2); strncpy(particles[ 2-1].symbol , "p\0", 2); strncpy(particles[ 3-1].symbol , "e\0", 2); strncpy(particles[ 8-1].symbol , "f\0", 2); strncpy(particles[ 4-1].symbol , "|\0", 2); strncpy(particles[ 16-1].symbol , "!\0", 2); strncpy(particles[ 6-1].symbol , "u\0", 2); strncpy(particles[ 17-1].symbol , "<\0", 2); strncpy(particles[ 7-1].symbol , "v\0", 2); strncpy(particles[ 18-1].symbol , ">\0", 2); strncpy(particles[ 9-1].symbol , "h\0", 2); strncpy(particles[ 19-1].symbol , "g\0", 2); strncpy(particles[ 10-1].symbol , "l\0", 2); strncpy(particles[ 25-1].symbol , "b\0", 2); strncpy(particles[ 11-1].symbol , "+\0", 2); strncpy(particles[ 26-1].symbol , "_\0", 2); strncpy(particles[ 12-1].symbol , "-\0", 2); strncpy(particles[ 27-1].symbol , "~\0", 2); strncpy(particles[ 13-1].symbol , "x\0", 2); strncpy(particles[ 28-1].symbol , "c\0", 2); strncpy(particles[ 14-1].symbol , "y\0", 2); strncpy(particles[ 29-1].symbol , "w\0", 2); strncpy(particles[ 15-1].symbol , "o\0", 2); strncpy(particles[ 30-1].symbol , "@\0", 2); strncpy(particles[ 20-1].symbol , "/\0", 2); strncpy(particles[ 35-1].symbol , "*\0", 2); strncpy(particles[ 21-1].symbol , "z\0", 2); strncpy(particles[ 22-1].symbol , "k\0", 2); strncpy(particles[ 36-1].symbol , "?\0", 2); strncpy(particles[ 23-1].symbol , "%\0", 2); strncpy(particles[ 24-1].symbol , "^\0", 2); strncpy(particles[ 31-1].symbol , "d\0", 2); strncpy(particles[ 32-1].symbol , "t\0", 2); strncpy(particles[ 33-1].symbol , "s\0", 2); strncpy(particles[ 34-1].symbol , "a\0", 2); strncpy(particles[ 37-1].symbol , "#\0", 2); // init surface lookup table strncpy(surface_card[ 0].symbol , "XXX\0" , 4); strncpy(surface_card[ 1].symbol , "p \0" , 4); strncpy(surface_card[ 2].symbol , "px \0" , 4); strncpy(surface_card[ 3].symbol , "py \0" , 4); strncpy(surface_card[ 4].symbol , "pz \0" , 4); strncpy(surface_card[ 5].symbol , "so \0" , 4); strncpy(surface_card[ 6].symbol , "s \0" , 4); strncpy(surface_card[ 7].symbol , "sx \0" , 4); strncpy(surface_card[ 8].symbol , "sy \0" , 4); strncpy(surface_card[ 9].symbol , "sz \0" , 4); strncpy(surface_card[10].symbol , "c/x\0" , 4); strncpy(surface_card[11].symbol , "c/y\0" , 4); strncpy(surface_card[12].symbol , "c/z\0" , 4); strncpy(surface_card[13].symbol , "cx \0" , 4); strncpy(surface_card[14].symbol , "cy \0" , 4); strncpy(surface_card[15].symbol , "cz \0" , 4); strncpy(surface_card[16].symbol , "k/x\0" , 4); strncpy(surface_card[17].symbol , "k/y\0" , 4); strncpy(surface_card[18].symbol , "k/z\0" , 4); strncpy(surface_card[19].symbol , "kx \0" , 4); strncpy(surface_card[20].symbol , "ky \0" , 4); strncpy(surface_card[21].symbol , "kz \0" , 4); strncpy(surface_card[22].symbol , "sq \0" , 4); strncpy(surface_card[23].symbol , "gq \0" , 4); strncpy(surface_card[24].symbol , "tx \0" , 4); strncpy(surface_card[25].symbol , "ty \0" , 4); strncpy(surface_card[26].symbol , "tz \0" , 4); strncpy(surface_card[27].symbol , "x \0" , 4); strncpy(surface_card[28].symbol , "y \0" , 4); strncpy(surface_card[29].symbol , "z \0" , 4); strncpy(surface_card[30].symbol , "box\0" , 4); strncpy(surface_card[31].symbol , "rpp\0" , 4); strncpy(surface_card[32].symbol , "sph\0" , 4); strncpy(surface_card[33].symbol , "rcc\0" , 4); strncpy(surface_card[34].symbol , "rec\0" , 4); strncpy(surface_card[35].symbol , "ell\0" , 4); strncpy(surface_card[36].symbol , "trc\0" , 4); strncpy(surface_card[37].symbol , "wed\0" , 4); strncpy(surface_card[38].symbol , "arb\0" , 4); strncpy(surface_card[39].symbol , "rhp\0" , 4); strncpy(surface_card[40].symbol , "hex\0" , 4); // surface_card[ 0].n_coefficients = 0; surface_card[ 1].n_coefficients = 4; surface_card[ 2].n_coefficients = 1; surface_card[ 3].n_coefficients = 1; surface_card[ 4].n_coefficients = 1; surface_card[ 5].n_coefficients = 1; surface_card[ 6].n_coefficients = 4; surface_card[ 7].n_coefficients = 2; surface_card[ 8].n_coefficients = 2; surface_card[ 9].n_coefficients = 2; surface_card[10].n_coefficients = 3; surface_card[11].n_coefficients = 3; surface_card[12].n_coefficients = 3; surface_card[13].n_coefficients = 1; surface_card[14].n_coefficients = 1; surface_card[15].n_coefficients = 1; surface_card[16].n_coefficients = 5; surface_card[17].n_coefficients = 5; surface_card[18].n_coefficients = 5; surface_card[19].n_coefficients = 3; surface_card[20].n_coefficients = 3; surface_card[21].n_coefficients = 3; surface_card[22].n_coefficients = 10; surface_card[23].n_coefficients = 10; surface_card[24].n_coefficients = 6; surface_card[25].n_coefficients = 6; surface_card[26].n_coefficients = 6; surface_card[27].n_coefficients = 0; surface_card[28].n_coefficients = 0; surface_card[29].n_coefficients = 0; surface_card[30].n_coefficients = 12; surface_card[31].n_coefficients = 6; surface_card[32].n_coefficients = 4; surface_card[33].n_coefficients = 7; surface_card[34].n_coefficients = 12; surface_card[35].n_coefficients = 7; surface_card[36].n_coefficients = 8; surface_card[37].n_coefficients = 12; surface_card[38].n_coefficients = 30; surface_card[39].n_coefficients = 15; surface_card[40].n_coefficients = 15; // strncpy(surface_card[ 0].description , "INDEXING ERROR \0", 41); strncpy(surface_card[ 1].description , "General plane \0", 41); strncpy(surface_card[ 2].description , "Plane normal to X-axis \0", 41); strncpy(surface_card[ 3].description , "Plane normal to Y-axis \0", 41); strncpy(surface_card[ 4].description , "Plane normal to Z-axis \0", 41); strncpy(surface_card[ 5].description , "Sphere centered at the origin \0", 41); strncpy(surface_card[ 6].description , "General sphere \0", 41); strncpy(surface_card[ 7].description , "Sphere centered on X-axis \0", 41); strncpy(surface_card[ 8].description , "Sphere centered on Y-axis \0", 41); strncpy(surface_card[ 9].description , "Sphere centered on Z-axis \0", 41); strncpy(surface_card[10].description , "Cylinder parallel to X-axis \0", 41); strncpy(surface_card[11].description , "Cylinder parallel to Y-axis \0", 41); strncpy(surface_card[12].description , "Cylinder parallel to Z-axis \0", 41); strncpy(surface_card[13].description , "Cylinder on X-axis \0", 41); strncpy(surface_card[14].description , "Cylinder on Y-axis \0", 41); strncpy(surface_card[15].description , "Cylinder on Z-axis \0", 41); strncpy(surface_card[16].description , "Cone parallel to X-axis \0", 41); strncpy(surface_card[17].description , "Cone parallel to Y-axis \0", 41); strncpy(surface_card[18].description , "Cone parallel to Z-axis \0", 41); strncpy(surface_card[19].description , "Cone on X-axis \0", 41); strncpy(surface_card[20].description , "Cone on Y-axis \0", 41); strncpy(surface_card[21].description , "Cone on Z-axis \0", 41); strncpy(surface_card[22].description , "Quadric parallel to X-,Y-, or Z-axis \0", 41); strncpy(surface_card[23].description , "Quadric not parallel to X-,Y-, or Z-axis\0", 41); strncpy(surface_card[24].description , "Torus parallel to X-axis \0", 41); strncpy(surface_card[25].description , "Torus parallel to Y-axis \0", 41); strncpy(surface_card[26].description , "Torus parallel to Z-axis \0", 41); strncpy(surface_card[27].description , "Surface defined by points sym. about X \0", 41); strncpy(surface_card[28].description , "Surface defined by points sym. about Y \0", 41); strncpy(surface_card[29].description , "Surface defined by points sym. about Z \0", 41); strncpy(surface_card[30].description , "Arbitrarily oriented orthogonal box \0", 41); strncpy(surface_card[31].description , "Rectangular Parallelepiped \0", 41); strncpy(surface_card[32].description , "Sphere \0", 41); strncpy(surface_card[33].description , "Right Circular Cylinder \0", 41); strncpy(surface_card[34].description , "Right Elliptical Cylinder \0", 41); strncpy(surface_card[35].description , "Ellipsoid \0", 41); strncpy(surface_card[36].description , "Truncated Right-angle Cone \0", 41); strncpy(surface_card[37].description , "Wedge \0", 41); strncpy(surface_card[38].description , "Arbitrary polydron \0", 41); strncpy(surface_card[39].description , "Right Hexagonal Prism \0", 41); strncpy(surface_card[40].description , "Right Hexagonal Prism - Same as RHP \0", 41); } // // CON/DE-STRUCTORS // SurfaceSource::~SurfaceSource(){ input_file.close(); output_file.close(); } SurfaceSource::SurfaceSource(const std::string& fileName){ Init(); OpenWssaFile_Read(fileName.c_str()); } SurfaceSource::SurfaceSource(const std::string& fileName1, const std::string& fileName2){ Init(); OpenWssaFile_Read( fileName1.c_str()); OpenWssaFile_Write(fileName2.c_str()); } SurfaceSource::SurfaceSource(const char* fileName){ Init(); OpenWssaFile_Read(fileName); } SurfaceSource::SurfaceSource(const char* fileName1, const char* fileName2){ Init(); OpenWssaFile_Read(fileName1); OpenWssaFile_Write(fileName2); } SurfaceSource::SurfaceSource(const std::string& fileName, const int flag){ Init(); switch(flag){ case RSSA_READ: OpenWssaFile_Read( fileName.c_str()); break; case RSSA_WRITE: OpenWssaFile_Write(fileName.c_str()); break; } } SurfaceSource::SurfaceSource(const char* fileName, const int flag){ Init(); switch(flag){ case RSSA_READ: OpenWssaFile_Read( fileName); break; case RSSA_WRITE: OpenWssaFile_Write(fileName); break; } } // // FILE IO // bool SurfaceSource::OpenWssaFile_Read(const char* fileName){ // for file check struct stat buffer; // set object name input_file_name.assign(fileName); // open file if( (stat (fileName, &buffer) == 0)){ input_file.open(fileName, std::ios::in | std::ios::binary); return true; } else{ printf("problem opening %s for reading.\n",fileName); return false; } } bool SurfaceSource::OpenWssaFile_Write(const char* fileName){ // for file check struct stat buffer; // set object name output_file_name.assign(fileName); // open file, make sure it doens't already exist if( (stat (fileName, &buffer) != 0)){ output_file.open(fileName, std::ios::out | std::ios::binary); return true; } else{ printf("problem opening %s for writing.\n",fileName); return false; } } // // RECORD READS // bool SurfaceSource::ReadRecord(void** destination, size_t* size, size_t NumberOfEntries) { int record_length0 = 0; int record_length1 = 0; int null = 0; int length_read = 0; int dist_to_end = 0; if (input_file.good()) { // read starting delimiter input_file.read((char*) &record_length0, RECORD_DELIMITER_LENGTH); //printf("READ RECORD LENGTH %d\n",record_length0); // read what's asked for for(int i=0;i<NumberOfEntries;i++){ length_read = length_read + size[i]; if(length_read>record_length0){ printf("DATA REQUESTED (%d) OVERRAN RECORD LENGTH (%d)!\n",length_read,record_length0); return false; } else{ input_file.read((char*) destination[i], size[i]); } } // go to the end of the record dist_to_end = record_length0-length_read; if( dist_to_end > 0 ){ printf("--> skipping ahead %d bytes to end of record after %d entries\n",dist_to_end, NumberOfEntries); input_file.seekg(dist_to_end, std::ios::cur); } // read ending delimiter, assert input_file.read((char*) &record_length1, RECORD_DELIMITER_LENGTH); if(record_length0!=record_length1){ printf("BEGINNING (%d) AND ENDING (%d) RECORD LENGTH DELIMITERS DO NOT MATCH\n",record_length0,record_length1); return false; } else{ return true; } } else { return false; } } bool SurfaceSource::ReadSurfaceRecord0(int* numbers, int* types, int* lengths, surface* parameters) { // internal variables int record_length0 = 0; int record_length1 = 0; // read record if (input_file.good()) { input_file.read((char*) &record_length0, sizeof(record_length0)); input_file.read((char*) numbers, sizeof(int)); input_file.read((char*) types, sizeof(int)); input_file.read((char*) lengths, sizeof(int)); input_file.read((char*) parameters,lengths[0]*sizeof(parameters->value[0])); input_file.read((char*) &record_length1, sizeof(record_length1)); if(record_length0!=record_length1){ printf("SurfaceRecord0 BEGINNING (%d) AND ENDING (%d) RECORD LENGTH DELIMITERS DO NOT MATCH\n",record_length0,record_length1); return false; } else{ return true; } } else { return false; } } bool SurfaceSource::ReadSurfaceRecord1(int* numbers, int* types, int* lengths, surface* parameters, int* facets) { // internal variables int record_length = 0; if (input_file.good()) { input_file.read((char*) &record_length, sizeof(record_length)); input_file.read((char*) numbers, sizeof(int)); input_file.read((char*) facets, sizeof(int)); input_file.read((char*) types, sizeof(int)); input_file.read((char*) lengths, sizeof(int)); input_file.read((char*) parameters,lengths[0]*sizeof(parameters->value[0])); input_file.seekg(RECORD_DELIMITER_LENGTH, std::ios::cur); return true; } else { return false; } } bool SurfaceSource::ReadSummaryRecord(int** summaries) { int record_length0 = 0; int record_length1 = 0; int null = 0; double dnull = 0.0; int length_read = 0; int dist_to_end = 0; int this_record_legnth = 0; if (input_file.good()) { // read starting delimiter input_file.read((char*) &record_length0, RECORD_DELIMITER_LENGTH); //printf("RECORD LENGTH %d\n",record_length0); // read dumb leading (double) zero input_file.read((char*) &dnull, sizeof(double)); length_read = sizeof(double); // read what's asked for for(int i=0;i<surface_count;i++){ for(int j=0;j<surface_summary_length;j++){ length_read = length_read + sizeof(int); if(length_read>record_length0){ printf("SUMMARY DATA REQUESTED (%d) OVERRAN RECORD LENGTH (%d)!\n",length_read,record_length0); return false; } else{ input_file.read((char*) &summaries[i][j], sizeof(int)); } } } // go to the end of the record dist_to_end = record_length0-length_read; if( dist_to_end > 0 ){ printf("--> skipping ahead %d bytes to end of record\n",dist_to_end); input_file.seekg(dist_to_end, std::ios::cur); } // read ending delimiter, assert input_file.read((char*) &record_length1, RECORD_DELIMITER_LENGTH); if(record_length0!=record_length1){ printf("BEGINNING (%d) AND ENDING (%d) SUMMARY RECORD LENGTH DELIMITERS DO NOT MATCH\n",record_length0,record_length1); return false; } else{ return true; } } else { return false; } } // // RECORD WRITES // bool SurfaceSource::WriteRecord(void** source, size_t* size, size_t NumberOfEntries) { int record_length0 = 0; for (int i=0;i<NumberOfEntries;i++){ record_length0 += size[i]; } //printf("WRITE RECORD LENGTH %d\n",record_length0); if (output_file.good()) { // read starting delimiter output_file.write((char*) &record_length0, RECORD_DELIMITER_LENGTH); // write what's given for(int i=0;i<NumberOfEntries;i++){ output_file.write((char*) source[i], size[i]); } // write ending delimiter output_file.write((char*) &record_length0, RECORD_DELIMITER_LENGTH); return true; } else { printf("OUTPUT FILE NOT GOOD.\n"); return false; } } bool SurfaceSource::WriteSurfaceRecord0(int* numbers, int* types, int* lengths, surface* parameters) { // internal variables int record_length = 3*sizeof(int) + lengths[0]*sizeof(parameters->value[0]); // write record if (output_file.good()) { output_file.write((char*) &record_length, RECORD_DELIMITER_LENGTH); output_file.write((char*) numbers, sizeof(int)); output_file.write((char*) types, sizeof(int)); output_file.write((char*) lengths, sizeof(int)); output_file.write((char*) parameters,lengths[0]*sizeof(parameters->value[0])); output_file.write((char*) &record_length, RECORD_DELIMITER_LENGTH); return true; } else { return false; } } bool SurfaceSource::WriteSurfaceRecord1(int* numbers, int* types, int* lengths, surface* parameters, int* facets) { // internal variables int record_length = 4*sizeof(int) + lengths[0]*sizeof(parameters->value[0]); if (output_file.good()) { output_file.write((char*) &record_length, RECORD_DELIMITER_LENGTH); output_file.write((char*) numbers, sizeof(int)); output_file.write((char*) facets, sizeof(int)); output_file.write((char*) types, sizeof(int)); output_file.write((char*) lengths, sizeof(int)); output_file.write((char*) parameters,lengths[0]*sizeof(parameters->value[0])); output_file.write((char*) &record_length, RECORD_DELIMITER_LENGTH); return true; } else { return false; } } bool SurfaceSource::WriteSummaryRecord(int** summaries) { int record_length0 = surface_summary_length*surface_count*sizeof(int)+sizeof(double); int null = 0; double dnull = 0.0; int length_write = 0; if (output_file.good()) { // write starting delimiter output_file.write((char*) &record_length0, RECORD_DELIMITER_LENGTH); // write stupid leading (double) zero output_file.write((char*) &dnull, sizeof(double)); // write what's asked for for(int i=0;i<surface_count;i++){ for(int j=0;j<surface_summary_length;j++){ length_write = length_write + sizeof(int); output_file.write((char*) &summaries[i][j], sizeof(int)); } } // write ending delimiter, assert output_file.write((char*) &record_length0, RECORD_DELIMITER_LENGTH); return true; } else { return false; } } // // HIGHER LEVEL ROUTINES // void SurfaceSource::ReadHeader(){ // HEADER FORMATTING // // record 1: id; // record 2: kods,vers,lods,idtms,probs,aids,knods; // record 3: np1,nrss,nrcd,njsw,niss; // record 4: niwr,mipts,kjaq; // // id = The ID string, should be SF_00001 for MCNP6-made surface source, char8 // kods = code name, char8 // vers = code version, char5 // lods = LODDAT of code that wrote surface source file, char8 // idtms = IDTM of the surface source write run, char19 // probs = probid, problem id, char19 // aids = title string of the creation run, char80 // knods = ending dump number, int // np1 = total number of histories in SS write run, int // nrss = the total number of tracks recorded, int // nrcd = Number of values in a surface-source record, int // njsw = Number of surfaces in JASW, int // niss = Number of histories in input surface source, int // niwr = Number of cells in RSSA file, int // mipts = Source particle type, int // kjaq = Flag for macrobody facets on source tape, int // // // the next njsw+niwr records describe the surfaces/cells in the SS // // // the last record is the SS summary vector // first record void** pointers = new void* [20]; size_t* sizes = new size_t [20]; size_t size = 1; pointers[0] = (void**) &id; sizes[0] = sizeof(id)-1; if(!ReadRecord(pointers, sizes, size)){printf("ERROR READING FIRST RECORD\n");std::exit(1);} // second record, first make array of pointers, then sizes size = 7; pointers[0] = (void*) &kods; pointers[1] = (void*) &vers; pointers[2] = (void*) &lods; pointers[3] = (void*) &idtms; pointers[4] = (void*) &probs; pointers[5] = (void*) &aids; pointers[6] = (void*) &knods; sizes[0] = sizeof(kods)-1; sizes[1] = sizeof(vers)-1; sizes[2] = sizeof(lods)-1; sizes[3] = sizeof(idtms)-1; sizes[4] = sizeof(probs)-1; sizes[5] = sizeof(aids)-1; sizes[6] = sizeof(knods); if(!ReadRecord(pointers, sizes, size)){printf("ERROR READING SECOND RECORD\n");std::exit(1);} // third record, first make array of pointers, then sizes size = 5; pointers[0] = (void*) &np1; pointers[1] = (void*) &nrss; pointers[2] = (void*) &nrcd; pointers[3] = (void*) &njsw; pointers[4] = (void*) &niss; sizes[0] = sizeof(np1); sizes[1] = sizeof(nrss); sizes[2] = sizeof(nrcd); sizes[3] = sizeof(njsw); sizes[4] = sizeof(niss); if(!ReadRecord(pointers, sizes, size)){printf("ERROR READING THIRD RECORD\n");std::exit(1);} // fourth record, first make array of pointers, then sizes size = 3+17; // 17 zeros written after for whatever reason! pointers[0] = (void*) &niwr; pointers[1] = (void*) &mipts; pointers[2] = (void*) &kjaq; int null = 0; for (int g=3;g<3+17;g++){pointers[g]=&null;} sizes[0] = sizeof(niwr); sizes[1] = sizeof(mipts); sizes[2] = sizeof(kjaq); for (int g=3;g<3+17;g++){sizes[g]=sizeof(null);} if(!ReadRecord(pointers, sizes, size)){printf("ERROR READING FOURTH RECORD\n");std::exit(1);} // init arays for surface information surface_count = njsw+niwr; surface_parameters = new surface [surface_count]; surface_parameters_lengths = new int [surface_count]; surface_numbers = new int [surface_count]; surface_types = new int [surface_count]; surface_facets = new int [surface_count]; surface_summaries = new int* [surface_count]; for(int i = 0 ; i < surface_count ; i++){ for(int j = 0 ; j < 10 ; j++){ surface_parameters [i].value[j] = 0; } surface_summaries[i] = new int [surface_summary_length]; for(int k=0;k<surface_summary_length;k++){ surface_summaries[i][k]=0; } surface_numbers [i] = -1; surface_facets [i] = -1; } // go on, copying surface/cell information from the next records until particle data starts for(int i = 0 ; i < surface_count ; i++){ if( kjaq==0 | i>njsw-1 ) { ReadSurfaceRecord0(&surface_numbers[i],&surface_types[i],&surface_parameters_lengths[i],&surface_parameters[i]); } if( kjaq==1 & i<=njsw-1 ) { ReadSurfaceRecord1(&surface_numbers[i],&surface_types[i],&surface_parameters_lengths[i],&surface_parameters[i],&surface_facets[i]); } } // last record is the summary tables ReadSummaryRecord(surface_summaries); } void SurfaceSource::WriteHeader(){ // HEADER FORMATTING // // record 1: id; // record 2: kods,vers,lods,idtms,probs,aids,knods; // record 3: np1,nrss,nrcd,njsw,niss; // record 4: niwr,mipts,kjaq; // // id = The ID string, should be SF_00001 for MCNP6-made surface source, char8 // kods = code name, char8 // vers = code version, char5 // lods = LODDAT of code that wrote surface source file, char8 // idtms = IDTM of the surface source write run, char19 // probs = probid, problem id, char19 // aids = title string of the creation run, char80 // knods = ending dump number, int // np1 = total number of histories in SS write run, int // nrss = the total number of tracks recorded, int // nrcd = Number of values in a surface-source record, int // njsw = Number of surfaces in JASW, int // niss = Number of histories in input surface source, int // niwr = Number of cells in RSSA file, int // mipts = Source particle type, int // kjaq = Flag for macrobody facets on source tape, int // // // the next njsw+niwr records describe the surfaces/cells in the SS // // // the last record is the SS summary vector // first record int largest_size = 3+17; void** pointers = new void* [largest_size]; size_t* sizes = new size_t [largest_size]; size_t size = 1; pointers[0] = (void**) &id; sizes[0] = sizeof(id)-1; if(!WriteRecord(pointers, sizes, size)){printf("ERROR WRITING FIRST RECORD\n");std::exit(1);} // second record, first make array of pointers, then sizes size = 7; pointers[0] = (void*) &kods; pointers[1] = (void*) &vers; pointers[2] = (void*) &lods; pointers[3] = (void*) &idtms; pointers[4] = (void*) &probs; pointers[5] = (void*) &aids; pointers[6] = (void*) &knods; sizes[0] = sizeof(kods)-1; sizes[1] = sizeof(vers)-1; sizes[2] = sizeof(lods)-1; sizes[3] = sizeof(idtms)-1; sizes[4] = sizeof(probs)-1; sizes[5] = sizeof(aids)-1; sizes[6] = sizeof(knods); if(!WriteRecord(pointers, sizes, size)){printf("ERROR WRITING SECOND RECORD\n");std::exit(1);} // third record, first make array of pointers, then sizes size = 5; pointers[0] = (void*) &np1; pointers[1] = (void*) &nrss; pointers[2] = (void*) &nrcd; pointers[3] = (void*) &njsw; pointers[4] = (void*) &niss; sizes[0] = sizeof(np1); sizes[1] = sizeof(nrss); sizes[2] = sizeof(nrcd); sizes[3] = sizeof(njsw); sizes[4] = sizeof(niss); if(!WriteRecord(pointers, sizes, size)){printf("ERROR WRITING THIRD RECORD\n");std::exit(1);} // fourth record, first make array of pointers, then sizes size = 3+17; pointers[0] = (void*) &niwr; pointers[1] = (void*) &mipts; pointers[2] = (void*) &kjaq; int null = 0; for (int g=3;g<size;g++){pointers[g]=&null;} sizes[0] = sizeof(niwr); sizes[1] = sizeof(mipts); sizes[2] = sizeof(kjaq); for (int g=3;g<size;g++){sizes[g]=sizeof(null);} if(!WriteRecord(pointers, sizes, size)){printf("ERROR WRITING FOURTH RECORD\n");std::exit(1);} // init arays for surface information //surface_count = njsw+niwr; //surface_parameters = new surface [surface_count]; //surface_parameters_lengths = new int [surface_count]; //surface_numbers = new int [surface_count]; //surface_types = new int [surface_count]; //surface_facets = new int [surface_count]; //surface_summaries = new int* [surface_count]; //for(int i = 0 ; i < surface_count ; i++){ // for(int j = 0 ; j < 10 ; j++){ // surface_parameters [i].value[j] = 0; // } // surface_summaries[i] = new int [surface_summary_length]; // for(int k=0;k<surface_summary_length;k++){ // surface_summaries[i][k]=0; // } // surface_numbers [i] = -1; // surface_facets [i] = -1; //} // go on, copying surface/cell information from the next records until particle data starts for(int i = 0 ; i < surface_count ; i++){ if( kjaq==0 | i>njsw-1 ) { WriteSurfaceRecord0(&surface_numbers[i],&surface_types[i],&surface_parameters_lengths[i],&surface_parameters[i]); } if( kjaq==1 & i<=njsw-1 ) { WriteSurfaceRecord1(&surface_numbers[i],&surface_types[i],&surface_parameters_lengths[i],&surface_parameters[i],&surface_facets[i]); } } // last record is the summary tables WriteSummaryRecord(surface_summaries); output_file.flush(); } void SurfaceSource::PrintSizes(){ printf("== DATA SIZE INFORMATION == \n"); printf("normal integers : %1ld bytes\n", sizeof(knods)); printf("floating points : %1ld bytes\n", sizeof(surface_parameters->value[0])); printf("characters : %1ld bytes\n", sizeof(id[0])); printf("\n"); } void SurfaceSource::PrintHeader(){ printf("=========================================== HEADER INFORMATION =========================================== \n"); printf("RSSA ID string : %8s \n", id); printf("code name : %8s \n", kods); printf("code version : %5s \n", vers); printf("LODDAT of code that wrote surface source file : %8s \n", lods); printf("IDTM of the surface source write run : %19s\n", idtms); printf("probid, problem id : %19s\n", probs); printf("title string of the creation run : %80s\n", aids); printf("ending dump number : %d\n", knods); printf("total number of histories in SS write run : %lld\n", np1); printf("the total number of tracks recorded : %lld\n", nrss); printf("Number of values in a surface-source record : %d\n", nrcd); printf("Number of surfaces in JASW : %d\n", njsw); printf("Number of histories in input surface source : %lld\n", niss); printf("Number of cells in RSSA file : %d\n", niwr); printf("Source particle type : %d\n", mipts); printf("Flag for macrobody facets on source tape : %d\n", kjaq); if( kjaq == 0 ) { printf("\n============================================================ SURFACE INFORMATION ============================================================ \n"); printf("creation-run surfaces | surface | type | coefficients\n"); } else if( kjaq == 1 ) { printf("\n============================================================ SURFACE INFORMATION ============================================================ \n"); printf("creation-run surfaces | surface | facet | type | coefficients\n"); } for(int i = 0 ; i < surface_count ; i++){ if( kjaq == 0 ) { printf(" %5d %5d %s ",i,surface_numbers[i],surface_card[surface_types[i]].symbol); for(int j = 0 ; j < surface_parameters_lengths[i] ; j++){ printf(" % 10.8E",surface_parameters[i].value[j]); } printf("\n"); } else if( kjaq == 1 ) { printf(" %5d %5d %1d %s ",i,surface_numbers[i],surface_facets[i],surface_card[surface_types[i]].symbol); for(int j = 0 ; j < surface_parameters_lengths[i] ; j++){ printf(" % 10.8E",surface_parameters[i].value[j]); } printf("\n"); } } printf("\n"); printf("\n============================================================= SURFACE SUMMARIES ============================================================= \n"); int a,b,c,d; for(int i=0;i<surface_count;i++){ printf("--=== Surface %5d ===--\n",surface_numbers[i]); printf("%20s %21s\n","TOTAL TRACKS","INDEPENDENT HISTORIES"); printf(" %12d %12d\n",surface_summaries[i][0],surface_summaries[i][1]); for(int j=0;j<mipts;j++){ a = surface_summaries[i][(2+j*4)+0]; b = surface_summaries[i][(2+j*4)+1]; c = surface_summaries[i][(2+j*4)+2]; d = surface_summaries[i][(2+j*4)+3]; if (a+b+c+d > 0){ printf("---- %s ----\n",particles[j].name); printf("%20s %20s %20s %20s\n","TOTAL TRACKS","INDEPENDENT TRACKS","UNCOLLIDED","INDEP. UNCOLLIDED"); printf(" %12d %12d %12d %12d\n",a,b,c,d); } } printf("\n"); } } void SurfaceSource::GetTrack(track* this_track){ // local vars size_t sizes = 11*sizeof(double); // try reading it all in at once... copy from array to make sure struct padding doesn't do anything... double* this_track_data = new double [12]; if(!ReadRecord((void**) &this_track_data, &sizes, 1)){printf("ERROR READING TRACKS RECORD\n");std::exit(1);} this_track->nps = this_track_data[ 0]; this_track->bitarray = this_track_data[ 1]; this_track->wgt = this_track_data[ 2]; this_track->erg = this_track_data[ 3]; this_track->tme = this_track_data[ 4]; this_track->x = this_track_data[ 5]; this_track->y = this_track_data[ 6]; this_track->z = this_track_data[ 7]; this_track->xhat = this_track_data[ 8]; this_track->yhat = this_track_data[ 9]; this_track->cs = this_track_data[10]; this_track->zhat = this_track_data[11]; delete this_track_data; // calculate missing zhat from the data if ((this_track->xhat*this_track->xhat+this_track->yhat*this_track->yhat)<1.0){ this_track->zhat = copysign(std::sqrt(1.0 - this_track->xhat*this_track->xhat - this_track->yhat*this_track->yhat), this_track->bitarray); } else{ this_track->zhat = 0.0; } } void SurfaceSource::PutTrack(double nps, double bitarray, double wgt, double erg, double tme, double x, double y, double z, double xhat, double yhat, double cs, double zhat){ // local vars size_t sizes = 11*sizeof(double); // only write the first 11, track in record doesn't have zhat double* this_track_data = new double [12]; this_track_data[ 0] = nps ; this_track_data[ 1] = bitarray; this_track_data[ 2] = wgt ; this_track_data[ 3] = erg ; this_track_data[ 4] = tme ; this_track_data[ 5] = x ; this_track_data[ 6] = y ; this_track_data[ 7] = z ; this_track_data[ 8] = xhat ; this_track_data[ 9] = yhat ; this_track_data[10] = cs ; this_track_data[11] = zhat ; // writing it all in at once... if(!WriteRecord((void**) &this_track_data, &sizes, 1)){printf("ERROR WRITING TRACK RECORD\n");std::exit(1);} delete this_track_data; } void SurfaceSource::PutTrack(track* this_track){ // pass to other method since it copies to a continguous array, so contiguity is guranteed, some compilers might pad the struct... PutTrack( this_track->nps, this_track->bitarray, this_track->wgt, this_track->erg, this_track->tme, this_track->x, this_track->y, this_track->z, this_track->xhat, this_track->yhat, this_track->cs, this_track->zhat ); }
36,350
15,746
// SPDX-License-Identifier: MIT constexpr char const* const PDI_CFG = R"PDI_CFG( metadata: Nx : int Nvx : int iter : int time_saved : double nbstep_diag: int iter_saved : int MeshX_extents: { type: array, subtype: int64, size: 1 } MeshX: type: array subtype: double size: [ '$MeshX_extents[0]' ] MeshVx_extents: { type: array, subtype: int64, size: 1 } MeshVx: type: array subtype: double size: [ '$MeshVx_extents[0]' ] Nkinspecies: int fdistribu_charges_extents : { type: array, subtype: int64, size: 1 } fdistribu_charges: type: array subtype: int size: [ '$fdistribu_charges_extents[0]' ] fdistribu_masses_extents : { type: array, subtype: int64, size: 1 } fdistribu_masses: type: array subtype: double size: [ '$fdistribu_masses_extents[0]' ] fdistribu_eq_extents : { type: array, subtype: int64, size: 2 } fdistribu_eq: type: array subtype: double size: [ '$fdistribu_eq_extents[0]', '$fdistribu_eq_extents[1]' ] data: fdistribu_extents: { type: array, subtype: int64, size: 3 } fdistribu: type: array subtype: double size: [ '$fdistribu_extents[0]', '$fdistribu_extents[1]', '$fdistribu_extents[2]' ] electrostatic_potential_extents: { type: array, subtype: int64, size: 1 } electrostatic_potential: type: array subtype: double size: [ '$electrostatic_potential_extents[0]' ] plugins: set_value: on_init: - share: - iter_saved: 0 on_data: iter: - set: - iter_saved: '${iter}/${nbstep_diag}' on_finalize: - release: [iter_saved] decl_hdf5: - file: 'VOICEXX_initstate.h5' on_event: [initial_state] collision_policy: replace_and_warn write: [Nx, Nvx, MeshX, MeshVx, nbstep_diag, Nkinspecies, fdistribu_charges,fdistribu_masses, fdistribu_eq] - file: 'VOICEXX_${iter_saved:05}.h5' on_event: [iteration, last_iteration] when: '${iter} % ${nbstep_diag} = 0' collision_policy: replace_and_warn write: [time_saved, fdistribu, electrostatic_potential] #trace: ~ )PDI_CFG";
2,111
864
/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */ #include <iostream> #include <iomanip> #include "PhaseFit.h" #include "Stats.h" PhaseFit::PhaseFit() { read.resize(0); signal.resize(0); residual_raw_vec.resize(0); residual_weighted_vec.resize(0); err.resize(0); flowString = ""; flowCycle.resize(0); concentration.resize(0); cf.resize(0); ie.resize(0); dr.resize(0); nFlow = 0; droopType = ONLY_WHEN_INCORPORATING; maxAdv = 0; droopAdvancerFirst.resize(0); extendAdvancerFirst.resize(0); droopAdvancer.resize(0); extendAdvancer.resize(0); flowWeight.resize(0); ignoreHPs = false; extraTaps = 0; residualType = SQUARED; residualSummary = MEAN; } void PhaseFit::InitializeFlowSpecs( string _flowString, vector<weight_vec_t> _concentration, weight_vec_t _cf, weight_vec_t _ie, weight_vec_t _dr, unsigned int _nFlow, DroopType _droopType, unsigned int _maxAdv ) { read.resize(0); signal.resize(0); flowString = _flowString; flowCycle.resize(flowString.length()); for(unsigned int iFlow=0; iFlow<flowString.length(); iFlow++) flowCycle[iFlow] = charToNuc(flowString[iFlow]); concentration = _concentration; cf = _cf; ie = _ie; dr = _dr; nFlow = _nFlow; droopType = _droopType; maxAdv = _maxAdv; } void PhaseFit::AddRead(weight_vec_t &seqFlow, weight_vec_t &sig, weight_t maxErr) { // Convert vector of continuous values to ints hpLen_vec_t hpFlow; vector<unsigned int> untrustedFlow; weight_vec_t::iterator iSeqFlow=seqFlow.begin(); for(unsigned int iFlow=0; iSeqFlow != seqFlow.end(); iFlow++, iSeqFlow++) { // Round the signal hpLen_t rounded = (hpLen_t) floor(*iSeqFlow + 0.5); hpFlow.push_back(rounded); // Check if it was larger than we'd like weight_t err = abs(*iSeqFlow - (weight_t) rounded); if(err > maxErr) untrustedFlow.push_back(iFlow); } // Set weights weight_vec_t newHpWeight(seqFlow.size(),1); if(untrustedFlow.size() > 0) { unsigned int first_to_ignore = std::max(((int)untrustedFlow[0])-4,1); for(weight_vec_t::iterator iHpWeight=newHpWeight.begin()+first_to_ignore; iHpWeight != newHpWeight.end(); iHpWeight++) *iHpWeight = 0; } //cout << "Weights: "; //for(unsigned int i=0; i<newHpWeight.size(); i++) // cout << ", " << setiosflags(ios::fixed) << setprecision(2) << newHpWeight[i]; //cout << "\n"; // Set up the read PhaseSim newRead; newRead.setDroopType(droopType); newRead.setFlowCycle(flowString); newRead.setSeq(hpFlow); newRead.setAdvancerContexts(maxAdv); newRead.setExtraTaps(extraTaps); // Store the results read.push_back(newRead); hpWeight.push_back(newHpWeight); signal.push_back(sig); } void PhaseFit::AddRead(string seq, weight_vec_t &sig) { PhaseSim newRead; newRead.setDroopType(droopType); newRead.setFlowCycle(flowString); newRead.setSeq(seq); newRead.setAdvancerContexts(maxAdv); newRead.setExtraTaps(extraTaps); read.push_back(newRead); signal.push_back(sig); } int PhaseFit::LevMarFit(int max_iter, int nParam, float *params) { unsigned int nRead = signal.size(); int nData = nRead * nFlow; // Call LevMarFitter::Initialize() - the 3rd arg is null as we don't need access to // the LevMarFitter's internal x array in the calls to Evaluate Initialize(nParam,nData,NULL); // Update LevMarFitter::residualWeight array if we are using flow-specific weighting or // if we are ignoring homopolymers of size > 1 if( (!ignoreHPs) || (flowWeight.size() > 0) || (hpWeight.size() > 0) ) updateResidualWeight(ignoreHPs, flowWeight, hpWeight); // Gather the observed data into an array of floats float *y = new float[nData]; unsigned int iY=0; for(unsigned int iRead=0; iRead<nRead; iRead++) for(unsigned int iFlow=0; iFlow<nFlow; iFlow++) y[iY++] = (float) signal[iRead][iFlow]; err.resize(nData); int nIter = LevMarFitter::Fit(max_iter, y, params); // Store the (possibly weighted) residuals float *fval = new float[len]; Evaluate(fval,params); residual_raw_vec.resize(nRead); residual_weighted_vec.resize(nRead); for(unsigned int iRead=0,iY=0; iRead<nRead; iRead++) { residual_raw_vec[iRead].resize(nFlow); residual_weighted_vec[iRead].resize(nFlow); for(unsigned int iFlow=0; iFlow<nFlow; iFlow++, iY++) { weight_t res = y[iY] - fval[iY]; residual_raw_vec[iRead][iFlow] = res; residual_weighted_vec[iRead][iFlow] = residualWeight[iY] * res; } } delete [] fval; delete [] y; return(nIter); } void PhaseFit::updateResidualWeight(bool ignoreHPs, weight_vec_t &flowWeight, vector<weight_vec_t> &hpWeight) { // residualWeight is initialized in the call to LevMarFitter::Initialize(nparams,len,x) // so this function should be called just after that call and if(len > 0) { // Initialize all weights to 1 for(int iRes=0; iRes<len; iRes++) residualWeight[iRes] = 1; // Apply per-flow multipliers unsigned int nRead = read.size(); if(flowWeight.size() > 0) { unsigned int iRes = 0; for(unsigned int iRead=0; iRead < nRead; iRead++) { for(unsigned int iFlow=0; iFlow<nFlow; iFlow++, iRes++) { if(iFlow >= flowWeight.size()) throw("flowWeight vector is shorter than the number of flows in one or more of the reads."); residualWeight[iRes] *= flowWeight[iFlow]; } } } // Apply per-flow multipliers if(hpWeight.size() > 0) { if(hpWeight.size()!=nRead) throw("hpWeight vector should be either empty or of the same length as the number of reads"); unsigned int iRes = 0; for(unsigned int iRead=0; iRead < nRead; iRead++) { for(unsigned int iFlow=0; iFlow<nFlow; iFlow++, iRes++) { residualWeight[iRes] *= hpWeight[iRead][iFlow]; } } } // Optionally ignore residuals for homopolymer runs of length larger than 1 if(ignoreHPs) { unsigned int iRes = 0; for(unsigned int iRead=0; iRead < nRead; iRead++) { const hpLen_vec_t seqFlow = read[iRead].getSeqFlow(); for(unsigned int iFlow=0; iFlow<nFlow; iFlow++, iRes++) { if(seqFlow[iFlow] > 1) residualWeight[iRes] = 0; } } } } //cout << "weight for first read:\n"; //for(unsigned int iFlow=0, iRes=0; iFlow<nFlow; iFlow++, iRes++) // cout << ", " << setiosflags(ios::fixed) << setprecision(2) << residualWeight[iRes]; //cout << "\n"; } void PhaseFit::PrintResidual(float *params) { unsigned int nRead = signal.size(); unsigned int nData = nRead * nFlow; float *tmp = new float[nData]; Evaluate(tmp,params); float *y = new float[nData]; for(unsigned int iRead=0, iY=0; iRead<nRead; iRead++) for(unsigned int iFlow=0; iFlow<nFlow; iFlow++) y[iY++] = (float) signal[iRead][iFlow]; float res = CalcResidual(y, tmp, len); cout << "Residual = " << setiosflags(ios::fixed) << setprecision(3) << res << "\n"; for(unsigned int iRead=0, iY=0; iRead<std::min(nRead,(unsigned int)2); iRead++) { cout << "raw res [" << iRead << "]: "; unsigned int iYsave = iY; for(unsigned int iFlow=0; iFlow<nFlow; iFlow++,iY++) cout << " " << setiosflags(ios::fixed) << setprecision(3) << y[iY] - tmp[iY]; cout << "\n"; iY = iYsave; cout << "wt res [" << iRead << "]: "; for(unsigned int iFlow=0; iFlow<nFlow; iFlow++,iY++) cout << " " << setiosflags(ios::fixed) << setprecision(3) << residualWeight[iY] * (y[iY] - tmp[iY]); cout << "\n"; } delete [] y; delete [] tmp; } float PhaseFit::CalcResidual(float *refVals, float *testVals, int numVals, double *err_vec) { // Compute raw residuals and if necessary, return them for (int i=0;i < numVals;i++) err[i] = residualWeight[i] * (refVals[i]-testVals[i]); if (err_vec) for (int i=0;i < numVals;i++) err_vec[i] = err[i]; // Transform residuals switch(residualType) { case(SQUARED): for (int i=0;i < numVals;i++) err[i] = pow(err[i], 2.0); break; case(ABSOLUTE): for (int i=0;i < numVals;i++) err[i] = abs(err[i]); break; case(GEMAN_MCCLURE): for (int i=0;i < numVals;i++) err[i] = ionStats::geman_mcclure(err[i]); break; default: throw("Invalid residual type"); } // Summarize the residuals float r=0; float numerator=0; float denominator=0; unsigned int nRead = signal.size(); weight_vec_t readErr; switch(residualSummary) { case(MEAN): for (int i=0;i < numVals;i++) if(residualWeight[i] > 0) { numerator += err[i]; denominator += residualWeight[i]; } r = numerator/denominator; break; case(MEDIAN): readErr.reserve(numVals); for (int i=0;i < numVals;i++) if(residualWeight[i] > 0) readErr.push_back(err[i]); r = ionStats::median(readErr); break; case(MEAN_OF_MEDIAN): readErr.reserve(nFlow); for(unsigned int iRead=0, iErr=0; iRead<nRead; iRead++) { readErr.resize(0); for(unsigned int iFlow=0; iFlow<nFlow; iFlow++,iErr++) { if(residualWeight[iErr] > 0) readErr.push_back(err[iErr]); } if(readErr.size() > 0) { numerator += readErr.size() * ionStats::median(readErr); denominator += readErr.size(); } } r = numerator/denominator; break; case(MEDIAN_OF_MEAN): readErr.reserve(nRead); readErr.resize(0); for(unsigned int iRead=0, iErr=0; iRead<nRead; iRead++) { numerator = 0; denominator = 0; for(unsigned int iFlow=0; iFlow<nFlow; iFlow++,iErr++) { if(residualWeight[iErr] > 0) { numerator += err[iErr]; denominator += residualWeight[iErr]; } } if(denominator > 0) readErr.push_back(numerator/denominator); } r = ionStats::median(readErr); break; default: throw("Invalid residual summary method"); } return r; }
10,247
3,858
// // exe_wwinmain.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // // The mainCRTStartup() entry point, linked into client executables that // uses main(). // #define _SCRT_STARTUP_MAIN #include "exe_common.inl" extern "C" int mainCRTStartup() { return __scrt_common_main(); }
312
110
#include <stdio.h> #define _USE_MATH_DEFINES #include <math.h> #include "libgtkgraph/gtkgraph.h" #include "libgtkgraph/gtkgraph_internal.h" /* Declaration of all local functions */ static GtkGraphAnnotation *gtk_graph_annotation_allocate(void); /* Externally referenceable functions */ static GtkGraphAnnotation *gtk_graph_annotation_allocate(void) { GtkGraphAnnotation *tmp; tmp = (GtkGraphAnnotation *) g_malloc(sizeof(GtkGraphAnnotation)); if (tmp == (GtkGraphAnnotation *) NULL) { (void) fprintf(stderr,"malloc failed at: %s\n","gtk_graph_trace_allocate"); return ((GtkGraphAnnotation *) NULL); } tmp->type = VERTICAL; tmp->value = 0; tmp->text = NULL; tmp->next = NULL; return(tmp); } /** * gtk_graph_annotation_new: * @graph: The #GtkGraph that you wish to add the annotation to * * Adds an annotation to a pre-existing #GtkGraph @graph. * * Returns: an unique integer identifying the new annotation. This must be * stored if you wish to alter the properties of the annotation */ gint gtk_graph_annotation_new(GtkGraph *graph) { int i; GtkGraphAnnotation *new_annotation, *tmp; g_return_val_if_fail (graph != NULL, FALSE); g_return_val_if_fail (GTK_IS_GRAPH (graph), FALSE); new_annotation = gtk_graph_annotation_allocate(); if (graph->annotations == NULL) graph->annotations = new_annotation; else { for (i = 0, tmp = graph->annotations; tmp->next != NULL ; tmp = tmp->next , i++) // Should advance us to last item in list ; tmp->next = new_annotation; } graph->num_annotations += 1; return graph->num_annotations - 1; } /** * gtk_graph_annotation_set_data: * @graph: the #GtkGraph that contains the annotation you wish to modify * @annotation_id: the unique integer ID returned by gtk_graph_annotation_new() * @type: * @value: value at which to display the annotation * @text: any text that you want displayed next to the * * The function description goes here. You can use @par1 to refer to parameters * so that they are highlighted in the output. You can also use %constant * for constants, function_name2() for functions and #GtkWidget for links to * other declarations (which may be documented elsewhere). */ void gtk_graph_annotation_set_data(GtkGraph *graph, gint annotation_id, GtkGraphAnnotationType type, gfloat value, gchar *text) { GtkGraphAnnotation *t; gint i; g_return_if_fail (graph != NULL); g_return_if_fail (GTK_IS_GRAPH (graph)); if (graph->annotations == NULL) return; g_return_if_fail (annotation_id < graph->num_annotations); t = graph->annotations; for (i = 0 ; i < annotation_id ; i++) t = t->next; t->type = type; t->value = value; t->text = g_strdup(text); } void gtk_graph_plot_annotations(GtkGraph *graph) { gint n; gint plotting_value, text_width, text_height; GtkGraphAnnotation *tmp; PangoFontDescription *fontdesc = NULL; PangoLayout *layout = NULL; gint centre_x = user_width / 2.0 + user_origin_x, xpos; gint centre_y = user_height / 2.0 + user_origin_y, ypos; gfloat theta, new_angle, r; gchar *text_buffer = NULL; //gint horizontal_position = user_origin_x; gint vertical_position = user_origin_y; g_return_if_fail (graph != NULL); g_return_if_fail (GTK_IS_GRAPH (graph)); g_return_if_fail (gtk_widget_get_realized(GTK_WIDGET(graph))); if (graph->annotations == NULL) return; fontdesc = pango_font_description_from_string("Sans 9"); layout = gtk_widget_create_pango_layout(GTK_WIDGET(graph), NULL); pango_layout_set_font_description(layout, fontdesc); tmp = graph->annotations; for (n = 0 ; n < graph->num_annotations ; n++) { switch(tmp->type) { case HORIZONTAL: if (graph->graph_type != XY) /* Skip on if the graph is not the correct type */ continue; /* Ensure that we are within the plotable range and then draw the line*/ plotting_value = (gint) rint((graph->dependant->axis_max - tmp->value ) * graph->dependant->scale_factor) + user_origin_y; if (tmp->value < graph->dependant->axis_min) plotting_value = (gint) rint((graph->dependant->axis_max - graph->dependant->axis_min) * graph->dependant->scale_factor) + user_origin_y; if (tmp->value > graph->dependant->axis_max) plotting_value = user_origin_y; gdk_draw_line(buffer, BlueandWcontext, user_origin_x, plotting_value, (graph->independant->n_maj_tick * graph->independant->pxls_per_maj_tick ) + user_origin_x, plotting_value); /* Set text and then plot above line if value is below half way and vice versa */ if (text_buffer) g_free(text_buffer); if (tmp->text) text_buffer = g_strdup_printf( "%s\nY: %.2f", tmp->text, tmp->value); else text_buffer = g_strdup_printf("Y: %.2f", tmp->value); pango_layout_set_text(layout, text_buffer, -1); pango_layout_get_pixel_size(layout, &text_width, &text_height); if (tmp->value <= (graph->dependant->axis_max - graph->dependant->axis_min) / 2.0) gdk_draw_layout(buffer, BandWcontext, (graph->independant->n_maj_tick * graph->independant->pxls_per_maj_tick )/2 + user_origin_x, plotting_value - text_height - 2, layout); else gdk_draw_layout(buffer, BandWcontext, (graph->independant->n_maj_tick * graph->independant->pxls_per_maj_tick )/2 + user_origin_x, plotting_value + 2, layout); break; case VERTICAL: if (graph->graph_type != XY) /* Skip on if the graph is not the correct type */ continue; /* Ensure that we are within the plotable range and then draw the line*/ plotting_value = (gint) rint((tmp->value - graph->independant->axis_min ) * graph->independant->scale_factor) + user_origin_x; if (tmp->value < graph->independant->axis_min) plotting_value = user_origin_x; if (tmp->value > graph->independant->axis_max) plotting_value = user_origin_x + graph->independant->pxls_per_maj_tick * graph->independant->n_maj_tick; gdk_draw_line(buffer, BlueandWcontext, plotting_value, user_origin_y, plotting_value, user_origin_y + graph->dependant->pxls_per_maj_tick * graph->dependant->n_maj_tick); /* Set text and then plot to the left if line on the right of the middle and vice versa */ if (text_buffer) g_free(text_buffer); if (tmp->text) text_buffer = g_strdup_printf("%s\nX: %.2f", tmp->text, tmp->value); else text_buffer = g_strdup_printf("X: %.2f", tmp->value); pango_layout_set_text(layout, text_buffer, -1); pango_layout_get_pixel_size(layout, &text_width, &text_height); if (tmp->value <= (graph->independant->axis_max - graph->independant->axis_min) / 2.0) gdk_draw_layout(buffer, BandWcontext, plotting_value +2, vertical_position, layout); else gdk_draw_layout(buffer, BandWcontext, plotting_value - text_width - 2, vertical_position, layout); vertical_position += text_height; break; case RADIAL: if (graph->graph_type != POLAR) continue; new_angle = wrap_angle(tmp->value, graph->polar_format); if (graph->polar_format.type >> 2) // i.e. one of the radian options theta = new_angle + graph->polar_format.polar_start; else // otherwise we must be in degrees theta = (new_angle + graph->polar_format.polar_start) * M_PI / 180.0; xpos = centre_x + (gint) (user_width / 2.0 * sin(theta)); ypos = centre_y - (gint) (user_height / 2.0 * cos(theta)); gdk_draw_line(buffer, BlueandWcontext, centre_x, centre_y, xpos, ypos); if (text_buffer) g_free(text_buffer); if (tmp->text) text_buffer = g_strdup_printf("%s\nTheta: %.2f", tmp->text, tmp->value); else text_buffer = g_strdup_printf("Theta: %.1f", tmp->value); pango_layout_set_text(layout, text_buffer, -1); pango_layout_get_pixel_size(layout, &text_width, &text_height); if (xpos > centre_x) { if (ypos >= centre_y) gdk_draw_layout(buffer, BandWcontext, xpos, ypos, layout); else gdk_draw_layout(buffer, BandWcontext, xpos, ypos-text_height - 2, layout); } else { if (ypos >= centre_y) gdk_draw_layout(buffer, BandWcontext, xpos - text_width - 2, ypos, layout); else gdk_draw_layout(buffer, BandWcontext, xpos - text_width - 2, ypos - text_height - 2, layout); } break; case AZIMUTHAL: if (graph->graph_type != POLAR) continue; plotting_value = (gint) rint(((tmp->value - graph->dependant->axis_min ) * graph->dependant->scale_factor)); if (tmp->value < graph->dependant->axis_min) plotting_value = 0; if (tmp->value > graph->dependant->axis_max) plotting_value = (gint) rint((graph->dependant->axis_max - graph->dependant->axis_min) * graph->dependant->scale_factor); gdk_draw_arc(buffer, BlueandWcontext, FALSE, centre_x - plotting_value, centre_y - plotting_value, 2.0 * plotting_value, 2.0 * plotting_value, 0, 23040); if (text_buffer) g_free(text_buffer); if (tmp->text) text_buffer = g_strdup_printf( "%s\nRadius: %.1f", tmp->text, tmp->value); else text_buffer = g_strdup_printf( "Radius: %.1f", tmp->value); pango_layout_set_text(layout, text_buffer, -1); pango_layout_get_pixel_size(layout, &text_width, &text_height); gdk_draw_layout(buffer, BandWcontext, centre_x - plotting_value / 1.414 - text_width - 2, centre_y - plotting_value / 1.414 - text_height, layout); break; case VSWR: if (graph->graph_type != SMITH) continue; plotting_value = fabs((tmp->value - 1.0)/(tmp->value + 1.0))*graph->dependant->scale_factor; gdk_draw_arc(buffer, BlueandWcontext, FALSE, centre_x - plotting_value, centre_y - plotting_value, 2.0 * plotting_value, 2.0 * plotting_value, 0, 23040); if (text_buffer) g_free(text_buffer); if (tmp->text) text_buffer = g_strdup_printf( "%s\nVSWR: %.1f", tmp->text, tmp->value); else text_buffer = g_strdup_printf( "VSWR: %.1f", tmp->value); pango_layout_set_text(layout, text_buffer, -1); pango_layout_get_pixel_size(layout, &text_width, &text_height); break; case Q: if (graph->graph_type != SMITH) continue; plotting_value = (1.0 / tmp->value) * graph->dependant->scale_factor; r = sqrt(1.0 / (tmp->value * tmp->value) + 1.0) * graph->dependant->scale_factor; theta = atan(1.0 / tmp->value) * 180.0 / M_PI * 64; gdk_draw_arc(buffer, BlueandWcontext, FALSE, centre_x - r, centre_y + plotting_value - r, 2.0 * r, 2.0 * r, theta, 11520 - 2.0 * theta); gdk_draw_arc(buffer, BlueandWcontext, FALSE, centre_x - r, centre_y - plotting_value - r, 2.0 * r, 2.0 * r, 11520 + theta, 11520 - 2.0 * theta); if (text_buffer) g_free(text_buffer); if (tmp->text) text_buffer = g_strdup_printf( "%s\nQ: %.1f", tmp->text, tmp->value); else text_buffer = g_strdup_printf( "Q: %.1f", tmp->value); pango_layout_set_text(layout, text_buffer, -1); pango_layout_get_pixel_size(layout, &text_width, &text_height); gdk_draw_layout(buffer, BandWcontext, centre_x - text_width / 2, centre_y - plotting_value + r, layout); break; } /* and then move onto the next trace */ tmp = tmp->next; } pango_font_description_free(fontdesc); g_object_unref(layout); }
10,952
4,396
/* * OXRS_MQTT.cpp * */ #include "Arduino.h" #include "OXRS_MQTT.h" #ifdef MQTT_ENABLE_STREAMING #include <StreamUtils.h> #endif // Topic constants static const char * MQTT_CONFIG_TOPIC = "conf"; static const char * MQTT_COMMAND_TOPIC = "cmnd"; static const char * MQTT_STATUS_TOPIC = "stat"; static const char * MQTT_TELEMETRY_TOPIC = "tele"; OXRS_MQTT::OXRS_MQTT(PubSubClient& client) { this->_client = &client; // Set the buffer size (depends on MCU we are running on) _client->setBufferSize(MQTT_MAX_MESSAGE_SIZE); } char * OXRS_MQTT::getClientId() { return _clientId; } void OXRS_MQTT::setClientId(const char * clientId) { strcpy(_clientId, clientId); } void OXRS_MQTT::setBroker(const char * broker, uint16_t port) { strcpy(_broker, broker); _port = port; } void OXRS_MQTT::setAuth(const char * username, const char * password) { if (username == NULL) { _username[0] = '\0'; _password[0] = '\0'; } else { strcpy(_username, username); strcpy(_password, password); } } void OXRS_MQTT::setTopicPrefix(const char * prefix) { if (prefix == NULL) { _topicPrefix[0] = '\0'; } else { strcpy(_topicPrefix, prefix); } } void OXRS_MQTT::setTopicSuffix(const char * suffix) { if (suffix == NULL) { _topicSuffix[0] = '\0'; } else { strcpy(_topicSuffix, suffix); } } char * OXRS_MQTT::getWildcardTopic(char topic[]) { return _getTopic(topic, "+"); } char * OXRS_MQTT::getLwtTopic(char topic[]) { sprintf_P(topic, PSTR("%s/%s"), getStatusTopic(topic), "lwt"); return topic; } char * OXRS_MQTT::getAdoptTopic(char topic[]) { sprintf_P(topic, PSTR("%s/%s"), getStatusTopic(topic), "adopt"); return topic; } char * OXRS_MQTT::getLogTopic(char topic[]) { sprintf_P(topic, PSTR("%s/%s"), getStatusTopic(topic), "log"); return topic; } char * OXRS_MQTT::getConfigTopic(char topic[]) { return _getTopic(topic, MQTT_CONFIG_TOPIC); } char * OXRS_MQTT::getCommandTopic(char topic[]) { return _getTopic(topic, MQTT_COMMAND_TOPIC); } char * OXRS_MQTT::getStatusTopic(char topic[]) { return _getTopic(topic, MQTT_STATUS_TOPIC); } char * OXRS_MQTT::getTelemetryTopic(char topic[]) { return _getTopic(topic, MQTT_TELEMETRY_TOPIC); } void OXRS_MQTT::onConnected(connectedCallback callback) { _onConnected = callback; } void OXRS_MQTT::onDisconnected(disconnectedCallback callback) { _onDisconnected = callback; } void OXRS_MQTT::onConfig(jsonCallback callback) { _onConfig = callback; } void OXRS_MQTT::onCommand(jsonCallback callback) { _onCommand = callback; } void OXRS_MQTT::setConfig(JsonVariant json) { if (_onConfig) { _onConfig(json); } } void OXRS_MQTT::setCommand(JsonVariant json) { if (_onCommand) { _onCommand(json); } } void OXRS_MQTT::loop(void) { // Let the MQTT client handle any messages if (_client->loop()) { // Currently connected so ensure we are ready to reconnect if it drops _backoff = 0; _lastReconnectMs = millis(); } else { // Calculate the backoff interval and check if we need to try again uint32_t backoffMs = (uint32_t)_backoff * MQTT_BACKOFF_SECS * 1000; if ((millis() - _lastReconnectMs) > backoffMs) { // Attempt to connect if (!_connect()) { // Reconnection failed, so backoff if (_backoff < MQTT_MAX_BACKOFF_COUNT) { _backoff++; } _lastReconnectMs = millis(); } } } } int OXRS_MQTT::receive(char * topic, byte * payload, unsigned int length) { // Ignore if an empty message if (length == 0) { return MQTT_RECEIVE_ZERO_LENGTH; } // Tokenise the topic (skipping any prefix) to get the root topic type char * topicType; topicType = strtok(&topic[strlen(_topicPrefix)], "/"); DynamicJsonDocument json(MQTT_MAX_MESSAGE_SIZE); DeserializationError error = deserializeJson(json, payload); if (error) { return MQTT_RECEIVE_JSON_ERROR; } // Forward to the appropriate callback if (strncmp(topicType, MQTT_CONFIG_TOPIC, strlen(MQTT_CONFIG_TOPIC)) == 0) { if (!_onConfig) { return MQTT_RECEIVE_NO_CONFIG_HANDLER; } _onConfig(json.as<JsonVariant>()); } else if (strncmp(topicType, MQTT_COMMAND_TOPIC, strlen(MQTT_COMMAND_TOPIC)) == 0) { if (!_onCommand) { return MQTT_RECEIVE_NO_COMMAND_HANDLER; } _onCommand(json.as<JsonVariant>()); } return MQTT_RECEIVE_OK; } boolean OXRS_MQTT::connected(void) { return _client->connected(); } void OXRS_MQTT::reconnect(void) { // Disconnect from MQTT broker _client->disconnect(); // Force a connect attempt immediately _backoff = 0; _lastReconnectMs = millis(); } boolean OXRS_MQTT::publishAdopt(JsonVariant json) { char topic[64]; return _publish(json, getAdoptTopic(topic), true); } boolean OXRS_MQTT::publishStatus(JsonVariant json) { char topic[64]; return _publish(json, getStatusTopic(topic), false); } boolean OXRS_MQTT::publishTelemetry(JsonVariant json) { char topic[64]; return _publish(json, getTelemetryTopic(topic), false); } boolean OXRS_MQTT::_connect(void) { // Set the broker address and port (in case they have changed) _client->setServer(_broker, _port); // Build our LWT payload const int capacity = JSON_OBJECT_SIZE(1); StaticJsonDocument<capacity> lwtJson; lwtJson["online"] = false; // Get our LWT offline payload as raw string char lwtBuffer[24]; serializeJson(lwtJson, lwtBuffer); // Attempt to connect to the MQTT broker char topic[64]; boolean success = _client->connect(_clientId, _username, _password, getLwtTopic(topic), 0, true, lwtBuffer); if (success) { // Subscribe to our config and command topics _client->subscribe(getConfigTopic(topic)); _client->subscribe(getCommandTopic(topic)); // Publish our LWT online payload now we are ready lwtJson["online"] = true; _publish(lwtJson.as<JsonVariant>(), getLwtTopic(topic), true); // Fire the connected callback if (_onConnected) { _onConnected(); } } else { // Fire the disconnected callback if (_onDisconnected) { _onDisconnected(_client->state()); } } return success; } char * OXRS_MQTT::_getTopic(char topic[], const char * topicType) { if (strlen(_topicPrefix) == 0) { if (strlen(_topicSuffix) == 0) { sprintf_P(topic, PSTR("%s/%s"), topicType, _clientId); } else { sprintf_P(topic, PSTR("%s/%s/%s"), topicType, _clientId, _topicSuffix); } } else { if (strlen(_topicSuffix) == 0) { sprintf_P(topic, PSTR("%s/%s/%s"), _topicPrefix, topicType, _clientId); } else { sprintf_P(topic, PSTR("%s/%s/%s/%s"), _topicPrefix, topicType, _clientId, _topicSuffix); } } return topic; } boolean OXRS_MQTT::_publish(JsonVariant json, char * topic, boolean retained) { if (!_client->connected()) { return false; } #ifdef MQTT_ENABLE_STREAMING // Publish as a buffered stream _client->beginPublish(topic, measureJson(json), retained); BufferingPrint bufferedClient(*_client, MQTT_STREAMING_BUFFER_SIZE); serializeJson(json, bufferedClient); bufferedClient.flush(); _client->endPublish(); #else // Write to a temporary buffer and then publish char buffer[MQTT_MAX_MESSAGE_SIZE]; serializeJson(json, buffer); _client->publish(topic, buffer, retained); #endif return true; }
7,686
2,956
#include <iostream> #include <vector> #include <cmath> using namespace std; int calculate(vector<int> coefficients, int x) { int result = coefficients[0]; for(int i = 1; i < coefficients.size(); i++) { result = result * x + coefficients[i]; } return result; } int main() { //* x*x*x + 2*x - 10; vector<int> coefficients {1, 0, 2, -10}; cout << calculate(coefficients, 10); return 0; }
427
157
// // ortho view generation tool // ulrich.krispel@fraunhofer.at // #include <vector> #include <string> #include <algorithm> #include <cmath> #include <iomanip> #include <limits> #include <boost/program_options.hpp> #include "types.h" #include "projection.h" #include "meanshift.h" #include "extraction.h" #include "../lib/frozen/frozen.h" namespace po = boost::program_options; // configuration variables double WINDOW_SIZE_NORMAL = 0.3; double WINDOW_SIZE_DISTANCE = 0.1; int main(int ac, char* av[]) { SphericalPanoramaImageProjection projection; myIFS ingeometry; double resolution = 1.0; // default: 1 mm/pixel double scalefactor = 1.0; // m bool exportOBJ = false; bool exportSphere = false; bool exportQuadGeometry = false; std::cout << "OrthoGen orthographic image generator for DuraArk" << std::endl; std::cout << "developed by Fraunhofer Austria Research GmbH" << std::endl; std::string output = "ortho"; try { po::options_description desc("commandline options"); desc.add_options() ("help", "show this help message") ("im", po::value< std::string >(), "input panoramic image [.jpg]") ("ig", po::value< std::string >(), "input geometry [.OBJ]") ("res", po::value< double >(), "resolution [mm/pixel], default 1mm/pixel") ("trans", po::value< std::vector<double> >()->multitoken(), "transformation [x,y,z]") ("rot", po::value< std::vector<double> >()->multitoken(), "rotation quaternion [w,x,y,z]") ("elevation", po::value< std::vector<double> >()->multitoken(), "elevation angle bounds [min..max], default [-PI/2..PI/2]" ) ("azimuth", po::value< std::vector<double> >()->multitoken(), "azimuth angle bounds [min..max], default [0..2*PI]") ("exgeom", po::value< bool >(), "export (textured) geometry [OBJ] 0/1, default 0 (false)") ("exquad", po::value< bool >(), "export extracted quads as (textured) geometry [OBJ] 0/1, default 0 (false)") ("exsphere", po::value< bool >(), "export panoramic sphere [OBJ] 0/1, default 0 (false)") ("scale", po::value< std::string >(), "scale of input coordinates (mm/cm/m), default m") ("ncluster", po::value< double >(), "geometry element normal direction clustering window size, default 0.3") ("dcluster", po::value< double >(), "geometry element planar distance clustering window size in m, default 0.1") ("output", po::value< std::string >(), "output filename [.jpg] will be appended") ; po::variables_map vm; po::store(po::parse_command_line(ac, av, desc, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return 0; } if (vm.count("im")) { Image img; if (loadJPEG(vm["im"].as<std::string>().c_str(), img)) { projection.setPanoramicImage(img); } else { std::cout << "Error: could not open " << vm["im"].as<std::string>() << std::endl; } } if (vm.count("ig")) { // load geometry ingeometry = IFS::loadOBJ<myIFS>(vm["ig"].as<std::string>()); if (!ingeometry.isValid()) std::cout << "Error: could not open " << vm["ig"].as<std::string>() << std::endl; } if (vm.count("res")) { resolution = vm["res"].as<double>(); } if (vm.count("ncluster")) { WINDOW_SIZE_NORMAL = vm["ncluster"].as<double>(); } if (vm.count("dcluster")) { WINDOW_SIZE_DISTANCE = vm["dcluster"].as<double>(); } if (vm.count("trans")) { std::vector<double> trans = vm["trans"].as<std::vector<double> >(); projection.setPosition(Vec3d(trans[0], trans[1], trans[2])); } if (vm.count("rot")) { std::vector<double> rot = vm["rot"].as<std::vector<double> >(); if (rot.size() == 4) { Quaterniond quaternion(rot[0], rot[1], rot[2], rot[3]); std::cout << " applying quaternion [" << quaternion.x() << "," << quaternion.y() << "," << quaternion.z() << "," << quaternion.w() << "]" << std::endl; projection.applyRotation(quaternion); } else { std::cout << " --rot Error: quaternion is not composed of 4 values." << std::endl; } } if (vm.count("elevation")) { std::vector<double> el = vm["elevation"].as<std::vector<double> >(); projection.elevationRange[0] = el[0]; projection.elevationRange[1] = el[1]; } if (vm.count("azimuth")) { std::vector<double> az = vm["azimuth"].as<std::vector<double> >(); projection.azimuthRange[0] = az[0]; projection.azimuthRange[1] = az[1]; } if (vm.count("exgeom")) { exportOBJ = vm["exgeom"].as<bool>(); } if (vm.count("exquad")) { exportQuadGeometry = vm["exgeom"].as<bool>(); } if (vm.count("exsphere")) { exportSphere = vm["exsphere"].as<bool>(); } if (vm.count("scale")) { std::string s = vm["scale"].as<std::string>(); transform(s.begin(), s.end(), s.begin(), toupper); if (s.compare("MM") == 0) scalefactor = 1000.0; if (s.compare("CM") == 0) scalefactor = 100.0; if (s.compare("DM") == 0) scalefactor = 10.0; if (s.compare("M") == 0) scalefactor = 1.0; if (s.compare("KM") == 0) scalefactor = 0.001; } if (vm.count("output")) { output = vm["output"].as<std::string>(); } } catch(std::exception& e) { std::cerr << "error: " << e.what() << "\n"; return 1; } if (projection.isValid() && ingeometry.isValid()) { const Image &img = projection.img(); std::cout << "input image is " << img.width() << " x " << img.height() << " pixels." << std::endl; std::cout << "input geometry consists of " << ingeometry.vertices.size() << " vertices and " << ingeometry.faces.size() << " faces." << std::endl; std::cout << "using a resolution of " << resolution << "mm/pixel" << std::endl; // set up resolution scale from mm to actual scale / pixel resolution = resolution * scalefactor / 1000; // PROCESS OUTPUT if (exportSphere) { double radius1m = 0.5 * scalefactor; std::cout << "- exporting projected panorama OBJ.." << std::endl; myIFS sphere = projection.exportTexturedSphere(radius1m, 100); sphere.materials.push_back(IFS::Material("sphere", "sphere.jpg")); sphere.facematerial.push_back(sphere.materials.size() - 1); IFS::exportOBJ(sphere, "sphere", "# OrthoGen panoramic sphere\n"); saveJPEG("sphere.jpg", projection.img()); // projection.exportPointCloud(radius1m, 1000); } // EXTRACT QUADS FROM GEOMETRY std::cout << "Using a meanshift size of " << WINDOW_SIZE_NORMAL << " for normal clustering." << std::endl; std::cout << "Using a meanshift size of " << WINDOW_SIZE_DISTANCE << " for plane distance clustering." << std::endl; std::vector<Quad3Dd> quads; std::vector<Triangle> triangles; extract_quads(ingeometry, scalefactor, triangles, quads, WINDOW_SIZE_DISTANCE, WINDOW_SIZE_NORMAL); myIFS outgeometry; // ifs with input geometry with texture coords outgeometry.useTextureCoordinates = true; std::cout << "Exporting " << quads.size() << " ortho views." << std::endl; { myIFS quadgeometry; // ifs with orthophoto quads quadgeometry.useTextureCoordinates = true; quadgeometry.texcoordinates.push_back(Vec2d(0, 1)); quadgeometry.texcoordinates.push_back(Vec2d(0, 0)); quadgeometry.texcoordinates.push_back(Vec2d(1, 0)); quadgeometry.texcoordinates.push_back(Vec2d(1, 1)); int qid = 0; for (auto const &q : quads) { // create orthophoto projection Image orthophoto = q.performProjection(projection, resolution); { std::ostringstream oss; if (quads.size() > 1) oss << output << "_" << qid << ".jpg"; else oss << output << ".jpg"; saveJPEG(oss.str().c_str(), orthophoto); std::cout << oss.str() << " : " << orthophoto.width() << "x" << orthophoto.height() << " n: " << q.pose.Z << std::endl; } std::ostringstream matname, texname; matname << "ortho" << qid; texname << "ortho_" << qid << ".jpg"; if (exportQuadGeometry) { // create quad geometry, quads always use the same texcoordinates myIFS::IFSINDICES face; myIFS::IFSINDICES facetc; face.push_back(quadgeometry.vertex2index(q.V[0])); facetc.push_back(0); face.push_back(quadgeometry.vertex2index(q.V[1])); facetc.push_back(1); face.push_back(quadgeometry.vertex2index(q.V[2])); facetc.push_back(2); face.push_back(quadgeometry.vertex2index(q.V[3])); facetc.push_back(3); quadgeometry.faces.push_back(face); quadgeometry.facetexc.push_back(facetc); quadgeometry.materials.push_back(IFS::Material(matname.str(), texname.str())); quadgeometry.facematerial.push_back(quadgeometry.materials.size() - 1); assert(quadgeometry.faces.size() == quadgeometry.facetexc.size() && quadgeometry.faces.size() == quadgeometry.facematerial.size()); } // create output triangles for this quad if (exportOBJ) { outgeometry.materials.push_back(IFS::Material(matname.str(), texname.str())); for (size_t i : q.tri_id) { myIFS::IFSINDICES face; myIFS::IFSINDICES facetc; const Triangle &T = triangles[i]; // add triangle vertices face.push_back(outgeometry.vertex2index(T.p)); facetc.push_back(outgeometry.texcoordinates.size()); outgeometry.texcoordinates.push_back(q.point2tex(T.p)); face.push_back(outgeometry.vertex2index(T.q)); facetc.push_back(outgeometry.texcoordinates.size()); outgeometry.texcoordinates.push_back(q.point2tex(T.q)); face.push_back(outgeometry.vertex2index(T.r)); facetc.push_back(outgeometry.texcoordinates.size()); outgeometry.texcoordinates.push_back(q.point2tex(T.r)); // add triangle outgeometry.faces.push_back(face); outgeometry.facetexc.push_back(facetc); outgeometry.facematerial.push_back(outgeometry.materials.size() - 1); assert(outgeometry.faces.size() == outgeometry.facetexc.size() && outgeometry.faces.size() == outgeometry.facematerial.size()); } } ++qid; } if (exportQuadGeometry) { IFS::exportOBJ(quadgeometry, "quadgeometry", "# OrthoGen textured quads\n"); } } if (exportOBJ) { IFS::exportOBJ(outgeometry, "outgeometry", "# OrthoGen textured model\n"); } return 0; } else { if (!projection.isValid()) { std::cout << "Error: invalid panoramic image " << std::endl; } if (!ingeometry.isValid()) { std::cout << "Error: invalid geometry " << std::endl; } } std::cout << "--help for options." << std::endl; }
12,873
3,942
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef ISOMODEL_LIGHTING_HPP #define ISOMODEL_LIGHTING_HPP namespace openstudio { namespace isomodel { class Lighting { public: double powerDensityOccupied() const {return _powerDensityOccupied;} double powerDensityUnoccupied() const {return _powerDensityUnoccupied;} double dimmingFraction() const {return _dimmingFraction;} double exteriorEnergy() const {return _exteriorEnergy;} void setPowerDensityOccupied(double value) {_powerDensityOccupied = value;} void setPowerDensityUnoccupied(double value) {_powerDensityUnoccupied = value;} void setDimmingFraction(double value) {_dimmingFraction = value;} void setExteriorEnergy(double value) {_exteriorEnergy = value;} private: double _powerDensityOccupied; double _powerDensityUnoccupied; double _dimmingFraction; double _exteriorEnergy; }; } // isomodel } // openstudio #endif // ISOMODEL_LIGHTING_HPP
1,885
588
#pragma once namespace BF { template<typename NumberType> struct QuadTreePosition { public: NumberType X; NumberType Y; QuadTreePosition() { X = 0; Y = 0; } QuadTreePosition(NumberType x, NumberType y) { X = x; Y = y; } }; }
261
129
class Solution { public: int reverse(int x) { long int tmp = 0; while (x != 0) { tmp = tmp * 10 + x % 10; x = x / 10; } return (tmp > INT_MAX || tmp < INT_MIN) ? 0 : tmp; } };
240
92
#include <thor-internal/arch/cpu.hpp> #include <thor-internal/arch/ints.hpp> #include <thor-internal/arch/gic.hpp> #include <thor-internal/debug.hpp> #include <thor-internal/thread.hpp> #include <assert.h> namespace thor { extern "C" void *thorExcVectors; void initializeIrqVectors() { asm volatile ("msr vbar_el1, %0" :: "r"(&thorExcVectors)); } extern "C" void enableIntsAndHaltForever(); void suspendSelf() { assert(!intsAreEnabled()); getCpuData()->currentDomain = static_cast<uint64_t>(Domain::idle); enableIntsAndHaltForever(); } extern frg::manual_box<GicDistributor> dist; void sendPingIpi(int id) { dist->sendIpi(getCpuData(id)->gicCpuInterface->interfaceNumber(), 0); } void sendShootdownIpi() { dist->sendIpiToOthers(1); } extern "C" void onPlatformInvalidException(FaultImageAccessor image) { thor::panicLogger() << "thor: an invalid exception has occured" << frg::endlog; } namespace { Word mmuAbortError(uint64_t esr) { Word errorCode = 0; auto ec = esr >> 26; auto iss = esr & ((1 << 25) - 1); // Originated from EL0 if (ec == 0x20 || ec == 0x24) errorCode |= kPfUser; // Is an instruction abort if (ec == 0x20 || ec == 0x21) { errorCode |= kPfInstruction; } else { if (iss & (1 << 6)) errorCode |= kPfWrite; } auto sc = iss & 0x3F; if (sc < 16) { auto type = (sc >> 2) & 0b11; if (type == 0) // Address size fault errorCode |= kPfBadTable; if (type != 1) // Not a translation fault errorCode |= kPfAccess; } return errorCode; } bool updatePageAccess(FaultImageAccessor image, Word error) { if ((error & kPfWrite) && (error & kPfAccess) && !inHigherHalf(*image.faultAddr())) { // Check if it's just a writable page that's not dirty yet smarter::borrowed_ptr<Thread> this_thread = getCurrentThread(); return this_thread->getAddressSpace()->updatePageAccess(*image.faultAddr() & ~(kPageSize - 1)); } return false; } } // namespace anonymous void handlePageFault(FaultImageAccessor image, uintptr_t address, Word errorCode); void handleOtherFault(FaultImageAccessor image, Interrupt fault); void handleSyscall(SyscallImageAccessor image); constexpr bool logUpdatePageAccess = false; extern "C" void onPlatformSyncFault(FaultImageAccessor image) { auto ec = *image.code() >> 26; enableInts(); switch (ec) { case 0x00: // Invalid case 0x18: // Trapped MSR, MRS, or System instruction handleOtherFault(image, kIntrIllegalInstruction); break; case 0x20: // Instruction abort, lower EL case 0x21: // Instruction abort, same EL case 0x24: // Data abort, lower EL case 0x25: { // Data abort, same EL auto error = mmuAbortError(*image.code()); if (updatePageAccess(image, error)) { if constexpr (logUpdatePageAccess) { infoLogger() << "thor: updated page " << (void *)(*image.faultAddr() & ~(kPageSize - 1)) << " status on access from " << (void *)*image.ip() << frg::endlog; } break; } handlePageFault(image, *image.faultAddr(), error); break; } case 0x15: // Trapped SVC in AArch64 handleSyscall(image); break; case 0x30: // Breakpoint, lower EL case 0x31: // Breakpoint, same EL handleOtherFault(image, kIntrBreakpoint); break; case 0x0E: // Illegal Execution fault case 0x22: // IP alignment fault case 0x26: // SP alignment fault handleOtherFault(image, kIntrGeneralFault); break; case 0x3C: // BRK instruction handleOtherFault(image, kIntrBreakpoint); break; default: panicLogger() << "Unexpected fault " << ec << " from ip: " << (void *)*image.ip() << "\n" << "sp: " << (void *)*image.sp() << " " << "syndrome: 0x" << frg::hex_fmt(*image.code()) << " " << "saved state: 0x" << frg::hex_fmt(*image.rflags()) << frg::endlog; } disableInts(); } extern "C" void onPlatformAsyncFault(FaultImageAccessor image) { urgentLogger() << "thor: On CPU " << getCpuData()->cpuIndex << frg::endlog; urgentLogger() << "thor: An asynchronous fault has occured!" << frg::endlog; auto code = *image.code(); auto ec = code >> 26; bool recoverable = false; if (ec == 0x2F) { bool ids = code & (1 << 24); bool iesb = code & (1 << 13); uint8_t aet = (code >> 10) & 7; bool ea = code & (1 << 9); uint8_t dfsc = code & 0x3F; constexpr const char *aet_str[] = { "Uncontainable", "Unrecoverable state", "Restartable state", "Recoverable state", "Reserved", "Reserved", "Corrected", "Reserved" }; if (ids) { urgentLogger() << "thor: SError with implementation defined information: ESR = 0x" << frg::hex_fmt{code} << frg::endlog; } else { auto log = urgentLogger(); log << "thor: "; if (dfsc == 0x11) log << aet_str[aet] << " "; log << "SError "; log << " (EA = " << (ea ? "true" : "false") << ", IESB = " << (iesb ? "true" : "false") << ")"; if (dfsc != 0x11) log << " with DFSC = " << dfsc; log << frg::endlog; if (aet == 2 || aet == 12) recoverable = true; } } else { urgentLogger() << "thor: unexpectec EC " << ec << " (ESR = 0x" << frg::hex_fmt{code} << ")" << frg::endlog; } urgentLogger() << "thor: IP = 0x" << frg::hex_fmt{*image.ip()} << ", SP = 0x" << frg::hex_fmt{*image.sp()} << frg::endlog; if (!recoverable) panicLogger() << "thor: Panic due to unrecoverable error" << frg::endlog; } void handleIrq(IrqImageAccessor image, int number); void handlePreemption(IrqImageAccessor image); static constexpr bool logSGIs = false; static constexpr bool logSpurious = false; extern "C" void onPlatformIrq(IrqImageAccessor image) { auto &cpuInterface = getCpuData()->gicCpuInterface; auto [cpu, irq] = cpuInterface->get(); asm volatile ("isb" ::: "memory"); if (irq < 16) { if constexpr (logSGIs) infoLogger() << "thor: onPlatformIrq: on CPU " << getCpuData()->cpuIndex << ", got a SGI (no. " << irq << ") that originated from CPU " << cpu << frg::endlog; cpuInterface->eoi(cpu, irq); if (irq == 0) { handlePreemption(image); } else { assert(irq == 1); assert(!irqMutex().nesting()); disableUserAccess(); for(int i = 0; i < maxAsid; i++) getCpuData()->asidBindings[i].shootdown(); getCpuData()->globalBinding.shootdown(); } } else if (irq >= 1020) { if constexpr (logSpurious) infoLogger() << "thor: on CPU " << getCpuData()->cpuIndex << ", spurious IRQ " << irq << " occured" << frg::endlog; // no need to EOI spurious irqs } else { handleIrq(image, irq); } } extern "C" void onPlatformWork() { assert(!irqMutex().nesting()); // TODO: User-access should already be disabled here. disableUserAccess(); enableInts(); getCurrentThread()->mainWorkQueue()->run(); disableInts(); } } // namespace thor
6,712
2,854
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/compositor/reflector_impl.h" #include "base/bind.h" #include "base/location.h" #include "content/browser/compositor/browser_compositor_output_surface.h" #include "content/browser/compositor/owned_mailbox.h" #include "content/common/gpu/client/gl_helper.h" #include "ui/compositor/layer.h" namespace content { ReflectorImpl::ReflectorImpl( ui::Compositor* mirrored_compositor, ui::Layer* mirroring_layer, IDMap<BrowserCompositorOutputSurface>* output_surface_map, base::MessageLoopProxy* compositor_thread_loop, int surface_id) : impl_unsafe_(output_surface_map), main_unsafe_(mirrored_compositor, mirroring_layer), impl_message_loop_(compositor_thread_loop), main_message_loop_(base::MessageLoopProxy::current()), surface_id_(surface_id) { GLHelper* helper = ImageTransportFactory::GetInstance()->GetGLHelper(); MainThreadData& main = GetMain(); main.mailbox = new OwnedMailbox(helper); impl_message_loop_->PostTask( FROM_HERE, base::Bind( &ReflectorImpl::InitOnImplThread, this, main.mailbox->holder())); } ReflectorImpl::MainThreadData::MainThreadData( ui::Compositor* mirrored_compositor, ui::Layer* mirroring_layer) : needs_set_mailbox(true), mirrored_compositor(mirrored_compositor), mirroring_layer(mirroring_layer) {} ReflectorImpl::MainThreadData::~MainThreadData() {} ReflectorImpl::ImplThreadData::ImplThreadData( IDMap<BrowserCompositorOutputSurface>* output_surface_map) : output_surface_map(output_surface_map), output_surface(NULL), texture_id(0) {} ReflectorImpl::ImplThreadData::~ImplThreadData() {} ReflectorImpl::ImplThreadData& ReflectorImpl::GetImpl() { DCHECK(impl_message_loop_->BelongsToCurrentThread()); return impl_unsafe_; } ReflectorImpl::MainThreadData& ReflectorImpl::GetMain() { DCHECK(main_message_loop_->BelongsToCurrentThread()); return main_unsafe_; } void ReflectorImpl::InitOnImplThread(const gpu::MailboxHolder& mailbox_holder) { ImplThreadData& impl = GetImpl(); // Ignore if the reflector was shutdown before // initialized, or it's already initialized. if (!impl.output_surface_map || impl.gl_helper.get()) return; impl.mailbox_holder = mailbox_holder; BrowserCompositorOutputSurface* source_surface = impl.output_surface_map->Lookup(surface_id_); // Skip if the source surface isn't ready yet. This will be // initialized when the source surface becomes ready. if (!source_surface) return; AttachToOutputSurfaceOnImplThread(impl.mailbox_holder, source_surface); } void ReflectorImpl::OnSourceSurfaceReady( BrowserCompositorOutputSurface* source_surface) { ImplThreadData& impl = GetImpl(); AttachToOutputSurfaceOnImplThread(impl.mailbox_holder, source_surface); } void ReflectorImpl::Shutdown() { MainThreadData& main = GetMain(); main.mailbox = NULL; main.mirroring_layer->SetShowPaintedContent(); main.mirroring_layer = NULL; impl_message_loop_->PostTask( FROM_HERE, base::Bind(&ReflectorImpl::ShutdownOnImplThread, this)); } void ReflectorImpl::DetachFromOutputSurface() { ImplThreadData& impl = GetImpl(); DCHECK(impl.output_surface); impl.output_surface->SetReflector(NULL); DCHECK(impl.texture_id); impl.gl_helper->DeleteTexture(impl.texture_id); impl.texture_id = 0; impl.gl_helper.reset(); impl.output_surface = NULL; } void ReflectorImpl::ShutdownOnImplThread() { ImplThreadData& impl = GetImpl(); if (impl.output_surface) DetachFromOutputSurface(); impl.output_surface_map = NULL; // The instance must be deleted on main thread. main_message_loop_->PostTask(FROM_HERE, base::Bind(&ReflectorImpl::DeleteOnMainThread, scoped_refptr<ReflectorImpl>(this))); } void ReflectorImpl::ReattachToOutputSurfaceFromMainThread( BrowserCompositorOutputSurface* output_surface) { MainThreadData& main = GetMain(); GLHelper* helper = ImageTransportFactory::GetInstance()->GetGLHelper(); main.mailbox = new OwnedMailbox(helper); main.needs_set_mailbox = true; main.mirroring_layer->SetShowPaintedContent(); impl_message_loop_->PostTask( FROM_HERE, base::Bind(&ReflectorImpl::AttachToOutputSurfaceOnImplThread, this, main.mailbox->holder(), output_surface)); } void ReflectorImpl::OnMirroringCompositorResized() { MainThreadData& main = GetMain(); main.mirroring_layer->SchedulePaint(main.mirroring_layer->bounds()); } void ReflectorImpl::OnSwapBuffers() { ImplThreadData& impl = GetImpl(); gfx::Size size = impl.output_surface->SurfaceSize(); if (impl.texture_id) { impl.gl_helper->CopyTextureFullImage(impl.texture_id, size); impl.gl_helper->Flush(); } main_message_loop_->PostTask( FROM_HERE, base::Bind( &ReflectorImpl::FullRedrawOnMainThread, this->AsWeakPtr(), size)); } void ReflectorImpl::OnPostSubBuffer(gfx::Rect rect) { ImplThreadData& impl = GetImpl(); if (impl.texture_id) { impl.gl_helper->CopyTextureSubImage(impl.texture_id, rect); impl.gl_helper->Flush(); } main_message_loop_->PostTask( FROM_HERE, base::Bind(&ReflectorImpl::UpdateSubBufferOnMainThread, this->AsWeakPtr(), impl.output_surface->SurfaceSize(), rect)); } ReflectorImpl::~ReflectorImpl() { // Make sure the reflector is deleted on main thread. DCHECK_EQ(main_message_loop_.get(), base::MessageLoopProxy::current().get()); } static void ReleaseMailbox(scoped_refptr<OwnedMailbox> mailbox, unsigned int sync_point, bool is_lost) { mailbox->UpdateSyncPoint(sync_point); } void ReflectorImpl::AttachToOutputSurfaceOnImplThread( const gpu::MailboxHolder& mailbox_holder, BrowserCompositorOutputSurface* output_surface) { ImplThreadData& impl = GetImpl(); if (output_surface == impl.output_surface) return; if (impl.output_surface) DetachFromOutputSurface(); impl.output_surface = output_surface; output_surface->context_provider()->BindToCurrentThread(); impl.gl_helper.reset( new GLHelper(output_surface->context_provider()->ContextGL(), output_surface->context_provider()->ContextSupport())); impl.texture_id = impl.gl_helper->ConsumeMailboxToTexture( mailbox_holder.mailbox, mailbox_holder.sync_point); impl.gl_helper->ResizeTexture(impl.texture_id, output_surface->SurfaceSize()); impl.gl_helper->Flush(); output_surface->SetReflector(this); // The texture doesn't have the data, so invokes full redraw now. main_message_loop_->PostTask( FROM_HERE, base::Bind(&ReflectorImpl::FullRedrawContentOnMainThread, scoped_refptr<ReflectorImpl>(this))); } void ReflectorImpl::UpdateTextureSizeOnMainThread(gfx::Size size) { MainThreadData& main = GetMain(); if (!main.mirroring_layer || !main.mailbox.get() || main.mailbox->mailbox().IsZero()) return; if (main.needs_set_mailbox) { main.mirroring_layer->SetTextureMailbox( cc::TextureMailbox(main.mailbox->holder()), cc::SingleReleaseCallback::Create( base::Bind(ReleaseMailbox, main.mailbox)), size); main.needs_set_mailbox = false; } else { main.mirroring_layer->SetTextureSize(size); } main.mirroring_layer->SetBounds(gfx::Rect(size)); } void ReflectorImpl::FullRedrawOnMainThread(gfx::Size size) { MainThreadData& main = GetMain(); if (!main.mirroring_layer) return; UpdateTextureSizeOnMainThread(size); main.mirroring_layer->SchedulePaint(main.mirroring_layer->bounds()); } void ReflectorImpl::UpdateSubBufferOnMainThread(gfx::Size size, gfx::Rect rect) { MainThreadData& main = GetMain(); if (!main.mirroring_layer) return; UpdateTextureSizeOnMainThread(size); // Flip the coordinates to compositor's one. int y = size.height() - rect.y() - rect.height(); gfx::Rect new_rect(rect.x(), y, rect.width(), rect.height()); main.mirroring_layer->SchedulePaint(new_rect); } void ReflectorImpl::FullRedrawContentOnMainThread() { MainThreadData& main = GetMain(); main.mirrored_compositor->ScheduleFullRedraw(); } } // namespace content
8,515
2,790
#pragma once struct triangle: shape { float x0; float y0; float z0; float x1; float y1; float z1; float x2; float y2; float z2; float norm_x; float norm_y; float norm_z; triangle ( material_type material, float x0, float y0, float z0, float x1, float y1, float z1, float x2, float y2, float z2, float r, float g, float b ) { this->primitive = shape_type::st_triangle; this->x0 = x0; this->y0 = y0; this->z0 = z0; this->x1 = x1; this->y1 = y1; this->z1 = z1; this->x2 = x2; this->y2 = y2; this->z2 = z2; this->r = r; this->g = g; this->b = b; this->material = material; // Surface normal. float v1v0_x = x1 - x0; float v1v0_y = y1 - y0; float v1v0_z = z1 - z0; float v2v0_x = x2 - x0; float v2v0_y = y2 - y0; float v2v0_z = z2 - z0; float cross_x = v1v0_y * v2v0_z - v2v0_y * v1v0_z; float cross_y = v1v0_x * v2v0_z - v2v0_x * v1v0_z; float cross_z = v1v0_x * v2v0_y - v2v0_x * v1v0_y; float cross_len = sqrtf ( cross_x * cross_x + cross_y * cross_y + cross_z * cross_z ); norm_x = cross_x / cross_len; norm_y = cross_y / cross_len; norm_z = cross_z / cross_len; } }; inline triangle TO_TRIANGLE(shape* __victim) { return *((triangle*)__victim); } inline float triangle_intersect ( triangle triangle1, float ray_ox, float ray_oy, float ray_oz, float ray_dx, float ray_dy, float ray_dz, float* norm_x, float* norm_y, float* norm_z, float* texture_u, float* texture_v ) { #define v0_x (triangle1.x0) #define v0_y (triangle1.y0) #define v0_z (triangle1.z0) #define v1_x (triangle1.x1) #define v1_y (triangle1.y1) #define v1_z (triangle1.z1) #define v2_x (triangle1.x2) #define v2_y (triangle1.y2) #define v2_z (triangle1.z2) float v0v1_x = v1_x - v0_x; float v0v1_y = v1_y - v0_y; float v0v1_z = v1_z - v0_z; float v0v2_x = v2_x - v0_x; float v0v2_y = v2_y - v0_y; float v0v2_z = v2_z - v0_z; float pvec_x = ray_dy * v0v2_z - ray_dz * v0v2_y; float pvec_y = ray_dz * v0v2_x - ray_dx * v0v2_z; float pvec_z = ray_dx * v0v2_y - ray_dy * v0v2_x; float inv_det = 1.0f / ( v0v1_x * pvec_x + v0v1_y * pvec_y + v0v1_z * pvec_z ); float tvec_x = ray_ox - v0_x; float tvec_y = ray_oy - v0_y; float tvec_z = ray_oz - v0_z; float u = inv_det * ( tvec_x * pvec_x + tvec_y * pvec_y + tvec_z * pvec_z ); if (u < 0.0f || u > 1.0f) { return -1.0f; } float qvec_x = tvec_y * v0v1_z - tvec_z * v0v1_y; float qvec_y = tvec_z * v0v1_x - tvec_x * v0v1_z; float qvec_z = tvec_x * v0v1_y - tvec_y * v0v1_x; float v = inv_det * ( ray_dx * qvec_x + ray_dy * qvec_y + ray_dz * qvec_z ); if (v < 0.0f || u + v > 1.0f) { return -1.0f; } float t = inv_det * ( v0v2_x * qvec_x + v0v2_y * qvec_y + v0v2_z * qvec_z ); set_ptr(norm_x, triangle1.norm_x); set_ptr(norm_y, triangle1.norm_y); set_ptr(norm_z, triangle1.norm_z); set_ptr(texture_u, u); set_ptr(texture_v, v); return t; }
2,984
1,702
#include "docsearchcontroller.hpp" #include "codeeditor.hpp" DocSearchController::DocSearchController( UICodeEditorSplitter* editorSplitter, App* app ) : mEditorSplitter( editorSplitter ), mApp( app ) {} void DocSearchController::initSearchBar( UISearchBar* searchBar ) { mSearchBarLayout = searchBar; mSearchBarLayout->setVisible( false )->setEnabled( false ); auto addClickListener = [&]( UIWidget* widget, std::string cmd ) { widget->addEventListener( Event::MouseClick, [this, cmd]( const Event* event ) { const MouseEvent* mouseEvent = static_cast<const MouseEvent*>( event ); if ( mouseEvent->getFlags() & EE_BUTTON_LMASK ) mSearchBarLayout->execute( cmd ); } ); }; auto addReturnListener = [&]( UIWidget* widget, std::string cmd ) { widget->addEventListener( Event::OnPressEnter, [this, cmd]( const Event* ) { mSearchBarLayout->execute( cmd ); } ); }; UITextInput* findInput = mSearchBarLayout->find<UITextInput>( "search_find" ); UITextInput* replaceInput = mSearchBarLayout->find<UITextInput>( "search_replace" ); UICheckBox* caseSensitiveChk = mSearchBarLayout->find<UICheckBox>( "case_sensitive" ); UICheckBox* wholeWordChk = mSearchBarLayout->find<UICheckBox>( "whole_word" ); UICheckBox* luaPatternChk = mSearchBarLayout->find<UICheckBox>( "lua_pattern" ); caseSensitiveChk->addEventListener( Event::OnValueChange, [&, caseSensitiveChk]( const Event* ) { mSearchState.caseSensitive = caseSensitiveChk->isChecked(); } ); wholeWordChk->addEventListener( Event::OnValueChange, [&, wholeWordChk]( const Event* ) { mSearchState.wholeWord = wholeWordChk->isChecked(); } ); luaPatternChk->addEventListener( Event::OnValueChange, [&, luaPatternChk]( const Event* ) { mSearchState.type = luaPatternChk->isChecked() ? TextDocument::FindReplaceType::LuaPattern : TextDocument::FindReplaceType::Normal; } ); findInput->addEventListener( Event::OnTextChanged, [&, findInput]( const Event* ) { if ( mSearchState.editor && mEditorSplitter->editorExists( mSearchState.editor ) ) { mSearchState.text = findInput->getText(); mSearchState.editor->setHighlightWord( mSearchState.text ); if ( !mSearchState.text.empty() ) { mSearchState.editor->getDocument().setSelection( { 0, 0 } ); if ( !findNextText( mSearchState ) ) { findInput->addClass( "error" ); } else { findInput->removeClass( "error" ); } } else { findInput->removeClass( "error" ); mSearchState.editor->getDocument().setSelection( mSearchState.editor->getDocument().getSelection().start() ); } } } ); mSearchBarLayout->addCommand( "close-searchbar", [&] { hideSearchBar(); if ( mEditorSplitter->getCurEditor() ) mEditorSplitter->getCurEditor()->setFocus(); if ( mSearchState.editor ) { if ( mEditorSplitter->editorExists( mSearchState.editor ) ) { mSearchState.editor->setHighlightWord( "" ); mSearchState.editor->setHighlightTextRange( TextRange() ); } } } ); mSearchBarLayout->addCommand( "repeat-find", [this] { findNextText( mSearchState ); } ); mSearchBarLayout->addCommand( "replace-all", [this, replaceInput] { size_t count = replaceAll( mSearchState, replaceInput->getText() ); mApp->getNotificationCenter()->addNotification( String::format( "Replaced %zu occurrences.", count ) ); replaceInput->setFocus(); } ); mSearchBarLayout->addCommand( "find-and-replace", [this, replaceInput] { findAndReplace( mSearchState, replaceInput->getText() ); } ); mSearchBarLayout->addCommand( "find-prev", [this] { findPrevText( mSearchState ); } ); mSearchBarLayout->addCommand( "replace-selection", [this, replaceInput] { replaceSelection( mSearchState, replaceInput->getText() ); } ); mSearchBarLayout->addCommand( "change-case", [&, caseSensitiveChk] { caseSensitiveChk->setChecked( !caseSensitiveChk->isChecked() ); } ); mSearchBarLayout->addCommand( "change-whole-word", [&, wholeWordChk] { wholeWordChk->setChecked( !wholeWordChk->isChecked() ); } ); mSearchBarLayout->addCommand( "toggle-lua-pattern", [&, luaPatternChk] { luaPatternChk->setChecked( !luaPatternChk->isChecked() ); } ); mSearchBarLayout->getKeyBindings().addKeybindsString( { { "f3", "repeat-find" }, { "ctrl+g", "repeat-find" }, { "escape", "close-searchbar" }, { "ctrl+r", "replace-all" }, { "ctrl+s", "change-case" }, { "ctrl+w", "change-whole-word" }, { "ctrl+l", "toggle-lua-pattern" } } ); addReturnListener( findInput, "repeat-find" ); addReturnListener( replaceInput, "find-and-replace" ); addClickListener( mSearchBarLayout->find<UIPushButton>( "find_prev" ), "find-prev" ); addClickListener( mSearchBarLayout->find<UIPushButton>( "find_next" ), "repeat-find" ); addClickListener( mSearchBarLayout->find<UIPushButton>( "replace" ), "replace-selection" ); addClickListener( mSearchBarLayout->find<UIPushButton>( "replace_find" ), "find-and-replace" ); addClickListener( mSearchBarLayout->find<UIPushButton>( "replace_all" ), "replace-all" ); addClickListener( mSearchBarLayout->find<UIWidget>( "searchbar_close" ), "close-searchbar" ); replaceInput->addEventListener( Event::OnTabNavigate, [findInput]( const Event* ) { findInput->setFocus(); } ); } void DocSearchController::showFindView() { mApp->hideLocateBar(); mApp->hideGlobalSearchBar(); UICodeEditor* editor = mEditorSplitter->getCurEditor(); if ( !editor ) return; mSearchState.editor = editor; mSearchState.range = TextRange(); mSearchState.caseSensitive = mSearchBarLayout->find<UICheckBox>( "case_sensitive" )->isChecked(); mSearchState.wholeWord = mSearchBarLayout->find<UICheckBox>( "whole_word" )->isChecked(); mSearchBarLayout->setEnabled( true )->setVisible( true ); UITextInput* findInput = mSearchBarLayout->find<UITextInput>( "search_find" ); findInput->getDocument().selectAll(); findInput->setFocus(); const TextDocument& doc = editor->getDocument(); if ( doc.getSelection().hasSelection() && doc.getSelection().inSameLine() ) { String text = doc.getSelectedText(); if ( !text.empty() ) { findInput->setText( text ); findInput->getDocument().selectAll(); } else if ( !findInput->getText().empty() ) { findInput->getDocument().selectAll(); } } else if ( doc.getSelection().hasSelection() ) { mSearchState.range = doc.getSelection( true ); if ( !findInput->getText().empty() ) findInput->getDocument().selectAll(); } mSearchState.text = findInput->getText(); editor->setHighlightTextRange( mSearchState.range ); editor->setHighlightWord( mSearchState.text ); editor->getDocument().setActiveClient( editor ); } bool DocSearchController::findPrevText( SearchState& search ) { if ( search.text.empty() ) search.text = mLastSearch; if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) || search.text.empty() ) return false; search.editor->getDocument().setActiveClient( search.editor ); mLastSearch = search.text; TextDocument& doc = search.editor->getDocument(); TextRange range = doc.getDocRange(); TextPosition from = doc.getSelection( true ).start(); if ( search.range.isValid() ) { range = doc.sanitizeRange( search.range ).normalized(); from = from < range.start() ? range.start() : from; } TextPosition found = doc.findLast( search.text, from, search.caseSensitive, search.wholeWord, search.range ); if ( found.isValid() ) { doc.setSelection( { doc.positionOffset( found, search.text.size() ), found } ); return true; } else { found = doc.findLast( search.text, range.end() ); if ( found.isValid() ) { doc.setSelection( { doc.positionOffset( found, search.text.size() ), found } ); return true; } } return false; } bool DocSearchController::findNextText( SearchState& search ) { if ( search.text.empty() ) search.text = mLastSearch; if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) || search.text.empty() ) return false; search.editor->getDocument().setActiveClient( search.editor ); mLastSearch = search.text; TextDocument& doc = search.editor->getDocument(); TextRange range = doc.getDocRange(); TextPosition from = doc.getSelection( true ).end(); if ( search.range.isValid() ) { range = doc.sanitizeRange( search.range ).normalized(); from = from < range.start() ? range.start() : from; } TextRange found = doc.find( search.text, from, search.caseSensitive, search.wholeWord, search.type, range ); if ( found.isValid() ) { doc.setSelection( found.reversed() ); return true; } else { found = doc.find( search.text, range.start(), search.caseSensitive, search.wholeWord, search.type, range ); if ( found.isValid() ) { doc.setSelection( found.reversed() ); return true; } } return false; } bool DocSearchController::replaceSelection( SearchState& search, const String& replacement ) { if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) || !search.editor->getDocument().hasSelection() ) return false; search.editor->getDocument().setActiveClient( search.editor ); search.editor->getDocument().replaceSelection( replacement ); return true; } int DocSearchController::replaceAll( SearchState& search, const String& replace ) { if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) ) return 0; if ( search.text.empty() ) search.text = mLastSearch; if ( search.text.empty() ) return 0; search.editor->getDocument().setActiveClient( search.editor ); mLastSearch = search.text; TextDocument& doc = search.editor->getDocument(); TextPosition startedPosition = doc.getSelection().start(); int count = doc.replaceAll( search.text, replace, search.caseSensitive, search.wholeWord, search.type, search.range ); doc.setSelection( startedPosition ); return count; } bool DocSearchController::findAndReplace( SearchState& search, const String& replace ) { if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) ) return false; if ( search.text.empty() ) search.text = mLastSearch; if ( search.text.empty() ) return false; search.editor->getDocument().setActiveClient( search.editor ); mLastSearch = search.text; TextDocument& doc = search.editor->getDocument(); if ( doc.hasSelection() && doc.getSelectedText() == search.text ) { return replaceSelection( search, replace ); } else { return findNextText( search ); } } void DocSearchController::hideSearchBar() { mSearchBarLayout->setEnabled( false )->setVisible( false ); } void DocSearchController::onCodeEditorFocusChange( UICodeEditor* editor ) { if ( mSearchState.editor && mSearchState.editor != editor ) { String word = mSearchState.editor->getHighlightWord(); mSearchState.editor->setHighlightWord( "" ); mSearchState.editor->setHighlightTextRange( TextRange() ); mSearchState.text = ""; mSearchState.range = TextRange(); if ( editor ) { mSearchState.editor = editor; mSearchState.editor->setHighlightWord( word ); mSearchState.range = TextRange(); } } } SearchState& DocSearchController::getSearchState() { return mSearchState; }
11,104
3,811
/* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "level_zero/core/source/cmdqueue/cmdqueue_hw.inl" #include "level_zero/core/source/cmdqueue/cmdqueue_hw_base.inl" #include "cmdqueue_extended.inl" namespace L0 { template struct CommandQueueHw<IGFX_GEN12LP_CORE>; static CommandQueuePopulateFactory<IGFX_ALDERLAKE_P, CommandQueueHw<IGFX_GEN12LP_CORE>> populateADLP; } // namespace L0
434
171
#include "WorldLogic.h" #include "WorldState.h" #include "GameState.h" #include "Events\ObjectDestroyedEvent.h" namespace Simulation { WorldLogic::WorldLogic() { } WorldLogic::~WorldLogic() { } void WorldLogic::Tick(WorldState* thisWorld, GameState* stateLastFrame, std::vector<EventBase*> eventsThisFrame) { for (auto it = eventsThisFrame.begin(); it < eventsThisFrame.end(); ++it) { EventBase* myEvent = *it; switch (myEvent->GetType()) { case eEventType::ObjectDestroyed: { thisWorld->_objects.erase(static_cast<ObjectDestroyedEvent*>(myEvent)->_id); } break; } } } }
625
264
/* * SpectRE - A Spectral Code for Reheating * Copyright (C) 2009-2010 Hal Finkel, Nathaniel Roth and Richard Easther * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED ``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 AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @file * @brief Computation of the gradient in Fourier space. */ #ifndef GRAD_COMPUTER_HPP #define GRAD_COMPUTER_HPP #include "field_size.hpp" #include "model_params.hpp" #include "field.hpp" template <typename R> class grad_computer { public: grad_computer(field_size &fs_, model_params<R> &mp_, field<R> &phi_, field<R> &chi_) : fs(fs_), upfs(fs_.n), mp(mp_), phi(phi_), chi(chi_), phigradx("phigradx"), chigradx("chigradx"), phigrady("phigrady"), chigrady("chigrady"), phigradz("phigradz"), chigradz("chigradz") { phigradx.construct(upfs); chigradx.construct(upfs); phigrady.construct(upfs); chigrady.construct(upfs); phigradz.construct(upfs); chigradz.construct(upfs); } public: void compute(field_state final_state = position); protected: field_size &fs, upfs; model_params<R> &mp; field<R> &phi, &chi; public: field<R> phigradx, chigradx; field<R> phigrady, chigrady; field<R> phigradz, chigradz; }; #endif // GRAD_COMPUTER_HPP
2,353
931
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/array.h> #include <Array.hpp> namespace opencl { template<typename T> Array<T> solve(const Array<T> &a, const Array<T> &b, const af_mat_prop options = AF_MAT_NONE); template<typename T> Array<T> solveLU(const Array<T> &a, const Array<int> &pivot, const Array<T> &b, const af_mat_prop options = AF_MAT_NONE); }
695
222
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/zx/guest.h> #include <zircon/syscalls.h> #include <lib/zx/vmar.h> namespace zx { zx_status_t guest::create(const resource& resource, uint32_t options, guest* guest, vmar* vmar) { // Assume |resource|, |guest| and |vmar| must refer to different containers, // due to strict aliasing. return zx_guest_create( resource.get(), options, guest->reset_and_get_address(), vmar->reset_and_get_address()); } } // namespace zx
654
224
//------------------------------------------------------------------------------------------------------------------------------ #pragma once //Engine Systems #include "Engine/Commons/EngineCommon.hpp" #include "Engine/Math/AABB2.hpp" #include "Engine/Math/AABB3.hpp" #include "Engine/Math/Capsule3D.hpp" #include "Engine/Math/Disc2D.hpp" #include "Engine/Renderer/CPUMesh.hpp" #include "Engine/Renderer/GPUMesh.hpp" #include "Engine/Renderer/Rgba.hpp" //------------------------------------------------------------------------------------------------------------------------------ class TextureView; //------------------------------------------------------------------------------------------------------------------------------ enum eDebugRenderObject { DEBUG_RENDER_POINT, DEBUG_RENDER_POINT3D, DEBUG_RENDER_LINE, DEBUG_RENDER_LINE3D, DEBUG_RENDER_QUAD, DEBUG_RENDER_WIRE_QUAD, DEBUG_RENDER_QUAD3D, DEBUG_RENDER_DISC, DEBUG_RENDER_RING, DEBUG_RENDER_SPHERE, DEBUG_RENDER_WIRE_SPHERE, //This has to be an icoSphere DEBUG_RENDER_BOX, DEBUG_RENDER_WIRE_BOX, DEBUG_RENDER_ARROW, DEBUG_RENDER_ARROW3D, DEBUG_RENDER_CAPSULE, DEBUG_RENDER_WIRE_CAPSULE, DEBUG_RENDER_BASIS, DEBUG_RENDER_TEXT, DEBUG_RENDER_TEXT3D, DEBUG_RENDER_LOG }; //------------------------------------------------------------------------------------------------------------------------------ class ObjectProperties { public: virtual ~ObjectProperties(); eDebugRenderObject m_renderObjectType; float m_durationSeconds = 0.0f; // show for a single frame float m_startDuration = 0.f; Rgba m_currentColor = Rgba::WHITE; CPUMesh* m_mesh; }; //------------------------------------------------------------------------------------------------------------------------------ // 2D Render Objects //------------------------------------------------------------------------------------------------------------------------------ // Point //------------------------------------------------------------------------------------------------------------------------------ class Point2DProperties : public ObjectProperties { public: explicit Point2DProperties(eDebugRenderObject renderObject, const Vec2& screenPosition, float durationSeconds = 0.f, float size = DEFAULT_POINT_SIZE); virtual ~Point2DProperties(); public: Vec2 m_screenPosition = Vec2::ZERO; float m_size = DEFAULT_POINT_SIZE; }; // Line //------------------------------------------------------------------------------------------------------------------------------ class Line2DProperties : public ObjectProperties { public: explicit Line2DProperties(eDebugRenderObject renderObject, const Vec2& startPos, const Vec2& endPos, float durationSeconds = 0.f, float lineWidth = DEFAULT_LINE_WIDTH); virtual ~Line2DProperties(); public: Vec2 m_startPos = Vec2::ZERO; Vec2 m_endPos = Vec2::ZERO; float m_lineWidth = DEFAULT_LINE_WIDTH; }; // Arrow //------------------------------------------------------------------------------------------------------------------------------ class Arrow2DProperties : public ObjectProperties { public: explicit Arrow2DProperties(eDebugRenderObject renderObject, const Vec2& start, const Vec2& end, float durationSeconds = 0.f, float lineWidth = DEFAULT_LINE_WIDTH); virtual ~Arrow2DProperties(); public: Vec2 m_startPos = Vec2::ZERO; Vec2 m_endPos = Vec2::ZERO; float m_lineWidth = DEFAULT_LINE_WIDTH; Vec2 m_lineEnd = Vec2::ZERO; Vec2 m_arrowTip = Vec2::ZERO; Vec2 m_lineNorm = Vec2::ZERO; }; // Quad //------------------------------------------------------------------------------------------------------------------------------ class Quad2DProperties : public ObjectProperties { public: explicit Quad2DProperties( eDebugRenderObject renderObject, const AABB2& quad, float durationSeconds = 0.f, float thickness = DEFAULT_WIRE_WIDTH_2D, TextureView* texture = nullptr ); virtual ~Quad2DProperties(); public: TextureView* m_texture = nullptr; float m_thickness = DEFAULT_WIRE_WIDTH_2D; //Only used when rendering as a wire box AABB2 m_quad; }; // Disc //------------------------------------------------------------------------------------------------------------------------------ class Disc2DProperties : public ObjectProperties { public: explicit Disc2DProperties( eDebugRenderObject renderObject, const Disc2D& disc, float thickness, float durationSeconds = 0.f); virtual ~Disc2DProperties(); public: Disc2D m_disc; float m_thickness; //Only used when rendering it as a ring }; //------------------------------------------------------------------------------------------------------------------------------ // 3D Render Objects //------------------------------------------------------------------------------------------------------------------------------ // Point //------------------------------------------------------------------------------------------------------------------------------ class Point3DProperties : public ObjectProperties { public: explicit Point3DProperties( eDebugRenderObject renderObject, const Vec3& position, float size = DEFAULT_POINT_SIZE_3D, float durationSeconds = 0.f, TextureView* texture = nullptr); virtual ~Point3DProperties(); public: Vec3 m_position = Vec3::ZERO; TextureView* m_texture = nullptr; float m_size = DEFAULT_POINT_SIZE_3D; AABB2 m_point; }; // Line //------------------------------------------------------------------------------------------------------------------------------ class Line3DProperties : public ObjectProperties { public: explicit Line3DProperties( eDebugRenderObject renderObject, const Vec3& startPos, const Vec3& endPos, float durationSeconds = 0.f, float lineWidth = DEFAULT_LINE_WIDTH); virtual ~Line3DProperties(); public: Vec3 m_startPos = Vec3::ZERO; Vec3 m_endPos = Vec3::ZERO; Vec3 m_center = Vec3::ZERO; float m_lineWidth = DEFAULT_LINE_WIDTH; AABB2 m_line; }; // Quad //------------------------------------------------------------------------------------------------------------------------------ class Quad3DProperties : public ObjectProperties { public: explicit Quad3DProperties( eDebugRenderObject renderObject, const AABB2& quad, const Vec3& position, float durationSeconds = 0.f, TextureView* texture = nullptr, bool billBoarded = true ); virtual ~Quad3DProperties(); public: Vec3 m_position = Vec3::ZERO; TextureView* m_texture = nullptr; bool m_billBoarded = true; AABB2 m_quad; }; // Sphere //------------------------------------------------------------------------------------------------------------------------------ class SphereProperties : public ObjectProperties { public: explicit SphereProperties( eDebugRenderObject renderObject, const Vec3& center, float radius, float durationSeconds = 0.f, TextureView* texture = nullptr); virtual ~SphereProperties(); public: Vec3 m_center = Vec3::ZERO; float m_radius = 0.f; TextureView* m_texture = nullptr; }; // Capsule //------------------------------------------------------------------------------------------------------------------------------ class CapsuleProperties : public ObjectProperties { public: explicit CapsuleProperties( eDebugRenderObject renderObject, const Capsule3D& capsule, const Vec3& position, float durationSeconds = 0.f, TextureView* texture = nullptr); virtual ~CapsuleProperties(); public: Vec3 m_position = Vec3::ZERO; TextureView* m_texture = nullptr; Capsule3D m_capsule; }; // Box //------------------------------------------------------------------------------------------------------------------------------ class BoxProperties : public ObjectProperties { public: explicit BoxProperties( eDebugRenderObject renderObject, const AABB3& box, const Vec3& position, float durationSeconds = 0.f, TextureView* texture = nullptr); virtual ~BoxProperties(); public: Vec3 m_position = Vec3::ZERO; TextureView* m_texture = nullptr; AABB3 m_box; }; //------------------------------------------------------------------------------------------------------------------------------ // Text Render Objects //------------------------------------------------------------------------------------------------------------------------------ class TextProperties : public ObjectProperties { public: explicit TextProperties( eDebugRenderObject renderObject, const Vec3& position, const Vec2& pivot, const std::string& text, float fontHeight, float durationSeconds = 0.f, bool isBillboarded = true); explicit TextProperties( eDebugRenderObject renderObject, const Vec2& startPosition, const Vec2& endPosition, const std::string& text, float fontHeight, float durationSeconds = 0.f); virtual ~TextProperties(); public: //For 3D Vec3 m_position = Vec3::ZERO; Vec2 m_pivot = Vec2::ZERO; bool m_isBillboarded = true; //For 2D Vec2 m_startPosition = Vec2::ZERO; Vec2 m_endPosition = Vec2::ZERO; float m_fontHeight = DEFAULT_TEXT_HEIGHT_3D; std::string m_string; }; //------------------------------------------------------------------------------------------------------------------------------ // Text Log Entry //------------------------------------------------------------------------------------------------------------------------------ class LogProperties : public ObjectProperties { public: explicit LogProperties(eDebugRenderObject renderObject, const Rgba& printColor, const std::string& printString, float durationSeconds = 0.f); virtual ~LogProperties(); public: Rgba m_printColor = Rgba::WHITE; std::string m_string; };
9,769
2,927
// Copyright (C) 2014, 2010 by Mathieu Geisert, LAAS-CNRS. // // This file is part of the SceneViewer-corba. // // This software is provided "as is" without warranty of any kind, // either expressed or implied, including but not limited to the // implied warranties of fitness for a particular purpose. // // See the COPYING file for more information. #include <errno.h> #include <pthread.h> #include <iostream> #include <stdexcept> #include "server.hh" #include "server-private.hh" namespace gepetto { namespace viewer { namespace corba { using CORBA::Exception; using CORBA::Object_var; using CORBA::SystemException; using CORBA::ORB_init; using CORBA::PolicyList; using omniORB::fatalException; Server::Server(WindowsManagerPtr_t wm, int argc, const char *argv[], bool inMultiThread, bool useNameService) : windowsManager_ (wm) { private_ = new impl::Server; initORBandServers (argc, argv, inMultiThread, useNameService); } void Server::qparent (QObject* parent) { private_->qparent (parent); } Server::~Server() { private_->deactivateAndDestroyServers(); delete private_; private_ = NULL; } /// CORBA SERVER INITIALIZATION void Server::initORBandServers(int argc, const char* argv[], bool inMultiThread, bool useNameService) { Object_var obj; PortableServer::ThreadPolicy_var threadPolicy; PortableServer::POA_var rootPoa; /// ORB init private_->orb_ = ORB_init (argc, const_cast<char **> (argv)); if (is_nil(private_->orb_)) { std::string msg ("failed to initialize ORB"); throw std::runtime_error (msg.c_str ()); } /// ORB init if (useNameService) { obj = private_->orb_->resolve_initial_references("RootPOA"); /// Create thread policy // // Make the CORBA object single-threaded to avoid GUI krash // // Create a sigle threaded policy object rootPoa = PortableServer::POA::_narrow(obj); if (inMultiThread) { threadPolicy = rootPoa->create_thread_policy (PortableServer::ORB_CTRL_MODEL); } else { threadPolicy = rootPoa->create_thread_policy (PortableServer::MAIN_THREAD_MODEL); } /// Duplicate thread policy PolicyList policyList; policyList.length(1); policyList[0] = PortableServer::ThreadPolicy::_duplicate(threadPolicy); try { private_->poa_ = rootPoa->create_POA ("child", PortableServer::POAManager::_nil(), policyList); } catch (PortableServer::POA::AdapterAlreadyExists& /*e*/) { private_->poa_ = rootPoa->find_POA ("child", false); } // Destroy policy object threadPolicy->destroy(); } else { // TODO: There is no way to use omniINSPOA with a different policy. // A rather easy workaround can be found here: // http://www.omniorb-support.com/pipermail/omniorb-list/2006-January/027358.html obj = private_->orb_->resolve_initial_references("omniINSPOA"); private_->poa_ = PortableServer::POA::_narrow(obj); } private_->useNameService_ = useNameService; private_->createServant(this); if (useNameService) private_->initRootPOA(); else private_->initOmniINSPOA(); } void Server::startCorbaServer() { if (private_->useNameService_) { // Obtain a reference to objects, and register them in // the naming service. Object_var graphicalInterfaceObj = private_->graphicalInterfaceServant_->_this(); private_->createContext (); // Bind graphicalInterfaceObj with name graphicalinterface to the Context: CosNaming::Name objectName; objectName.length(1); objectName[0].id = (const char*) "corbaserver"; // string copied objectName[0].kind = (const char*) "gui"; // string copied private_->bindObjectToName(graphicalInterfaceObj, objectName); private_->graphicalInterfaceServant_->_remove_ref(); } PortableServer::POAManager_var pman = private_->poa_->the_POAManager(); pman->activate(); } int Server::processRequest (bool loop) { if (loop) { private_->orb_->run(); } else { if (private_->orb_->work_pending()) private_->orb_->perform_work(); } return 0; } void Server::shutdown (bool wait) { private_->orb_->shutdown(wait); } } // end of namespace corba. } // end of namespace viewer. } // end of namespace gepetto.
4,657
1,474
// Copyright (c) 2009-2021 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander #include "ConstraintSphereGPU.h" #include "ConstraintSphereGPU.cuh" namespace py = pybind11; using namespace std; /*! \file ConstraintSphereGPU.cc \brief Contains code for the ConstraintSphereGPU class */ /*! \param sysdef SystemDefinition containing the ParticleData to compute forces on \param group Group of particles on which to apply this constraint \param P position of the sphere \param r radius of the sphere */ ConstraintSphereGPU::ConstraintSphereGPU(std::shared_ptr<SystemDefinition> sysdef, std::shared_ptr<ParticleGroup> group, Scalar3 P, Scalar r) : ConstraintSphere(sysdef, group, P, r), m_block_size(256) { if (!m_exec_conf->isCUDAEnabled()) { m_exec_conf->msg->error() << "Creating a ConstraintSphereGPU with no GPU in the execution configuration" << endl; throw std::runtime_error("Error initializing ConstraintSphereGPU"); } } /*! Computes the specified constraint forces \param timestep Current timestep */ void ConstraintSphereGPU::computeForces(uint64_t timestep) { unsigned int group_size = m_group->getNumMembers(); if (group_size == 0) return; if (m_prof) m_prof->push(m_exec_conf, "ConstraintSphere"); assert(m_pdata); // access the particle data arrays const GlobalArray<Scalar4>& net_force = m_pdata->getNetForce(); ArrayHandle<Scalar4> d_net_force(net_force, access_location::device, access_mode::read); const GlobalArray<unsigned int>& group_members = m_group->getIndexArray(); ArrayHandle<unsigned int> d_group_members(group_members, access_location::device, access_mode::read); ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::read); ArrayHandle<Scalar4> d_force(m_force, access_location::device, access_mode::overwrite); ArrayHandle<Scalar> d_virial(m_virial, access_location::device, access_mode::overwrite); // run the kernel in parallel on all GPUs gpu_compute_constraint_sphere_forces(d_force.data, d_virial.data, m_virial.getPitch(), d_group_members.data, m_group->getNumMembers(), m_pdata->getN(), d_pos.data, d_vel.data, d_net_force.data, m_P, m_r, m_deltaT, m_block_size); if (m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); if (m_prof) m_prof->pop(m_exec_conf); } void export_ConstraintSphereGPU(py::module& m) { py::class_<ConstraintSphereGPU, ConstraintSphere, std::shared_ptr<ConstraintSphereGPU>>( m, "ConstraintSphereGPU") .def(py::init<std::shared_ptr<SystemDefinition>, std::shared_ptr<ParticleGroup>, Scalar3, Scalar>()); }
3,786
1,081
#include "catch.hpp" #include "common/types/timestamp.hpp" #include <vector> using namespace duckdb; using namespace std; static void VerifyTimestamp(date_t date, dtime_t time, int64_t epoch) { // create the timestamp from the string timestamp_t stamp = Timestamp::FromString(Date::ToString(date) + " " + Time::ToString(time)); // verify that we can get the date and time back REQUIRE(Timestamp::GetDate(stamp) == date); REQUIRE(Timestamp::GetTime(stamp) == time); // verify that the individual extract functions work int32_t hour, min, sec, msec; Time::Convert(time, hour, min, sec, msec); REQUIRE(Timestamp::GetHours(stamp) == hour); REQUIRE(Timestamp::GetMinutes(stamp) == min); REQUIRE(Timestamp::GetSeconds(stamp) == sec); // verify that the epoch is correct REQUIRE(epoch == (Date::Epoch(date) + time / 1000)); REQUIRE(Timestamp::GetEpoch(stamp) == epoch); } TEST_CASE("Verify that timestamp functions work", "[timestamp]") { VerifyTimestamp(Date::FromDate(2019, 8, 26), Time::FromTime(8, 52, 6), 1566809526); VerifyTimestamp(Date::FromDate(1970, 1, 1), Time::FromTime(0, 0, 0), 0); VerifyTimestamp(Date::FromDate(2000, 10, 10), Time::FromTime(10, 10, 10), 971172610); }
1,199
475
#include "position.h" #include <boost/format.hpp> namespace foolgo { namespace board { using boost::format; using std::string; const BoardLen Position::STRAIGHT_ORNTTIONS[4][2] = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } }; const BoardLen Position::OBLIQUE_ORNTTIONS[4][2] = { { 1, -1 }, { 1, 1 }, { -1, 1 }, { -1, -1 } }; string PositionToString(const Position &position) { return (boost::format("{%1%, %2%}") % static_cast<int>(position.x) % static_cast<int>(position.y)).str(); } std::ostream &operator<<(std::ostream &os, const Position &position) { return os << PositionToString(position); } Position AdjacentPosition(const Position & position, int i) { return Position(position.x + Position::STRAIGHT_ORNTTIONS[i][0], position.y + Position::STRAIGHT_ORNTTIONS[i][1]); } Position ObliquePosition(const Position &position, int i) { return Position(position.x + Position::OBLIQUE_ORNTTIONS[i][0], position.y + Position::OBLIQUE_ORNTTIONS[i][1]); } } }
1,024
369
// Copyright (c) 2019 Google LLC. // // 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 <sstream> #include <string> #include <tuple> #include "gmock/gmock.h" #include "test/test_fixture.h" #include "test/unit_spirv.h" #include "test/val/val_fixtures.h" namespace spvtools { namespace val { namespace { using ::testing::Combine; using ::testing::HasSubstr; using ::testing::Values; using ValidateFunctionCall = spvtest::ValidateBase<std::string>; std::string GenerateShader(const std::string& storage_class, const std::string& capabilities, const std::string& extensions) { std::string spirv = R"( OpCapability Shader OpCapability Linkage OpCapability AtomicStorage )" + capabilities + R"( OpExtension "SPV_KHR_storage_buffer_storage_class" )" + extensions + R"( OpMemoryModel Logical GLSL450 OpName %var "var" %void = OpTypeVoid %int = OpTypeInt 32 0 %ptr = OpTypePointer )" + storage_class + R"( %int %caller_ty = OpTypeFunction %void %callee_ty = OpTypeFunction %void %ptr )"; if (storage_class != "Function") { spirv += "%var = OpVariable %ptr " + storage_class; } spirv += R"( %caller = OpFunction %void None %caller_ty %1 = OpLabel )"; if (storage_class == "Function") { spirv += "%var = OpVariable %ptr Function"; } spirv += R"( %call = OpFunctionCall %void %callee %var OpReturn OpFunctionEnd %callee = OpFunction %void None %callee_ty %param = OpFunctionParameter %ptr %2 = OpLabel OpReturn OpFunctionEnd )"; return spirv; } std::string GenerateShaderParameter(const std::string& storage_class, const std::string& capabilities, const std::string& extensions) { std::string spirv = R"( OpCapability Shader OpCapability Linkage OpCapability AtomicStorage )" + capabilities + R"( OpExtension "SPV_KHR_storage_buffer_storage_class" )" + extensions + R"( OpMemoryModel Logical GLSL450 OpName %p "p" %void = OpTypeVoid %int = OpTypeInt 32 0 %ptr = OpTypePointer )" + storage_class + R"( %int %func_ty = OpTypeFunction %void %ptr %caller = OpFunction %void None %func_ty %p = OpFunctionParameter %ptr %1 = OpLabel %call = OpFunctionCall %void %callee %p OpReturn OpFunctionEnd %callee = OpFunction %void None %func_ty %param = OpFunctionParameter %ptr %2 = OpLabel OpReturn OpFunctionEnd )"; return spirv; } std::string GenerateShaderAccessChain(const std::string& storage_class, const std::string& capabilities, const std::string& extensions) { std::string spirv = R"( OpCapability Shader OpCapability Linkage OpCapability AtomicStorage )" + capabilities + R"( OpExtension "SPV_KHR_storage_buffer_storage_class" )" + extensions + R"( OpMemoryModel Logical GLSL450 OpName %var "var" OpName %gep "gep" %void = OpTypeVoid %int = OpTypeInt 32 0 %int2 = OpTypeVector %int 2 %int_0 = OpConstant %int 0 %ptr = OpTypePointer )" + storage_class + R"( %int2 %ptr2 = OpTypePointer )" + storage_class + R"( %int %caller_ty = OpTypeFunction %void %callee_ty = OpTypeFunction %void %ptr2 )"; if (storage_class != "Function") { spirv += "%var = OpVariable %ptr " + storage_class; } spirv += R"( %caller = OpFunction %void None %caller_ty %1 = OpLabel )"; if (storage_class == "Function") { spirv += "%var = OpVariable %ptr Function"; } spirv += R"( %gep = OpAccessChain %ptr2 %var %int_0 %call = OpFunctionCall %void %callee %gep OpReturn OpFunctionEnd %callee = OpFunction %void None %callee_ty %param = OpFunctionParameter %ptr2 %2 = OpLabel OpReturn OpFunctionEnd )"; return spirv; } TEST_P(ValidateFunctionCall, VariableNoVariablePointers) { const std::string storage_class = GetParam(); std::string spirv = GenerateShader(storage_class, "", ""); const std::vector<std::string> valid_storage_classes = { "UniformConstant", "Function", "Private", "Workgroup", "AtomicCounter"}; bool valid = std::find(valid_storage_classes.begin(), valid_storage_classes.end(), storage_class) != valid_storage_classes.end(); CompileSuccessfully(spirv); if (valid) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } else { EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); if (storage_class == "StorageBuffer") { EXPECT_THAT(getDiagnosticString(), HasSubstr("StorageBuffer pointer operand 1[%var] requires a " "variable pointers capability")); } else { EXPECT_THAT( getDiagnosticString(), HasSubstr("Invalid storage class for pointer operand 1[%var]")); } } } TEST_P(ValidateFunctionCall, VariableVariablePointersStorageClass) { const std::string storage_class = GetParam(); std::string spirv = GenerateShader( storage_class, "OpCapability VariablePointersStorageBuffer", "OpExtension \"SPV_KHR_variable_pointers\""); const std::vector<std::string> valid_storage_classes = { "UniformConstant", "Function", "Private", "Workgroup", "StorageBuffer", "AtomicCounter"}; bool valid = std::find(valid_storage_classes.begin(), valid_storage_classes.end(), storage_class) != valid_storage_classes.end(); CompileSuccessfully(spirv); if (valid) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } else { EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Invalid storage class for pointer operand 1[%var]")); } } TEST_P(ValidateFunctionCall, VariableVariablePointers) { const std::string storage_class = GetParam(); std::string spirv = GenerateShader(storage_class, "OpCapability VariablePointers", "OpExtension \"SPV_KHR_variable_pointers\""); const std::vector<std::string> valid_storage_classes = { "UniformConstant", "Function", "Private", "Workgroup", "StorageBuffer", "AtomicCounter"}; bool valid = std::find(valid_storage_classes.begin(), valid_storage_classes.end(), storage_class) != valid_storage_classes.end(); CompileSuccessfully(spirv); if (valid) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } else { EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Invalid storage class for pointer operand 1[%var]")); } } TEST_P(ValidateFunctionCall, ParameterNoVariablePointers) { const std::string storage_class = GetParam(); std::string spirv = GenerateShaderParameter(storage_class, "", ""); const std::vector<std::string> valid_storage_classes = { "UniformConstant", "Function", "Private", "Workgroup", "AtomicCounter"}; bool valid = std::find(valid_storage_classes.begin(), valid_storage_classes.end(), storage_class) != valid_storage_classes.end(); CompileSuccessfully(spirv); if (valid) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } else { EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); if (storage_class == "StorageBuffer") { EXPECT_THAT(getDiagnosticString(), HasSubstr("StorageBuffer pointer operand 1[%p] requires a " "variable pointers capability")); } else { EXPECT_THAT(getDiagnosticString(), HasSubstr("Invalid storage class for pointer operand 1[%p]")); } } } TEST_P(ValidateFunctionCall, ParameterVariablePointersStorageBuffer) { const std::string storage_class = GetParam(); std::string spirv = GenerateShaderParameter( storage_class, "OpCapability VariablePointersStorageBuffer", "OpExtension \"SPV_KHR_variable_pointers\""); const std::vector<std::string> valid_storage_classes = { "UniformConstant", "Function", "Private", "Workgroup", "StorageBuffer", "AtomicCounter"}; bool valid = std::find(valid_storage_classes.begin(), valid_storage_classes.end(), storage_class) != valid_storage_classes.end(); CompileSuccessfully(spirv); if (valid) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } else { EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Invalid storage class for pointer operand 1[%p]")); } } TEST_P(ValidateFunctionCall, ParameterVariablePointers) { const std::string storage_class = GetParam(); std::string spirv = GenerateShaderParameter(storage_class, "OpCapability VariablePointers", "OpExtension \"SPV_KHR_variable_pointers\""); const std::vector<std::string> valid_storage_classes = { "UniformConstant", "Function", "Private", "Workgroup", "StorageBuffer", "AtomicCounter"}; bool valid = std::find(valid_storage_classes.begin(), valid_storage_classes.end(), storage_class) != valid_storage_classes.end(); CompileSuccessfully(spirv); if (valid) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } else { EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Invalid storage class for pointer operand 1[%p]")); } } TEST_P(ValidateFunctionCall, NonMemoryObjectDeclarationNoVariablePointers) { const std::string storage_class = GetParam(); std::string spirv = GenerateShaderAccessChain(storage_class, "", ""); const std::vector<std::string> valid_storage_classes = { "UniformConstant", "Function", "Private", "Workgroup", "AtomicCounter"}; bool valid_sc = std::find(valid_storage_classes.begin(), valid_storage_classes.end(), storage_class) != valid_storage_classes.end(); CompileSuccessfully(spirv); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); if (valid_sc) { EXPECT_THAT( getDiagnosticString(), HasSubstr( "Pointer operand 2[%gep] must be a memory object declaration")); } else { if (storage_class == "StorageBuffer") { EXPECT_THAT(getDiagnosticString(), HasSubstr("StorageBuffer pointer operand 2[%gep] requires a " "variable pointers capability")); } else { EXPECT_THAT( getDiagnosticString(), HasSubstr("Invalid storage class for pointer operand 2[%gep]")); } } } TEST_P(ValidateFunctionCall, NonMemoryObjectDeclarationVariablePointersStorageBuffer) { const std::string storage_class = GetParam(); std::string spirv = GenerateShaderAccessChain( storage_class, "OpCapability VariablePointersStorageBuffer", "OpExtension \"SPV_KHR_variable_pointers\""); const std::vector<std::string> valid_storage_classes = { "UniformConstant", "Function", "Private", "Workgroup", "StorageBuffer", "AtomicCounter"}; bool valid_sc = std::find(valid_storage_classes.begin(), valid_storage_classes.end(), storage_class) != valid_storage_classes.end(); bool validate = storage_class == "StorageBuffer"; CompileSuccessfully(spirv); if (validate) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } else { EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); if (valid_sc) { EXPECT_THAT( getDiagnosticString(), HasSubstr( "Pointer operand 2[%gep] must be a memory object declaration")); } else { EXPECT_THAT( getDiagnosticString(), HasSubstr("Invalid storage class for pointer operand 2[%gep]")); } } } TEST_P(ValidateFunctionCall, NonMemoryObjectDeclarationVariablePointers) { const std::string storage_class = GetParam(); std::string spirv = GenerateShaderAccessChain(storage_class, "OpCapability VariablePointers", "OpExtension \"SPV_KHR_variable_pointers\""); const std::vector<std::string> valid_storage_classes = { "UniformConstant", "Function", "Private", "Workgroup", "StorageBuffer", "AtomicCounter"}; bool valid_sc = std::find(valid_storage_classes.begin(), valid_storage_classes.end(), storage_class) != valid_storage_classes.end(); bool validate = storage_class == "StorageBuffer" || storage_class == "Workgroup"; CompileSuccessfully(spirv); if (validate) { EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } else { EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); if (valid_sc) { EXPECT_THAT( getDiagnosticString(), HasSubstr( "Pointer operand 2[%gep] must be a memory object declaration")); } else { EXPECT_THAT( getDiagnosticString(), HasSubstr("Invalid storage class for pointer operand 2[%gep]")); } } } INSTANTIATE_TEST_SUITE_P(StorageClass, ValidateFunctionCall, Values("UniformConstant", "Input", "Uniform", "Output", "Workgroup", "Private", "Function", "PushConstant", "Image", "StorageBuffer", "AtomicCounter")); } // namespace } // namespace val } // namespace spvtools
13,823
4,329
/* * Copyright 2019 by Crisp 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. */ #ifndef CRISP_INTERPRETUSERDEFINEDAST_HPP #define CRISP_INTERPRETUSERDEFINEDAST_HPP #include "Common.hpp" #include "CrispFunction.hpp" namespace crisp { template <typename Environ, typename F, typename... Args> struct CallCrispFunction { using type = Interpret<Call<typename F::__name__, Args...>, Environ>; }; template <template <typename...> class F, typename Environ, typename... Args> struct Interpret<F<Args...>, Environ> { using FApply = F<Args...>; using FApplyInterp = typename ConditionalApply< When<Bool<is_base_of<CrispFunction, FApply>::value>, DeferApply<CallCrispFunction, Environ, FApply, Args...>>, Else<DeferConstruct<Id, FApply>>>::type; using env = Environ; using type = typename FApplyInterp::type; }; } // namespace crisp #endif // CRISP_INTERPRETUSERDEFINEDAST_HPP
1,455
479
/* * Copyright (c) 2019 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-04-28 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxscale/ccdefs.hh> #include <maxscale/protocol.hh> #include <maxscale/authenticator.hh> class BackendDCB; class ClientDCB; class DCB; class SERVICE; namespace maxscale { class BackendConnection; class ClientConnection; class ConfigParameters; class UserAccountManager; class ProtocolModule { public: using AuthenticatorList = std::vector<mxs::SAuthenticatorModule>; virtual ~ProtocolModule() = default; enum Capabilities { CAP_AUTHDATA = (1u << 0), // Protocol implements a user account manager CAP_BACKEND = (1u << 1), // Protocol supports backend communication CAP_AUTH_MODULES = (1u << 2), // Protocol uses authenticator modules and does not integrate one }; /** * Allocate new client protocol session * * @param session The session to which the connection belongs to * @param component The component to use for routeQuery * * @return New protocol session or null on error */ virtual std::unique_ptr<mxs::ClientConnection> create_client_protocol(MXS_SESSION* session, mxs::Component* component) = 0; /** * Allocate new backend protocol session * * @param session The session to which the connection belongs to * @param server Server where the connection is made * * @return New protocol session or null on error */ virtual std::unique_ptr<BackendConnection> create_backend_protocol(MXS_SESSION* session, SERVER* server, mxs::Component* component) { mxb_assert(!true); return nullptr; } /** * Get the default authenticator for the protocol. * * @return The default authenticator for the protocol or empty if the protocol * does not provide one */ virtual std::string auth_default() const = 0; /** * Get rejection message. The protocol should return an error indicating that access to MaxScale * has been temporarily suspended. * * @param host The host that is blocked * @return A buffer containing the error message */ virtual GWBUF* reject(const std::string& host) { return nullptr; } /** * Get protocol module name. * * @return Module name */ virtual std::string name() const = 0; /** * Print a list of authenticator users to json. This should only be implemented by protocols without * CAP_AUTHDATA. * * @return JSON user list */ virtual json_t* print_auth_users_json() { return nullptr; } /** * Create a user account manager. Will be only called for protocols with CAP_AUTHDATA. * * @return New user account manager. Will be shared between all listeners of the service. */ virtual std::unique_ptr<UserAccountManager> create_user_data_manager() { mxb_assert(!true); return nullptr; } virtual uint64_t capabilities() const { return 0; } /** * The protocol module should read the listener parameters for the list of authenticators and their * options and generate authenticator modules. This is only called if CAP_AUTH_MODULES is enabled. * * @param params Listener and authenticator settings * @return An array of authenticators. Empty on error. */ virtual AuthenticatorList create_authenticators(const ConfigParameters& params) { mxb_assert(!true); return {}; } }; /** * Client protocol connection interface. All protocols must implement this. */ class ClientConnection : public ProtocolConnection { public: virtual ~ClientConnection() = default; /** * Initialize a connection. * * @return True, if the connection could be initialized, false otherwise. */ virtual bool init_connection() = 0; /** * Finalize a connection. Called right before the DCB itself is closed. */ virtual void finish_connection() = 0; /** * Handle connection limits. Currently the return value is ignored. * * @param limit Maximum number of connections * @return 1 on success, 0 on error */ virtual int32_t connlimit(int limit) { return 0; } /** * Return current database. Only required by query classifier. * * @return Current database */ virtual std::string current_db() const { return ""; } virtual ClientDCB* dcb() = 0; virtual const ClientDCB* dcb() const = 0; virtual void wakeup() { // Should not be called for non-supported protocols. mxb_assert(!true); } /** * Called when the session starts to stop * * This can be used to do any preparatory work that needs to be done before the actual shutdown is * started. At this stage the session is still valid and routing works normally. * * The default implementation does nothing. */ virtual void kill() { } }; /** * Partial client protocol implementation. More fields and functions may be added later. */ class ClientConnectionBase : public ClientConnection { public: json_t* diagnostics() const override; void set_dcb(DCB* dcb) override; ClientDCB* dcb() override; const ClientDCB* dcb() const override; protected: ClientDCB* m_dcb {nullptr}; /**< Dcb used by this protocol connection */ }; /** * Backend protocol connection interface. Only protocols with backend support need to implement this. */ class BackendConnection : public mxs::ProtocolConnection { public: virtual ~BackendConnection() = default; /** * Initialize a connection. * * @return True, if the connection could be initialized, false otherwise. */ virtual bool init_connection() = 0; /** * Finalize a connection. Called right before the DCB itself is closed. */ virtual void finish_connection() = 0; /** * Reuse a connection. The connection was in the persistent pool * and will now be taken into use again. * * @param dcb The connection to be reused. * @param upstream The upstream component. * * @return True, if the connection can be reused, false otherwise. * If @c false is returned, the @c dcb should be closed. */ virtual bool reuse_connection(BackendDCB* dcb, mxs::Component* upstream) = 0; /** * Check if the connection has been fully established, used by connection pooling * * @return True if the connection is fully established and can be pooled */ virtual bool established() = 0; /** * Ping a backend connection * * The backend connection should perform an action that keeps the connection alive if it is currently * idle. The idleness of a connection is determined at the protocol level and any actions taken at the * protocol level should not propagate upwards. * * What this means in practice is that if a query is used to ping a backend, the result should be * discarded and the pinging should not interrupt ongoing queries. */ virtual void ping() = 0; /** * Check if the connection can be closed in a controlled manner * * @return True if the connection can be closed without interruping anything */ virtual bool can_close() const = 0; /** * How many seconds has the connection been idle * * @return Number of seconds the connection has been idle */ virtual int64_t seconds_idle() const = 0; virtual const BackendDCB* dcb() const = 0; virtual BackendDCB* dcb() = 0; }; class UserAccountCache; /** * An interface which a user account manager must implement. The instance is shared between all threads. */ class UserAccountManager { public: virtual ~UserAccountManager() = default; /** * Start the user account manager. Should be called after creation. */ virtual void start() = 0; /** * Stop the user account manager. Should be called before destruction. */ virtual void stop() = 0; /** * Notify the manager that its data should be updated. The updating may happen * in a separate thread. */ virtual void update_user_accounts() = 0; /** * Set the username and password the manager should use when accessing backends. * * @param user Username * @param pw Password, possibly encrypted */ virtual void set_credentials(const std::string& user, const std::string& pw) = 0; virtual void set_backends(const std::vector<SERVER*>& backends) = 0; virtual void set_union_over_backends(bool union_over_backends) = 0; virtual void set_strip_db_esc(bool strip_db_esc) = 0; /** * Which protocol this manager can be used with. Currently, it's assumed that the user data managers * do not have listener-specific settings. If multiple listeners with the same protocol name feed * the same service, only one manager is required. */ virtual std::string protocol_name() const = 0; /** * Create a thread-local account cache linked to this account manager. * * @return A new user account cache */ virtual std::unique_ptr<UserAccountCache> create_user_account_cache() = 0; /** * Set owning service. * * @param service */ virtual void set_service(SERVICE* service) = 0; /** * Print contents to a json array. * * @return Users as json */ virtual json_t* users_to_json() const = 0; }; class UserAccountCache { public: virtual ~UserAccountCache() = default; virtual void update_from_master() = 0; }; template<class ProtocolImplementation> class ProtocolApiGenerator { public: ProtocolApiGenerator() = delete; ProtocolApiGenerator(const ProtocolApiGenerator&) = delete; ProtocolApiGenerator& operator=(const ProtocolApiGenerator&) = delete; static mxs::ProtocolModule* create_protocol_module() { // If protocols require non-authentication-related settings, add passing them here. // The unsolved issue is how to separate listener, protocol and authenticator-settings from // each other. Currently this is mostly a non-issue as the only authenticator with a setting // is gssapi. return ProtocolImplementation::create(); } static MXS_PROTOCOL_API s_api; }; template<class ProtocolImplementation> MXS_PROTOCOL_API ProtocolApiGenerator<ProtocolImplementation>::s_api = { &ProtocolApiGenerator<ProtocolImplementation>::create_protocol_module, }; }
11,055
3,055
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 _itkRegularExpressionSeriesFileNames_cxx #define _itkRegularExpressionSeriesFileNames_cxx #include <vector> #include <string.h> #include <stdlib.h> #include <algorithm> #include "itksys/SystemTools.hxx" #include "itksys/Directory.hxx" #include "itksys/RegularExpression.hxx" #include "itkRegularExpressionSeriesFileNames.h" struct lt_pair_numeric_string_string { bool operator()(const std::pair< std::string, std::string > s1, const std::pair< std::string, std::string > s2) const { return atof( s1.second.c_str() ) < atof( s2.second.c_str() ); } }; struct lt_pair_alphabetic_string_string { bool operator()(const std::pair< std::string, std::string > s1, const std::pair< std::string, std::string > s2) const { return s1.second < s2.second; } }; namespace itk { const std::vector< std::string > & RegularExpressionSeriesFileNames ::GetFileNames() { // Validate the ivars if ( m_Directory == "" ) { itkExceptionMacro (<< "No directory defined!"); } itksys::RegularExpression reg; if ( !reg.compile( m_RegularExpression.c_str() ) ) { itkExceptionMacro(<< "Error compiling regular expression " << m_RegularExpression); } // Process all files in the directory itksys::Directory fileDir; if ( !fileDir.Load ( m_Directory.c_str() ) ) { itkExceptionMacro (<< "Directory " << m_Directory.c_str() << " cannot be read!"); } std::vector< std::pair< std::string, std::string > > sortedBySubMatch; // Scan directory for files. Each file is checked to see if it // matches the m_RegularExpression. for ( unsigned long i = 0; i < fileDir.GetNumberOfFiles(); i++ ) { // Only read files if ( itksys::SystemTools::FileIsDirectory( ( m_Directory + "/" + fileDir.GetFile(i) ).c_str() ) ) { continue; } if ( reg.find( fileDir.GetFile(i) ) ) { // Store the full filename and the selected sub expression match std::pair< std::string, std::string > fileNameMatch; fileNameMatch.first = m_Directory + "/" + fileDir.GetFile(i); fileNameMatch.second = reg.match(m_SubMatch); sortedBySubMatch.push_back(fileNameMatch); } } // Sort the files. The files are sorted by the sub match defined by // m_SubMatch. Sorting can be alpahbetic or numeric. if ( m_NumericSort ) { std::sort( sortedBySubMatch.begin(), sortedBySubMatch.end(), lt_pair_numeric_string_string() ); } else { std::sort( sortedBySubMatch.begin(), sortedBySubMatch.end(), lt_pair_alphabetic_string_string() ); } // Now, store the sorted names in a vector m_FileNames.clear(); std::vector< std::pair< std::string, std::string > >::iterator siter; for ( siter = sortedBySubMatch.begin(); siter != sortedBySubMatch.end(); siter++ ) { m_FileNames.push_back( ( *siter ).first ); } return m_FileNames; } void RegularExpressionSeriesFileNames ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Directory: " << m_Directory << std::endl; os << indent << "SubMatch: " << m_SubMatch << std::endl; os << indent << "NumericSort: " << m_NumericSort << std::endl; os << indent << "RegularExpression: " << m_RegularExpression << std::endl; for ( unsigned int i = 0; i < m_FileNames.size(); i++ ) { os << indent << "Filenames[" << i << "]: " << m_FileNames[i] << std::endl; } } } //namespace ITK #endif
4,325
1,391
๏ปฟ/** * @file sph_neumann_impl.hpp * * @brief sph_neumann ้–ขๆ•ฐใฎๅฎŸ่ฃ… * * @author myoukaku */ #ifndef BKSGE_FND_CMATH_DETAIL_SPH_NEUMANN_IMPL_HPP #define BKSGE_FND_CMATH_DETAIL_SPH_NEUMANN_IMPL_HPP #include <bksge/fnd/cmath/isnan.hpp> #include <bksge/fnd/cmath/detail/sph_bessel_jn.hpp> #include <bksge/fnd/type_traits/float_promote.hpp> #include <bksge/fnd/config.hpp> #include <cmath> #include <limits> namespace bksge { namespace detail { #if defined(__cpp_lib_math_special_functions) && (__cpp_lib_math_special_functions >= 201603) inline /*BKSGE_CONSTEXPR*/ double sph_neumann_unchecked(unsigned int n, double x) { return std::sph_neumann(n, x); } inline /*BKSGE_CONSTEXPR*/ float sph_neumann_unchecked(unsigned int n, float x) { return std::sph_neumannf(n, x); } inline /*BKSGE_CONSTEXPR*/ long double sph_neumann_unchecked(unsigned int n, long double x) { return std::sph_neumannl(n, x); } #else template <typename T> inline BKSGE_CXX14_CONSTEXPR T sph_neumann_unchecked_2(unsigned int n, T x) { T j_n, n_n, jp_n, np_n; bksge::detail::sph_bessel_jn(n, x, j_n, n_n, jp_n, np_n); return n_n; } template <typename T> inline BKSGE_CXX14_CONSTEXPR T sph_neumann_unchecked(unsigned int n, T x) { using value_type = bksge::float_promote_t<double, T>; return static_cast<T>(sph_neumann_unchecked_2(n, static_cast<value_type>(x))); } #endif template <typename T> inline BKSGE_CXX14_CONSTEXPR T sph_neumann_impl(unsigned int n, T x) { if (bksge::isnan(x)) { return std::numeric_limits<T>::quiet_NaN(); } if (x == T(0)) { return -std::numeric_limits<T>::infinity(); } return sph_neumann_unchecked(n, x); } } // namespace detail } // namespace bksge #endif // BKSGE_FND_CMATH_DETAIL_SPH_NEUMANN_IMPL_HPP
1,822
861
#include <library/cpp/blockcodecs/core/codecs.h> #include <library/cpp/blockcodecs/core/common.h> #include <library/cpp/blockcodecs/core/register.h> #define ZSTD_STATIC_LINKING_ONLY #include <contrib/libs/zstd/zstd.h> using namespace NBlockCodecs; namespace { struct TZStd08Codec: public TAddLengthCodec<TZStd08Codec> { inline TZStd08Codec(unsigned level) : Level(level) , MyName(AsStringBuf("zstd08_") + ToString(Level)) { } static inline size_t CheckError(size_t ret, const char* what) { if (ZSTD_isError(ret)) { ythrow yexception() << what << AsStringBuf(" zstd error: ") << ZSTD_getErrorName(ret); } return ret; } static inline size_t DoMaxCompressedLength(size_t l) noexcept { return ZSTD_compressBound(l); } inline size_t DoCompress(const TData& in, void* out) const { return CheckError(ZSTD_compress(out, DoMaxCompressedLength(in.size()), in.data(), in.size(), Level), "compress"); } inline void DoDecompress(const TData& in, void* out, size_t dsize) const { const size_t res = CheckError(ZSTD_decompress(out, dsize, in.data(), in.size()), "decompress"); if (res != dsize) { ythrow TDecompressError(dsize, res); } } TStringBuf Name() const noexcept override { return MyName; } const unsigned Level; const TString MyName; }; struct TZStd08Registrar { TZStd08Registrar() { for (int i = 1; i <= ZSTD_maxCLevel(); ++i) { RegisterCodec(MakeHolder<TZStd08Codec>(i)); RegisterAlias("zstd_" + ToString(i), "zstd08_" + ToString(i)); } } }; static const TZStd08Registrar Registrar{}; }
1,871
629
#include "hole.h" #include "term.h" #include <iostream> Hole::Hole() { } Hole::Hole(int _x, int _y) { this->_x = _x; this->_y = _y; _present = true; } void Hole::handleEvent(Event *e) { } void Hole::display() { std::cout << cursorPosition(_x, _y) << '^'; } void Hole::present(bool _present) { this->_present = _present; } bool Hole::present() { return _present; } void Hole::x(int _x) { this->_x = _x; } void Hole::y(int _y) { this->_y = _y; } int Hole::x() { return _x; } int Hole::y() { return _y; }
523
257
#include "sqliter/sqliter.h" #include <iostream> #include <string> using namespace sqliter::asio; int main(int argc, char *argv[]) { boost::asio::io_service io; sqlite db(io); if (argc != 2) { std::cout << argv[0] << " <sqlite db file>" << std::endl; return -1; } db.open(argv[1]); boost::system::error_code ec; db.query("SELECT * from app", ec); std::cout << "Result: " << ec.message() << std::endl; io.run(); db.close(ec); return 0; }
495
200
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/mdc/v20200828/model/CreateInput.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Mdc::V20200828::Model; using namespace std; CreateInput::CreateInput() : m_inputNameHasBeenSet(false), m_protocolHasBeenSet(false), m_descriptionHasBeenSet(false), m_allowIpListHasBeenSet(false), m_sRTSettingsHasBeenSet(false), m_rTPSettingsHasBeenSet(false), m_failOverHasBeenSet(false) { } CoreInternalOutcome CreateInput::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("InputName") && !value["InputName"].IsNull()) { if (!value["InputName"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateInput.InputName` IsString=false incorrectly").SetRequestId(requestId)); } m_inputName = string(value["InputName"].GetString()); m_inputNameHasBeenSet = true; } if (value.HasMember("Protocol") && !value["Protocol"].IsNull()) { if (!value["Protocol"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateInput.Protocol` IsString=false incorrectly").SetRequestId(requestId)); } m_protocol = string(value["Protocol"].GetString()); m_protocolHasBeenSet = true; } if (value.HasMember("Description") && !value["Description"].IsNull()) { if (!value["Description"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateInput.Description` IsString=false incorrectly").SetRequestId(requestId)); } m_description = string(value["Description"].GetString()); m_descriptionHasBeenSet = true; } if (value.HasMember("AllowIpList") && !value["AllowIpList"].IsNull()) { if (!value["AllowIpList"].IsArray()) return CoreInternalOutcome(Core::Error("response `CreateInput.AllowIpList` is not array type")); const rapidjson::Value &tmpValue = value["AllowIpList"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_allowIpList.push_back((*itr).GetString()); } m_allowIpListHasBeenSet = true; } if (value.HasMember("SRTSettings") && !value["SRTSettings"].IsNull()) { if (!value["SRTSettings"].IsObject()) { return CoreInternalOutcome(Core::Error("response `CreateInput.SRTSettings` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_sRTSettings.Deserialize(value["SRTSettings"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_sRTSettingsHasBeenSet = true; } if (value.HasMember("RTPSettings") && !value["RTPSettings"].IsNull()) { if (!value["RTPSettings"].IsObject()) { return CoreInternalOutcome(Core::Error("response `CreateInput.RTPSettings` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_rTPSettings.Deserialize(value["RTPSettings"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_rTPSettingsHasBeenSet = true; } if (value.HasMember("FailOver") && !value["FailOver"].IsNull()) { if (!value["FailOver"].IsString()) { return CoreInternalOutcome(Core::Error("response `CreateInput.FailOver` IsString=false incorrectly").SetRequestId(requestId)); } m_failOver = string(value["FailOver"].GetString()); m_failOverHasBeenSet = true; } return CoreInternalOutcome(true); } void CreateInput::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_inputNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InputName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_inputName.c_str(), allocator).Move(), allocator); } if (m_protocolHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Protocol"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_protocol.c_str(), allocator).Move(), allocator); } if (m_descriptionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Description"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_description.c_str(), allocator).Move(), allocator); } if (m_allowIpListHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AllowIpList"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_allowIpList.begin(); itr != m_allowIpList.end(); ++itr) { value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_sRTSettingsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SRTSettings"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_sRTSettings.ToJsonObject(value[key.c_str()], allocator); } if (m_rTPSettingsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RTPSettings"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_rTPSettings.ToJsonObject(value[key.c_str()], allocator); } if (m_failOverHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "FailOver"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_failOver.c_str(), allocator).Move(), allocator); } } string CreateInput::GetInputName() const { return m_inputName; } void CreateInput::SetInputName(const string& _inputName) { m_inputName = _inputName; m_inputNameHasBeenSet = true; } bool CreateInput::InputNameHasBeenSet() const { return m_inputNameHasBeenSet; } string CreateInput::GetProtocol() const { return m_protocol; } void CreateInput::SetProtocol(const string& _protocol) { m_protocol = _protocol; m_protocolHasBeenSet = true; } bool CreateInput::ProtocolHasBeenSet() const { return m_protocolHasBeenSet; } string CreateInput::GetDescription() const { return m_description; } void CreateInput::SetDescription(const string& _description) { m_description = _description; m_descriptionHasBeenSet = true; } bool CreateInput::DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; } vector<string> CreateInput::GetAllowIpList() const { return m_allowIpList; } void CreateInput::SetAllowIpList(const vector<string>& _allowIpList) { m_allowIpList = _allowIpList; m_allowIpListHasBeenSet = true; } bool CreateInput::AllowIpListHasBeenSet() const { return m_allowIpListHasBeenSet; } CreateInputSRTSettings CreateInput::GetSRTSettings() const { return m_sRTSettings; } void CreateInput::SetSRTSettings(const CreateInputSRTSettings& _sRTSettings) { m_sRTSettings = _sRTSettings; m_sRTSettingsHasBeenSet = true; } bool CreateInput::SRTSettingsHasBeenSet() const { return m_sRTSettingsHasBeenSet; } CreateInputRTPSettings CreateInput::GetRTPSettings() const { return m_rTPSettings; } void CreateInput::SetRTPSettings(const CreateInputRTPSettings& _rTPSettings) { m_rTPSettings = _rTPSettings; m_rTPSettingsHasBeenSet = true; } bool CreateInput::RTPSettingsHasBeenSet() const { return m_rTPSettingsHasBeenSet; } string CreateInput::GetFailOver() const { return m_failOver; } void CreateInput::SetFailOver(const string& _failOver) { m_failOver = _failOver; m_failOverHasBeenSet = true; } bool CreateInput::FailOverHasBeenSet() const { return m_failOverHasBeenSet; }
8,944
2,879
//////////////////////////////////////////////////////////////////////////////////////////////////// // StandardLicenseDeactivate.cpp // Copyright (c) 2019 Pdfix. All Rights Reserved. //////////////////////////////////////////////////////////////////////////////////////////////////// #include "pdfixsdksamples/StandardLicenseDeactivate.h" // system #include <string> #include <iostream> // other libraries #include "Pdfix.h" using namespace PDFixSDK; namespace StandardLicenseDeactivate { // Adds a new text annotation. void Run() { // initialize Pdfix if (!Pdfix_init(Pdfix_MODULE_NAME)) throw std::runtime_error("Pdfix initialization fail"); Pdfix* pdfix = GetPdfix(); if (!pdfix) throw std::runtime_error("GetPdfix fail"); auto authorization = pdfix->GetStandardAuthorization(); if (!authorization) throw PdfixException(); if (!authorization->Deactivate()) throw PdfixException(); pdfix->Destroy(); } } //! [StandardLicenseDeactivate_cpp]
1,025
293
#include "bio_test_data.h" #include <bio/biobase_match.h> #include <bio/matrix.h> #include <bio/score_sequence.h> USING_BIO_NS; #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include <boost/io/ios_state.hpp> #include <boost/progress.hpp> #include <boost/test/parameterized_test.hpp> using namespace boost; using boost::unit_test::test_suite; #include <string> using namespace std; /** Results from TRANSFAC for the test sequence: matrix position core matrix sequence (always the factor name identifier (strand) match match (+)-strand is shown) V$DEAF1_01 86 (+) 1.000 0.857 gcgcctcagtgtacTTCCGaacgaa DEAF1 V$IPF1_Q4_01 111 (+) 1.000 0.975 tgagtCATTAataga IPF1 V$EFC_Q6 336 (-) 0.910 0.853 ttacccgaGTGACt RFX1 (EF-C) V$AP1_Q4 343 (+) 1.000 0.990 agTGACTgact AP-1 V$CREBP1_01 384 (+) 1.000 1.000 TTACGtaa CRE-BP1 V$CREBP1_01 384 (-) 1.000 1.000 ttaCGTAA CRE-BP1 V$HNF3ALPHA_Q6 446 (+) 1.000 0.973 TGTTTgctctc HNF-3alpha V$FOXP3_Q4 589 (+) 0.859 0.831 tatgaGCTGTttcagat FOXP3 V$HNF1_Q6 694 (-) 0.952 0.873 cttctgaaggAGTAActc HNF-1 V$COMP1_01 888 (+) 1.000 0.859 taggaaGATTGgccacatcagctt COMP1 V$CDPCR1_01 979 (-) 0.896 0.914 acgaTCTATg CDP CR1 */ void check_biobase_matches(BiobaseParams const & params) { ensure_biobase_params_built(); cout << "******* check_biobase_matches(): Testing with " << params.name.c_str() << " parameters" << endl; //progress_timer timer; boost::io::ios_precision_saver saver(cout); cout.precision(3); //build the pssms const Pssm matrix_pssm = *params.pssm; const Pssm iupac_pssm = make_pssm_from_iupac(params.iupac->begin(), params.iupac->end()); #ifdef VERBOSE_CHECKING cout << "Matrix pssm:" << endl << matrix_pssm << endl; cout << "IUPAC pssm:" << endl << iupac_pssm << endl; #endif //match to compute the score Hit pssm_match (-1.0, 0); Hit iupac_match (-1.0, 0); if (params.run_over_range) { pssm_match = score_sequence( matrix_pssm, params.seq_begin, params.seq_end, params.match_complement); iupac_match = score_sequence( iupac_pssm, params.seq_begin, params.seq_end, params.match_complement); } else { assert(params.seq_end - params.seq_begin == int( matrix_pssm.size() ) ); pssm_match.score = matrix_pssm.score(params.seq_begin, params.match_complement); iupac_match.score = iupac_pssm.score(params.seq_begin, params.match_complement); } //compare against expected BOOST_CHECK_CLOSE(params.target_match.score, pssm_match.score, 1.0); //only compare to 1% (we have 3 figure accuracy) BOOST_CHECK_CLOSE(iupac_match.score, pssm_match.score, params.iupac_tolerance); //IUPAC should be close to PSSM match BOOST_CHECK_EQUAL(params.target_match.position, pssm_match.position); //position of the pssm match BOOST_CHECK_EQUAL(params.target_match.complement, pssm_match.complement); //was it on the complementary strand } void register_biobase_matches_tests(boost::unit_test::test_suite * test) { ensure_biobase_params_built(); test->add(BOOST_PARAM_TEST_CASE(&check_biobase_matches, biobase_params.begin(), biobase_params.end()), 0); //superceded //test->add(BOOST_TEST_CASE(&check_ott_normaliser_cache), 0); //test->add(BOOST_TEST_CASE(&check_ott_normalisation), 0); //test->add(BOOST_TEST_CASE(&check_weak_pssms), 0); }
3,874
1,586
/* * This file is part of FFL project. * * The MIT License (MIT) * Copyright (C) 2017-2018 zhufeifei All rights reserved. * * MemcopyRender.hpp * Created by zhufeifei(34008081@qq.com) on 2018/06/28 * https://github.com/zhenfei2016/FFL-v2.git * android ANativewindowๆ•ฐๆฎๆ‹ท่ดๆ˜พ็คบๆ–นๅผ * */ #include "RenderInterface.hpp" #include "VideoFormat.hpp" namespace android{ class MemcopyRender : public RenderInterface{ public: MemcopyRender(); ~MemcopyRender(); public: // ่Žทๅ–ๆ”ฏๆŒ็š„ๆ ผๅผ // wanted: ๅฆ‚ๆžœไธบnUllๅˆ™่ฟ”ๅ›žๆ‰€ๆœ‰ๆ”ฏๆŒ็š„ๆ ผๅผ // ้žnull ่ฟ”ๅ›ž่ทŸไป–ๅŒน้…็š„ // fmtList: ่ฟ”ๅ›žๆ”ฏๆŒ็š„ๆ ผๅผlist // virtual void getSupportFormat(player::VideoSurface* surface,const player::VideoFormat* wanted,FFL::List<player::VideoFormat>& fmtList); virtual bool getOptimalFormat(player::VideoSurface* surface,const player::VideoFormat* wanted,player::VideoFormat* optinal); virtual bool isSupportFormat(player::VideoSurface* surface,const player::VideoFormat* wanted); // // ๅˆ›ๅปบ่ฟ™ไธชrender ๏ผŒarg่‡ชๅฎšไน‰็š„ๅ‚ๆ•ฐ // virtual status_t create(player::VideoSurface* surface,const player::VideoFormat* arg); // // ็ป˜ๅˆถๅ›พ็‰‡texๅˆฐ surfaceไธŠ้ข // virtual status_t draw(player::VideoSurface* surface,player::VideoTexture* tex); // // ้‡Šๆ”พ่ฟ™ไธชrender๏ผŒ้‡Šๆ”พๅŽ่ฟ™ไธชrenderๅฐฑไธๅฏ็”จไบ† // virtual void destroy(); }; }
1,405
505
#include "stdafx.h" #include <SA2ModLoader.h> // for everything #include "Networking.h" // for MessageID #include "globals.h" #include "OnGameState.h" DataPointer(uint, dword_174B058, 0x174B058); // Note that the name is misleading. This only happens when the gamestate changes to Ingame. // TODO: Real OnGameState // TODO: Consider removing since PoseEffect2PStartMan is now synchronized static void __stdcall OnGameState() { using namespace nethax; using namespace globals; // This is here because we overwrite its assignment with a call // in the original code. dword_174B058 = 0; if (!is_connected()) { return; } broker->send_ready_and_wait(MessageID::S_GameState); } // TODO: Make revertible void nethax::events::InitOnGameState() { WriteCall((void*)0x0043AAEE, OnGameState); }
804
296
// Concord // // Copyright (c) 2018 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache 2.0 license (the "License"). // You may not use this product except in compliance with the Apache 2.0 // License. // // This product may include a number of subcomponents with separate copyright // notices and license terms. Your use of these subcomponents is subject to the // terms and conditions of the subcomponent's license, as noted in the LICENSE // file. #include "ObjectsMetadataHandler.hpp" #include <stdio.h> #include <cstring> using namespace std; namespace bftEngine { ostream &operator<<(ostream &stream, const ObjectsMetadataHandler &objectsMetadataHandler) { stream << "ObjectsMetadataHandler: objectsNumber=" << objectsMetadataHandler.getObjectsNum() << '\n'; for (auto it : objectsMetadataHandler.getObjectsMap()) { stream << it.second.toString() << '\n'; } return stream; } size_t ObjectsMetadataHandler::getObjectsMetadataSize() { return (sizeof(objectsNum_) + sizeof(MetadataObjectInfo) * objectsNum_); } void ObjectsMetadataHandler::setObjectInfo(const MetadataObjectInfo &objectInfo) { objectsMap_.insert(pair<uint32_t, MetadataObjectInfo>(objectInfo.id, objectInfo)); } MetadataObjectInfo *ObjectsMetadataHandler::getObjectInfo(uint32_t objectId) { auto it = objectsMap_.find(objectId); if (it != objectsMap_.end()) { return &(it->second); } return nullptr; } } // namespace bftEngine
1,472
433
/* * SphereData.hpp * * Created on: 9 Aug 2016 * Author: Martin Schreiber <schreiberx@gmail.com> */ #ifndef SWEET_SPHERE_DATA_SPECTRAL_HPP_ #define SWEET_SPHERE_DATA_SPECTRAL_HPP_ #include <complex> #include <functional> #include <array> #include <cstring> #include <iostream> #include <fstream> #include <iomanip> #include <cassert> #include <limits> #include <utility> #include <functional> #include <cmath> #include <sweet/parmemcpy.hpp> #include <sweet/MemBlockAlloc.hpp> #include <sweet/openmp_helper.hpp> #include <sweet/sphere/SphereData_Config.hpp> #include <sweet/sphere/SphereData_Physical.hpp> #include <sweet/sphere/SphereData_PhysicalComplex.hpp> #include <sweet/SWEETError.hpp> class SphereData_Spectral { friend class SphereData_SpectralComplex; typedef std::complex<double> Tcomplex; public: const SphereData_Config *sphereDataConfig = nullptr; public: std::complex<double> *spectral_space_data = nullptr; std::complex<double>& operator[](std::size_t i) { return spectral_space_data[i]; } const std::complex<double>& operator[](std::size_t i) const { return spectral_space_data[i]; } void swap( SphereData_Spectral &i_sphereData ) { assert(sphereDataConfig == i_sphereData.sphereDataConfig); std::swap(spectral_space_data, i_sphereData.spectral_space_data); } public: SphereData_Spectral( const SphereData_Config *i_sphereDataConfig ) : sphereDataConfig(i_sphereDataConfig), spectral_space_data(nullptr) { assert(i_sphereDataConfig != 0); setup(i_sphereDataConfig); } public: SphereData_Spectral( const SphereData_Config *i_sphereDataConfig, const std::complex<double> &i_value ) : sphereDataConfig(i_sphereDataConfig), spectral_space_data(nullptr) { assert(i_sphereDataConfig != 0); setup(i_sphereDataConfig); spectral_set_value(i_value); } public: SphereData_Spectral( const SphereData_Config *i_sphereDataConfig, double &i_value ) : sphereDataConfig(i_sphereDataConfig), spectral_space_data(nullptr) { assert(i_sphereDataConfig != 0); setup(i_sphereDataConfig); spectral_set_value(i_value); } public: SphereData_Spectral() : sphereDataConfig(nullptr), spectral_space_data(nullptr) { } public: SphereData_Spectral( const SphereData_Spectral &i_sph_data ) : sphereDataConfig(i_sph_data.sphereDataConfig), spectral_space_data(nullptr) { if (i_sph_data.sphereDataConfig == nullptr) return; alloc_data(); operator=(i_sph_data); } public: SphereData_Spectral( SphereData_Spectral &&i_sph_data ) : sphereDataConfig(i_sph_data.sphereDataConfig), spectral_space_data(nullptr) { if (i_sph_data.sphereDataConfig == nullptr) return; alloc_data(); spectral_space_data = i_sph_data.spectral_space_data; } /** * Run validation checks to make sure that the physical and spectral spaces match in size */ public: inline void check( const SphereData_Config *i_sphereDataConfig ) const { assert(sphereDataConfig->physical_num_lat == i_sphereDataConfig->physical_num_lat); assert(sphereDataConfig->physical_num_lon == i_sphereDataConfig->physical_num_lon); assert(sphereDataConfig->spectral_modes_m_max == i_sphereDataConfig->spectral_modes_m_max); assert(sphereDataConfig->spectral_modes_n_max == i_sphereDataConfig->spectral_modes_n_max); } public: SphereData_Spectral& operator=( const SphereData_Spectral &i_sph_data ) { if (i_sph_data.sphereDataConfig == nullptr) return *this; if (sphereDataConfig == nullptr) setup(i_sph_data.sphereDataConfig); parmemcpy(spectral_space_data, i_sph_data.spectral_space_data, sizeof(Tcomplex)*sphereDataConfig->spectral_array_data_number_of_elements); return *this; } /** * This function implements copying the spectral data only. * * This becomes handy if coping with data which should be only transformed without dealiasing. */ public: SphereData_Spectral& load_nodealiasing( const SphereData_Spectral &i_sph_data ///< data to be converted to sphereDataConfig_nodealiasing ) { if (sphereDataConfig == nullptr) SWEETError("sphereDataConfig not initialized"); parmemcpy(spectral_space_data, i_sph_data.spectral_space_data, sizeof(Tcomplex)*sphereDataConfig->spectral_array_data_number_of_elements); return *this; } public: SphereData_Spectral& operator=( SphereData_Spectral &&i_sph_data ) { if (sphereDataConfig == nullptr) setup(i_sph_data.sphereDataConfig); std::swap(spectral_space_data, i_sph_data.spectral_space_data); return *this; } public: SphereData_Spectral spectral_returnWithDifferentModes( const SphereData_Config *i_sphereDataConfig ) const { SphereData_Spectral out(i_sphereDataConfig); /* * 0 = invalid * -1 = scale down * 1 = scale up */ int scaling_mode = 0; if (sphereDataConfig->spectral_modes_m_max < out.sphereDataConfig->spectral_modes_m_max) { scaling_mode = 1; } else if (sphereDataConfig->spectral_modes_m_max > out.sphereDataConfig->spectral_modes_m_max) { scaling_mode = -1; } if (sphereDataConfig->spectral_modes_n_max < out.sphereDataConfig->spectral_modes_n_max) { assert(scaling_mode != -1); scaling_mode = 1; } else if (sphereDataConfig->spectral_modes_n_max > out.sphereDataConfig->spectral_modes_n_max) { assert(scaling_mode != 1); scaling_mode = -1; } if (scaling_mode == 0) { // Just copy the data out = *this; return out; } if (scaling_mode == -1) { /* * more modes -> less modes */ SWEET_THREADING_SPACE_PARALLEL_FOR for (int m = 0; m <= out.sphereDataConfig->spectral_modes_m_max; m++) { Tcomplex *dst = &out.spectral_space_data[out.sphereDataConfig->getArrayIndexByModes(m, m)]; Tcomplex *src = &spectral_space_data[sphereDataConfig->getArrayIndexByModes(m, m)]; std::size_t size = sizeof(Tcomplex)*(out.sphereDataConfig->spectral_modes_n_max-m+1); memcpy(dst, src, size); } } else { /* * less modes -> more modes */ // zero all values out.spectral_set_zero(); SWEET_THREADING_SPACE_PARALLEL_FOR for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++) { Tcomplex *dst = &out.spectral_space_data[out.sphereDataConfig->getArrayIndexByModes(m, m)]; Tcomplex *src = &spectral_space_data[sphereDataConfig->getArrayIndexByModes(m, m)]; std::size_t size = sizeof(Tcomplex)*(sphereDataConfig->spectral_modes_n_max-m+1); memcpy(dst, src, size); } } return out; } /* * Setup spectral sphere data based on data in physical space */ void loadSphereDataPhysical( const SphereData_Physical &i_sphereDataPhysical ) { /** * Warning: The sphat_to_SH function is an in-situ operation. * Therefore, the data in the source array will be destroyed. * Hence, we create a copy */ SphereData_Physical tmp(i_sphereDataPhysical); spat_to_SH(sphereDataConfig->shtns, tmp.physical_space_data, spectral_space_data); } /* * Return the data converted to physical space */ SphereData_Physical getSphereDataPhysical() const { /** * Warning: This is an in-situ operation. * Therefore, the data in the source array will be destroyed. */ SphereData_Spectral tmp(*this); SphereData_Physical retval(sphereDataConfig); SH_to_spat(sphereDataConfig->shtns, tmp.spectral_space_data, retval.physical_space_data); return retval; } /* * Return the data converted to physical space * * alias for "getSphereDataPhysical" */ SphereData_Physical toPhys() const { /** * Warning: This is an in-situ operation. * Therefore, the data in the source array will be destroyed. */ SphereData_Spectral tmp(*this); SphereData_Physical retval(sphereDataConfig); SH_to_spat(sphereDataConfig->shtns, tmp.spectral_space_data, retval.physical_space_data); return retval; } SphereData_PhysicalComplex getSphereDataPhysicalComplex() const { SphereData_PhysicalComplex out(sphereDataConfig); /* * WARNING: * We have to use a temporary array here because of destructive SH transformations */ SphereData_Spectral tmp_spectral(*this); SphereData_Physical tmp_physical(sphereDataConfig); SH_to_spat(sphereDataConfig->shtns, tmp_spectral.spectral_space_data, tmp_physical.physical_space_data); parmemcpy(out.physical_space_data, tmp_physical.physical_space_data, sizeof(double)*sphereDataConfig->physical_array_data_number_of_elements); return out; } SphereData_Spectral( const SphereData_Physical &i_sphere_data_physical ) { setup(i_sphere_data_physical.sphereDataConfig); loadSphereDataPhysical(i_sphere_data_physical); } SphereData_Spectral operator+( const SphereData_Spectral &i_sph_data ) const { check(i_sph_data.sphereDataConfig); SphereData_Spectral out(sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) out.spectral_space_data[idx] = spectral_space_data[idx] + i_sph_data.spectral_space_data[idx]; return out; } SphereData_Spectral& operator+=( const SphereData_Spectral &i_sph_data ) { check(i_sph_data.sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) spectral_space_data[idx] += i_sph_data.spectral_space_data[idx]; return *this; } SphereData_Spectral& operator-=( const SphereData_Spectral &i_sph_data ) { check(i_sph_data.sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) spectral_space_data[idx] -= i_sph_data.spectral_space_data[idx]; return *this; } SphereData_Spectral operator-( const SphereData_Spectral &i_sph_data ) const { check(i_sph_data.sphereDataConfig); SphereData_Spectral out(sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) out.spectral_space_data[idx] = spectral_space_data[idx] - i_sph_data.spectral_space_data[idx]; return out; } SphereData_Spectral operator-() const { SphereData_Spectral out(sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) out.spectral_space_data[idx] = -spectral_space_data[idx]; return out; } SphereData_Spectral operator*( const SphereData_Spectral &i_sph_data ) const { check(i_sph_data.sphereDataConfig); SphereData_Physical a = getSphereDataPhysical(); SphereData_Physical b = i_sph_data.toPhys(); SphereData_Physical mul(sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (std::size_t i = 0; i < sphereDataConfig->physical_array_data_number_of_elements; i++) mul.physical_space_data[i] = a.physical_space_data[i]*b.physical_space_data[i]; SphereData_Spectral out(mul); return out; } SphereData_Spectral operator/( const SphereData_Spectral &i_sph_data ) const { check(i_sph_data.sphereDataConfig); SphereData_Physical a = getSphereDataPhysical(); SphereData_Physical b = i_sph_data.toPhys(); SphereData_Physical div(sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (std::size_t i = 0; i < sphereDataConfig->physical_array_data_number_of_elements; i++) div.physical_space_data[i] = a.physical_space_data[i]/b.physical_space_data[i]; SphereData_Spectral out(div); return out; } SphereData_Spectral operator*( double i_value ) const { SphereData_Spectral out(sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) out.spectral_space_data[idx] = spectral_space_data[idx]*i_value; return out; } const SphereData_Spectral& operator*=( double i_value ) const { SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) spectral_space_data[idx] *= i_value; return *this; } const SphereData_Spectral& operator/=( double i_value ) const { SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) spectral_space_data[idx] /= i_value; return *this; } const SphereData_Spectral& operator*=( const std::complex<double> &i_value ) const { SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) spectral_space_data[idx] *= i_value; return *this; } SphereData_Spectral operator/( double i_value ) const { SphereData_Spectral out(sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) out.spectral_space_data[idx] = spectral_space_data[idx]/i_value; return out; } SphereData_Spectral operator+( double i_value ) const { SphereData_Spectral out(*this); out.spectral_space_data[0] += i_value*std::sqrt(4.0*M_PI); return out; } SphereData_Spectral operator_scalar_sub_this( double i_value ) const { SphereData_Spectral out(sphereDataConfig); SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++) out.spectral_space_data[idx] = -spectral_space_data[idx]; out.spectral_space_data[0] = i_value*std::sqrt(4.0*M_PI) + out.spectral_space_data[0]; return out; } const SphereData_Spectral& operator+=( double i_value ) const { spectral_space_data[0] += i_value*std::sqrt(4.0*M_PI); return *this; } SphereData_Spectral operator-( double i_value ) const { SphereData_Spectral out(*this); out.spectral_space_data[0] -= i_value*std::sqrt(4.0*M_PI); return out; } SphereData_Spectral& operator-=( double i_value ) { spectral_space_data[0] -= i_value*std::sqrt(4.0*M_PI); return *this; } public: void setup( const SphereData_Config *i_sphereDataConfig ) { sphereDataConfig = i_sphereDataConfig; alloc_data(); } public: void setup( const SphereData_Config *i_sphereDataConfig, double i_value ) { sphereDataConfig = i_sphereDataConfig; alloc_data(); spectral_set_value(i_value); } private: void alloc_data() { assert(spectral_space_data == nullptr); spectral_space_data = MemBlockAlloc::alloc<Tcomplex>(sphereDataConfig->spectral_array_data_number_of_elements * sizeof(Tcomplex)); } public: void setup_if_required( const SphereData_Config *i_sphereDataConfig ) { if (sphereDataConfig != nullptr) return; setup(i_sphereDataConfig); } public: void free() { if (spectral_space_data != nullptr) { MemBlockAlloc::free(spectral_space_data, sphereDataConfig->spectral_array_data_number_of_elements * sizeof(Tcomplex)); spectral_space_data = nullptr; sphereDataConfig = nullptr; } } public: ~SphereData_Spectral() { free(); } /** * Solve a Helmholtz problem given by * * (a + b D^2) x = rhs */ inline SphereData_Spectral spectral_solve_helmholtz( const double &i_a, const double &i_b, double r ) { SphereData_Spectral out(*this); const double a = i_a; const double b = i_b/(r*r); out.spectral_update_lambda( [&]( int n, int m, std::complex<double> &io_data ) { io_data /= (a + (-b*(double)n*((double)n+1.0))); } ); return out; } /** * Solve a Laplace problem given by * * (D^2) x = rhs */ inline SphereData_Spectral spectral_solve_laplace( double r ) { SphereData_Spectral out(*this); const double b = 1.0/(r*r); out.spectral_update_lambda( [&]( int n, int m, std::complex<double> &io_data ) { if (n == 0) io_data = 0; else io_data /= (-b*(double)n*((double)n+1.0)); } ); return out; } /** * Truncate modes which are not representable in spectral space */ const SphereData_Spectral& spectral_truncate() const { SphereData_Physical tmp(sphereDataConfig); SH_to_spat(sphereDataConfig->shtns, spectral_space_data, tmp.physical_space_data); spat_to_SH(sphereDataConfig->shtns, tmp.physical_space_data, spectral_space_data); return *this; } void spectral_update_lambda( std::function<void(int,int,Tcomplex&)> i_lambda ) { SWEET_THREADING_SPACE_PARALLEL_FOR for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++) { std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m); for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++) { i_lambda(n, m, spectral_space_data[idx]); idx++; } } } const std::complex<double>& spectral_get_DEPRECATED( int i_n, int i_m ) const { static const std::complex<double> zero = {0,0}; if (i_n < 0 || i_m < 0) return zero; if (i_n > sphereDataConfig->spectral_modes_n_max) return zero; if (i_m > sphereDataConfig->spectral_modes_m_max) return zero; if (i_m > i_n) return zero; assert (i_m <= sphereDataConfig->spectral_modes_m_max); return spectral_space_data[sphereDataConfig->getArrayIndexByModes(i_n, i_m)]; } const std::complex<double>& spectral_get_( int i_n, int i_m ) const { assert(i_n >= 0 && i_m >= 0); assert(i_n <= sphereDataConfig->spectral_modes_n_max); assert(i_m <= sphereDataConfig->spectral_modes_m_max); assert(i_m <= i_n); return spectral_space_data[sphereDataConfig->getArrayIndexByModes(i_n, i_m)]; } void spectral_set( int i_n, int i_m, const std::complex<double> &i_data ) const { #if SWEET_DEBUG if (i_n < 0 || i_m < 0) SWEETError("Out of boundary a"); if (i_n > sphereDataConfig->spectral_modes_n_max) SWEETError("Out of boundary b"); if (i_m > sphereDataConfig->spectral_modes_m_max) SWEETError("Out of boundary c"); if (i_m > i_n) SWEETError("Out of boundary d"); assert (i_m <= sphereDataConfig->spectral_modes_m_max); #endif spectral_space_data[sphereDataConfig->getArrayIndexByModes(i_n, i_m)] = i_data; } /* * Set all values to zero */ void spectral_set_zero() { SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int i = 0; i < sphereDataConfig->spectral_array_data_number_of_elements; i++) spectral_space_data[i] = {0,0}; } /* * Set all values to value */ void spectral_set_value( const std::complex<double> &i_value ) { SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD for (int i = 0; i < sphereDataConfig->spectral_array_data_number_of_elements; i++) spectral_space_data[i] = i_value; } /* * Add a constant in physical space by adding the corresponding value in spectral space */ void spectral_add_physical_constant( double i_value ) const { this->spectral_space_data[0] += i_value*std::sqrt(4.0*M_PI); } /** * return the maximum of all absolute values, use quad precision for reduction */ std::complex<double> spectral_reduce_sum_quad_increasing() const { std::complex<double> sum = 0; std::complex<double> c = 0; #if SWEET_THREADING_SPACE //#pragma omp parallel for PROC_BIND_CLOSE reduction(+:sum,c) #endif for (int i = 0; i < sphereDataConfig->spectral_array_data_number_of_elements; i++) { std::complex<double> value = spectral_space_data[i]*(double)i; // Use Kahan summation std::complex<double> y = value - c; std::complex<double> t = sum + y; c = (t - sum) - y; sum = t; } sum -= c; return sum; } /** * return the sum of all values, use quad precision for reduction */ std::complex<double> spectral_reduce_sum_quad() const { std::complex<double> sum = 0; std::complex<double> c = 0; #if SWEET_THREADING_SPACE //#pragma omp parallel for PROC_BIND_CLOSE reduction(+:sum,c) #endif for (int i = 0; i < sphereDataConfig->spectral_array_data_number_of_elements; i++) { std::complex<double> value = spectral_space_data[i]; // Use Kahan summation std::complex<double> y = value - c; std::complex<double> t = sum + y; c = (t - sum) - y; sum = t; } sum -= c; return sum; } /** * return the sum of squares of all values, use quad precision for reduction * Important: Since m=0 modes appear only once and m>0 appear twice in the full spectrum */ double spectral_reduce_sum_sqr_quad() const { std::complex<double> sum = 0; //std::complex<double> c = 0; //m=0 case - weight 1 std::size_t idx = sphereDataConfig->getArrayIndexByModes(0, 0); for (int n = 0; n <= sphereDataConfig->spectral_modes_n_max; n++) { sum += spectral_space_data[idx]*std::conj(spectral_space_data[idx]); idx++; } //m>0 case - weight 2, as they appear twice for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++) { std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m); for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++) { sum += 2.0*spectral_space_data[idx]*std::conj(spectral_space_data[idx]); idx++; } } return sum.real(); } /** * Return the minimum value */ std::complex<double> spectral_reduce_min() const { std::complex<double> error = std::numeric_limits<double>::infinity(); for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++) { error.real(std::min(spectral_space_data[j].real(), error.real())); error.imag(std::min(spectral_space_data[j].imag(), error.imag())); } return error; } /** * Return the max value */ std::complex<double> spectral_reduce_max() const { std::complex<double> error = -std::numeric_limits<double>::infinity(); for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++) { error.real(std::max(spectral_space_data[j].real(), error.real())); error.imag(std::max(spectral_space_data[j].imag(), error.imag())); } return error; } /** * Return the max abs value */ double spectral_reduce_max_abs() const { double error = -std::numeric_limits<double>::infinity(); std::complex<double> w = {0,0}; for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++) { w = spectral_space_data[j]*std::conj(spectral_space_data[j]); error = std::max(std::abs(w), error); } return error; } /** * Return the minimum abs value */ double spectral_reduce_min_abs() const { double error = std::numeric_limits<double>::infinity(); std::complex<double> w = {0,0}; for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++) { w = spectral_space_data[j]*std::conj(spectral_space_data[j]); error = std::min(std::abs(w), error); } return error; } bool spectral_reduce_is_any_nan_or_inf() const { bool retval = false; #if SWEET_THREADING_SPACE #pragma omp parallel for simd reduction(|:retval) #endif for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++) { retval |= std::isnan(spectral_space_data[j].real()); retval |= std::isinf(spectral_space_data[j].real()); retval |= std::isnan(spectral_space_data[j].imag()); retval |= std::isinf(spectral_space_data[j].imag()); } return retval; } bool spectral_is_first_nan_or_inf() const { bool retval = false; retval |= std::isnan(spectral_space_data[0].real()); retval |= std::isinf(spectral_space_data[0].real()); retval |= std::isnan(spectral_space_data[0].imag()); retval |= std::isinf(spectral_space_data[0].imag()); return retval; } void spectral_print( int i_precision = 16, double i_abs_threshold = -1 ) const { std::cout << std::setprecision(i_precision); std::cout << "m \\ n ----->" << std::endl; for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++) { std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m); for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++) { if (std::abs(spectral_space_data[idx]) < i_abs_threshold) std::cout << 0 << "\t"; else std::cout << spectral_space_data[idx] << "\t"; idx++; } std::cout << std::endl; } } void spectral_structure_print( int i_precision = 16, double i_abs_threshold = -1 ) const { std::cout << std::setprecision(i_precision); std::cout << "m \\ n ----->" << std::endl; for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++) { //std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m); for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++) { std::cout << "(" << m <<"," << n <<")" << "\t"; } std::cout << std::endl; } } void spectrum_file_write( const std::string &i_filename, const char *i_title = "", int i_precision = 20 ) const { std::ofstream file(i_filename, std::ios_base::trunc); file << std::setprecision(i_precision); file << "#SWEET_SPHERE_SPECTRAL_DATA_ASCII" << std::endl; file << "#TI " << i_title << std::endl; // Use 0 to make it processable by python file << "0\t"; std::complex<double> w = {0,0}; std::vector<double> sum(sphereDataConfig->spectral_modes_n_max+1,0); std::vector<double> sum_squared(sphereDataConfig->spectral_modes_n_max+1,0); std::vector<double> max(sphereDataConfig->spectral_modes_n_max+1,0); for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++) { std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m); for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++) { w = spectral_space_data[idx]; idx++; sum[n] += std::abs(w); sum_squared[n] += std::abs(w * w); if (std::abs(w) >= max[n]) max[n] = std::abs(w); } } file << sphereDataConfig->spectral_modes_m_max << " " << sphereDataConfig->spectral_modes_n_max << std::endl; for (int n = 0; n <= sphereDataConfig->spectral_modes_n_max; n++) file << n << " " << sum[n] << " " << max[n] << " " << std::sqrt(sum_squared[n]) << std::endl; file.close(); } void spectrum_abs_file_write_line( const std::string &i_filename, const char *i_title = "", const double i_time = 0.0, int i_precision = 20, double i_abs_threshold = -1, int i_reduce_mode_factor = 1 ) const { std::ofstream file; if(i_time == 0.0){ file.open(i_filename, std::ios_base::trunc); file << std::setprecision(i_precision); file << "#SWEET_SPHERE_SPECTRAL_ABS_EVOL_ASCII" << std::endl; file << "#TI " << i_title << std::endl; file << "0\t"<< std::endl; // Use 0 to make it processable by python file << "(n_max="<<sphereDataConfig->spectral_modes_n_max << " m_max=" << sphereDataConfig->spectral_modes_n_max << ")" << std::endl; file << "timestamp\t" ; for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max/i_reduce_mode_factor; m++) { //std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m); for (int n = m; n <= sphereDataConfig->spectral_modes_n_max/i_reduce_mode_factor; n++) { file << "(" << n << ";" << m << ")\t" ; } } file<< "SpectralSum" <<std::endl; } else{ file.open(i_filename, std::ios_base::app); file << std::setprecision(i_precision); } std::complex<double> w = {0,0}; double wabs = 0.0; double sum = 0.0; //std::cout << "n" << " " << "m" << " " << "norm" <<std::endl; file << i_time << "\t"; for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max/i_reduce_mode_factor; m++) { std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m); for (int n = m; n <= sphereDataConfig->spectral_modes_n_max/i_reduce_mode_factor; n++) { w = spectral_space_data[idx]; wabs = std::abs(w * std::conj(w)); if ( m > 0 ) sum += 2*wabs; //term appears twice in the spectrum else sum += wabs; // term appears only once if ( wabs < i_abs_threshold){ //file << "(" << n << "," << m << ")\t"<<std::endl; file << 0 << "\t"; //<<std::endl; } else{ //file << "(" << n << "," << m << ")\t"<<std::endl; file << wabs << "\t"; //<<std::endl;; //std::cout << n << " " << m << " " << wabs <<std::endl; } idx++; } } file<< sum << std::endl; file.close(); } void spectrum_phase_file_write_line( const std::string &i_filename, const char *i_title = "", const double i_time = 0.0, int i_precision = 20, double i_abs_threshold = -1, int i_reduce_mode_factor = 1 ) const { std::ofstream file; if(i_time == 0.0){ file.open(i_filename, std::ios_base::trunc); file << std::setprecision(i_precision); file << "#SWEET_SPHERE_SPECTRAL_PHASE_EVOL_ASCII" << std::endl; file << "#TI " << i_title << std::endl; file << "0\t"<< std::endl; // Use 0 to make it processable by python file << "(n_max="<<sphereDataConfig->spectral_modes_n_max << " m_max=" << sphereDataConfig->spectral_modes_n_max << ")" << std::endl; file << "timestamp\t" ; for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max/i_reduce_mode_factor; m++) { //std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m); for (int n = m; n <= sphereDataConfig->spectral_modes_n_max/i_reduce_mode_factor; n++) { file << "(" << n << ";" << m << ")\t" ; } } file << std::endl; } else{ file.open(i_filename, std::ios_base::app); file << std::setprecision(i_precision); } std::complex<double> w = {0,0}; double wphase = 0.0; //std::cout << "n" << " " << "m" << " " << "norm" <<std::endl; file << i_time << "\t"; for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max/i_reduce_mode_factor; m++) { std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m); for (int n = m; n <= sphereDataConfig->spectral_modes_n_max/i_reduce_mode_factor; n++) { w = spectral_space_data[idx]; wphase = std::arg(w); // std::abs(w * std::conj(w)); //file << "(" << n << "," << m << ")\t"<<std::endl; file << wphase << "\t"; //<<std::endl;; //std::cout << n << " " << m << " " << wabs <<std::endl; idx++; } } file<< std::endl; file.close(); } /** * Write the spectral data to a file in binary format */ void file_write_binary_spectral( const std::string &i_filename ) const { std::ofstream file(i_filename, std::ios_base::trunc | std::ios_base::binary); if (!file.is_open()) SWEETError("Error while opening file"); file << "SWEET" << std::endl; file << "DATA_TYPE SH_DATA" << std::endl; file << "MODES_M_MAX " << sphereDataConfig->spectral_modes_m_max << std::endl; file << "MODES_N_MAX " << sphereDataConfig->spectral_modes_n_max << std::endl; file << "GRID_TYPE GAUSSIAN" << std::endl; file << "NUM_ELEMENTS " << sphereDataConfig->spectral_array_data_number_of_elements << std::endl; file << "FIN" << std::endl; file.write((const char*)spectral_space_data, sizeof(std::complex<double>)*sphereDataConfig->spectral_array_data_number_of_elements); file.close(); } void file_read_binary_spectral( const std::string &i_filename ) { std::ifstream file(i_filename, std::ios_base::binary); if (!file.is_open()) SWEETError("Error while opening file"); std::string magic; std::getline(file, magic); if (magic != "SWEET") SWEETError("Magic code 'SWEET' not found"); std::string data_type; int num_lon = -1; int num_lat = -1; int size = -1; while (true) { std::string buf; file >> buf; if (buf == "FIN") break; if (buf == "DATA_TYPE") { // load data type file >> data_type; std::cout << data_type << std::endl; continue; } if (buf == "NUM_LON") { file >> buf; num_lon = std::stoi(buf); std::cout << num_lon << std::endl; continue; } if (buf == "NUM_LAT") { file >> buf; num_lat = std::stoi(buf); std::cout << num_lat << std::endl; continue; } if (buf == "SIZE") { file >> buf; size = std::stoi(buf); std::cout << size << std::endl; continue; } SWEETError("Unknown Tag '"+buf+"'"); } // read last newline char nl; file.read(&nl, 1); std::cout << file.tellg() << std::endl; if (data_type != "SH_DATA") SWEETError("Unknown data type '"+data_type+"'"); if (num_lon != sphereDataConfig->spectral_modes_m_max) SWEETError("NUM_LON "+std::to_string(num_lon)+" doesn't match SphereDataConfig"); if (num_lat != sphereDataConfig->spectral_modes_n_max) SWEETError("NUM_LAT "+std::to_string(num_lat)+" doesn't match SphereDataConfig"); file.read((char*)spectral_space_data, sizeof(std::complex<double>)*sphereDataConfig->spectral_array_data_number_of_elements); file.close(); } void normalize( const std::string &normalization = "" ) { if (normalization == "avg_zero") { // move average value to 0 double phi_min = getSphereDataPhysical().physical_reduce_min(); double phi_max = getSphereDataPhysical().physical_reduce_max(); double avg = 0.5*(phi_max+phi_min); operator-=(avg); } else if (normalization == "min_zero") { // move minimum value to zero double phi_min = getSphereDataPhysical().physical_reduce_min(); operator-=(phi_min); } else if (normalization == "max_zero") { // move maximum value to zero double phi_max = getSphereDataPhysical().physical_reduce_max(); operator-=(phi_max); } else if (normalization == "") { } else { SWEETError("Normalization not supported!"); } } }; /** * operator to support operations such as: * * 1.5 * arrayData; * * Otherwise, we'd have to write it as arrayData*1.5 * */ inline static SphereData_Spectral operator*( double i_value, const SphereData_Spectral &i_array_data ) { return ((SphereData_Spectral&)i_array_data)*i_value; } /** * operator to support operations such as: * * 1.5 + arrayData * */ inline static SphereData_Spectral operator+( double i_value, const SphereData_Spectral &i_array_data ) { return ((SphereData_Spectral&)i_array_data)+i_value; } /** * operator to support operations such as: * * 1.5 - arrayData * */ inline static SphereData_Spectral operator-( double i_value, const SphereData_Spectral &i_array_data ) { return i_array_data.operator_scalar_sub_this(i_value); } #endif /* SWEET_SPHERE_DATA_HPP_ */
34,525
14,994
//// //// 1110.cpp //// Algorithm //// //// Created by ๋™๊ท  on 2018. 6. 1.. //// Copyright ยฉ 2018๋…„ ๋™๊ท . All rights reserved. //// // //#include <iostream> //using namespace std; // //int main() { // // int number, number2 , tmp1, tmp2, tmp3; // int cnt =0; // // cin >> number; // number2 = number; // // tmp1 = number2/10; // tmp2 = number2%10; // tmp3 = (tmp1+tmp2) % 10; // // number2 = tmp2 *10 + tmp3; // // return 0; // //}
478
217
#include "ruleMixedSites.h" #include <frozen/set.h> #include <nextclade/nextclade.h> #include <algorithm> #include <optional> #include <vector> #include "../utils/mapFind.h" #include "getQcRuleStatus.h" namespace Nextclade { namespace { constexpr frozen::set<Nucleotide, 6> GOOD_NUCLEOTIDES = { Nucleotide::A, Nucleotide::C, Nucleotide::G, Nucleotide::T, Nucleotide::N, Nucleotide::GAP, }; }//namespace std::optional<QCResultMixedSites> ruleMixedSites(// const AnalysisResult& result, // const std::vector<NucleotideSubstitution>&, // const QCRulesConfigMixedSites& config // ) { if (!config.enabled) { return {}; } int totalMixedSites = 0; for (const auto& [nuc, total] : result.nucleotideComposition) { if (has(GOOD_NUCLEOTIDES, nuc)) { continue; } totalMixedSites += total; } const auto score = std::max(0.0, 100.0 * (totalMixedSites / config.mixedSitesThreshold)); const auto& status = getQcRuleStatus(score); return QCResultMixedSites{ .score = score, .status = status, .totalMixedSites = totalMixedSites, .mixedSitesThreshold = config.mixedSitesThreshold, }; } }// namespace Nextclade
1,285
482
/* LICENSE ------- Copyright 2005 Nullsoft, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Nullsoft 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. */ // video delay // copyright tom holden, 2002 // mail: cfp@myrealbox.com #include "r_defs.h" #include "resource.h" #include <windows.h> #ifndef LASER #define MOD_NAME "Trans / Video Delay" #define C_DELAY C_VideoDelayClass class C_DELAY : public C_RBASE { protected: public: // standard ape members C_DELAY(); virtual ~C_DELAY(); virtual int render(char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h); virtual HWND conf(HINSTANCE hInstance, HWND hwndParent); virtual char* get_desc(); virtual void load_config(unsigned char* data, int len); virtual int save_config(unsigned char* data); // saved members bool enabled; bool usebeats; unsigned int delay; // unsaved members LPVOID buffer; LPVOID inoutpos; unsigned long buffersize; unsigned long virtualbuffersize; unsigned long oldvirtualbuffersize; unsigned long framessincebeat; unsigned long framedelay; unsigned long framemem; unsigned long oldframemem; }; // global configuration dialog pointer static C_DELAY* g_Delay; // global DLL instance pointer static HINSTANCE g_hDllInstance; // configuration screen static BOOL CALLBACK g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { char value[16]; int val; unsigned int objectcode, objectmessage; HWND hwndEdit; switch (uMsg) { case WM_INITDIALOG: //init CheckDlgButton(hwndDlg, IDC_CHECK1, g_Delay->enabled); CheckDlgButton(hwndDlg, IDC_RADIO1, g_Delay->usebeats); CheckDlgButton(hwndDlg, IDC_RADIO2, !g_Delay->usebeats); hwndEdit = GetDlgItem(hwndDlg, IDC_EDIT1); _itoa(g_Delay->delay, value, 10); SetWindowText(hwndEdit, value); return 1; case WM_COMMAND: objectcode = LOWORD(wParam); objectmessage = HIWORD(wParam); // see if enable checkbox is checked if (objectcode == IDC_CHECK1) { g_Delay->enabled = IsDlgButtonChecked(hwndDlg, IDC_CHECK1) == 1; return 0; } // see if beats radiobox is checked if (objectcode == IDC_RADIO1) { if (IsDlgButtonChecked(hwndDlg, IDC_RADIO1) == 1) { g_Delay->usebeats = true; CheckDlgButton(hwndDlg, IDC_RADIO2, BST_UNCHECKED); g_Delay->framedelay = 0; g_Delay->framessincebeat = 0; hwndEdit = GetDlgItem(hwndDlg, IDC_EDIT1); //new if (g_Delay->delay > 16) { //new g_Delay->delay = 16; //new SetWindowText(hwndEdit, "16"); //new } //new } else g_Delay->usebeats = false; return 0; } // see if frames radiobox is checked if (objectcode == IDC_RADIO2) { if (IsDlgButtonChecked(hwndDlg, IDC_RADIO2) == 1) { g_Delay->usebeats = false; CheckDlgButton(hwndDlg, IDC_RADIO1, BST_UNCHECKED); g_Delay->framedelay = g_Delay->delay; } else g_Delay->usebeats = true; return 0; } //get and put data from the delay box if (objectcode == IDC_EDIT1) { hwndEdit = GetDlgItem(hwndDlg, IDC_EDIT1); if (objectmessage == EN_CHANGE) { GetWindowText(hwndEdit, value, 16); val = atoi(value); if (g_Delay->usebeats) { if (val > 16) val = 16; } //new else { if (val > 200) val = 200; } //new g_Delay->delay = val; g_Delay->framedelay = g_Delay->usebeats ? 0 : g_Delay->delay; } else if (objectmessage == EN_KILLFOCUS) { _itoa(g_Delay->delay, value, 10); SetWindowText(hwndEdit, value); } return 0; } } return 0; } // set up default configuration C_DELAY::C_DELAY() { // enable enabled = true; usebeats = false; delay = 10; framedelay = 10; framessincebeat = 0; buffersize = 1; virtualbuffersize = 1; oldvirtualbuffersize = 1; buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE); inoutpos = buffer; } // virtual destructor C_DELAY::~C_DELAY() { VirtualFree(buffer, buffersize, MEM_DECOMMIT); } // RENDER FUNCTION: // render should return 0 if it only used framebuffer, or 1 if the new output data is in fbout // w and h are the-width and height of the screen, in pixels. // isBeat is 1 if a beat has been detected. // visdata is in the format of [spectrum:0,wave:1][channel][band]. int C_DELAY::render(char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h) { if (isBeat & 0x80000000) return 0; framemem = w * h * 4; if (usebeats) { if (isBeat) { framedelay = framessincebeat * delay; //changed if (framedelay > 400) framedelay = 400; //new framessincebeat = 0; } framessincebeat++; } if (enabled && framedelay != 0) { virtualbuffersize = framedelay * framemem; if (framemem == oldframemem) { if (virtualbuffersize != oldvirtualbuffersize) { if (virtualbuffersize > oldvirtualbuffersize) { if (virtualbuffersize > buffersize) { // allocate new memory if (!VirtualFree(buffer, buffersize, MEM_DECOMMIT)) return 0; if (usebeats) { buffersize = 2 * virtualbuffersize; if (buffersize > framemem * 400) buffersize = framemem * 400; //new buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE); if (buffer == NULL) { buffersize = virtualbuffersize; buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE); } } else { buffersize = virtualbuffersize; buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE); } inoutpos = buffer; if (buffer == NULL) { framedelay = 0; framessincebeat = 0; return 0; } } else { unsigned long size = (((unsigned long)buffer) + oldvirtualbuffersize) - ((unsigned long)inoutpos); unsigned long l = ((unsigned long)buffer) + virtualbuffersize; unsigned long d = l - size; MoveMemory((LPVOID)d, inoutpos, size); for (l = (unsigned long)inoutpos; l < d; l += framemem) CopyMemory((LPVOID)l, (LPVOID)d, framemem); } } else { // virtualbuffersize < oldvirtualbuffersize unsigned long presegsize = ((unsigned long)inoutpos) - ((unsigned long)buffer) + framemem; if (presegsize > virtualbuffersize) { MoveMemory(buffer, (LPVOID)(((unsigned long)buffer) + presegsize - virtualbuffersize), virtualbuffersize); inoutpos = (LPVOID)(((unsigned long)buffer) + virtualbuffersize - framemem); } else if (presegsize < virtualbuffersize) MoveMemory((LPVOID)(((unsigned long)inoutpos) + framemem), (LPVOID)(((unsigned long)buffer) + oldvirtualbuffersize + presegsize - virtualbuffersize), virtualbuffersize - presegsize); } oldvirtualbuffersize = virtualbuffersize; } } else { // allocate new memory if (!VirtualFree(buffer, buffersize, MEM_DECOMMIT)) return 0; if (usebeats) { buffersize = 2 * virtualbuffersize; buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE); if (buffer == NULL) { buffersize = virtualbuffersize; buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE); } } else { buffersize = virtualbuffersize; buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE); } inoutpos = buffer; if (buffer == NULL) { framedelay = 0; framessincebeat = 0; return 0; } oldvirtualbuffersize = virtualbuffersize; } oldframemem = framemem; CopyMemory(fbout, inoutpos, framemem); CopyMemory(inoutpos, framebuffer, framemem); inoutpos = (LPVOID)(((unsigned long)inoutpos) + framemem); if ((unsigned long)inoutpos >= ((unsigned long)buffer) + virtualbuffersize) inoutpos = buffer; return 1; } else return 0; } HWND C_DELAY::conf(HINSTANCE hInstance, HWND hwndParent) // return NULL if no config dialog possible { g_Delay = this; return CreateDialog(hInstance, MAKEINTRESOURCE(IDD_CFG_VIDEODELAY), hwndParent, g_DlgProc); } char* C_DELAY::get_desc(void) { return MOD_NAME; } // load_/save_config are called when saving and loading presets (.avs files) #define GET_INT() (data[pos] | (data[pos + 1] << 8) | (data[pos + 2] << 16) | (data[pos + 3] << 24)) void C_DELAY::load_config(unsigned char* data, int len) // read configuration of max length "len" from data. { int pos = 0; // always ensure there is data to be loaded if (len - pos >= 4) { // load activation toggle enabled = (GET_INT() == 1); pos += 4; } if (len - pos >= 4) { // load beats toggle usebeats = (GET_INT() == 1); pos += 4; } if (len - pos >= 4) { // load delay delay = GET_INT(); if (usebeats) { if (delay > 16) delay = 16; } //new else { if (delay > 200) delay = 200; } //new pos += 4; } } // write configuration to data, return length. config data should not exceed 64k. #define PUT_INT(y) \ data[pos] = (y)&255; \ data[pos + 1] = (y >> 8) & 255; \ data[pos + 2] = (y >> 16) & 255; \ data[pos + 3] = (y >> 24) & 255 int C_DELAY::save_config(unsigned char* data) { int pos = 0; PUT_INT((int)enabled); pos += 4; PUT_INT((int)usebeats); pos += 4; PUT_INT((unsigned int)delay); pos += 4; return pos; } // export stuff C_RBASE* R_VideoDelay(char* desc) // creates a new effect object if desc is NULL, otherwise fills in desc with description { if (desc) { strcpy(desc, MOD_NAME); return NULL; } return (C_RBASE*)new C_DELAY(); } #endif
12,739
4,128
#ifndef METRICS_HPP #define METRICS_HPP static const size_t MAX_NORM=~size_t(0); template<class FloatType,size_t P> struct Lnorm_impl { static FloatType call(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask) { FloatType sm=0.0; for(size_t di=0;di<n;di++) { if(mask.size() == n && mask[di]) { FloatType diff=f2[di]-f1[di]; sm+=std::pow(std::fabs(diff),P); } } return std::pow(sm,1.0/static_cast<double>(P)); } }; template<class FloatType> struct Lnorm_impl<FloatType,MAX_NORM> { static FloatType call(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask) { FloatType sm=0.0; for(size_t di=0;di<n;di++) { if(mask.size() == n && mask[di]) { FloatType diff=f2[di]-f1[di]; sm=std::max(sm,std::fabs(diff)); } } return sm; } }; template<class FloatType> struct Lnorm_impl<FloatType,1> { static FloatType call(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask) { FloatType sm=0.0; for(size_t di=0;di<n;di++) { if(mask.size() == n && mask[di]) { FloatType diff=f2[di]-f1[di]; sm+=std::abs(diff); } } return sm; } }; template<class FloatType> struct Lnorm_impl<FloatType,2> { static FloatType call(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask) { FloatType sm=0.0; for(size_t di=0;di<n;di++) { if(mask.size() == n && mask[di]) { FloatType diff=f2[di]-f1[di]; sm+=diff*diff; } } return std::sqrt(sm); } }; //premature optimization is the root of all evil but it's possible to implement this recursively and compile-time. template<class FloatType,size_t P> inline FloatType Lnorm(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask) { return Lnorm_impl<FloatType,P>::call(f1,f2,n,mask); } #endif
1,858
859
#include "public_key.hpp" extern const RsaPublicKey PublicKey = { 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xe0, 0x15, 0x69, 0x00, 0x55, 0x3c, 0x6a, 0x56, 0x35, 0x6d, 0x3c, 0x2a, 0x3d, 0xd6, 0xdc, 0x7a, 0xe2, 0x72, 0x3f, 0x87, 0xa3, 0x13, 0x26, 0x86, 0x75, 0x75, 0x79, 0x45, 0xbe, 0xc8, 0xb5, 0x57, 0xaa, 0x4a, 0x9a, 0xff, 0x3a, 0x30, 0xd7, 0xa2, 0x33, 0xa0, 0x64, 0x1e, 0xbf, 0x3b, 0x13, 0x2c, 0x01, 0x57, 0x90, 0xc1, 0x78, 0xf7, 0x6d, 0x6c, 0x41, 0x87, 0xe2, 0x53, 0x77, 0x77, 0x28, 0x27, 0xf4, 0x56, 0xf2, 0x85, 0x5f, 0x79, 0xa8, 0xc6, 0x84, 0x5e, 0x75, 0x45, 0x77, 0x47, 0x0c, 0x51, 0x3d, 0xab, 0xf4, 0xbe, 0xe4, 0xb1, 0x54, 0x8b, 0x88, 0x39, 0xe6, 0x3a, 0x03, 0x69, 0x71, 0x25, 0x5e, 0xcc, 0x6b, 0x38, 0xfa, 0xfc, 0x80, 0x15, 0xf9, 0x90, 0x4e, 0xe4, 0x52, 0x31, 0xe5, 0x26, 0xa2, 0xc7, 0x88, 0xc8, 0x30, 0x64, 0xdd, 0x86, 0x22, 0xbb, 0xe0, 0x79, 0xe1, 0x50, 0x66, 0x6d, 0x02, 0x03, 0x01, 0x00, 0x01 };
933
841
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/app_list/views/search_box_view.h" #include <algorithm> #include "grit/ui_resources.h" #include "ui/app_list/search_box_model.h" #include "ui/app_list/search_box_view_delegate.h" #include "ui/base/events/event.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/textfield/textfield.h" namespace app_list { namespace { const int kPadding = 14; const int kIconDimension = 32; const int kPreferredWidth = 360; const int kPreferredHeight = 48; const int kMenuButtonDimension = 29; const SkColor kHintTextColor = SkColorSetRGB(0xA0, 0xA0, 0xA0); } // namespace SearchBoxView::SearchBoxView(SearchBoxViewDelegate* delegate, AppListViewDelegate* view_delegate) : delegate_(delegate), model_(NULL), menu_(view_delegate), icon_view_(new views::ImageView), search_box_(new views::Textfield), contents_view_(NULL) { AddChildView(icon_view_); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); #if !defined(OS_CHROMEOS) menu_button_ = new views::MenuButton(NULL, string16(), this, false); menu_button_->set_border(NULL); menu_button_->SetIcon(*rb.GetImageSkiaNamed(IDR_APP_LIST_TOOLS_NORMAL)); menu_button_->SetHoverIcon(*rb.GetImageSkiaNamed(IDR_APP_LIST_TOOLS_HOVER)); menu_button_->SetPushedIcon(*rb.GetImageSkiaNamed( IDR_APP_LIST_TOOLS_PRESSED)); AddChildView(menu_button_); #endif search_box_->RemoveBorder(); search_box_->SetFont(rb.GetFont(ui::ResourceBundle::MediumFont)); search_box_->set_placeholder_text_color(kHintTextColor); search_box_->SetController(this); AddChildView(search_box_); } SearchBoxView::~SearchBoxView() { if (model_) model_->RemoveObserver(this); } void SearchBoxView::SetModel(SearchBoxModel* model) { if (model_ == model) return; if (model_) model_->RemoveObserver(this); model_ = model; if (model_) { model_->AddObserver(this); IconChanged(); HintTextChanged(); } } bool SearchBoxView::HasSearch() const { return !search_box_->text().empty(); } void SearchBoxView::ClearSearch() { search_box_->SetText(string16()); // Updates model and fires query changed manually because SetText() above // does not generate ContentsChanged() notification. UpdateModel(); NotifyQueryChanged(); } gfx::Size SearchBoxView::GetPreferredSize() { return gfx::Size(kPreferredWidth, kPreferredHeight); } void SearchBoxView::Layout() { gfx::Rect rect(GetContentsBounds()); if (rect.IsEmpty()) return; gfx::Rect icon_frame(rect); icon_frame.set_width(kIconDimension + 2 * kPadding); icon_view_->SetBoundsRect(icon_frame); gfx::Rect menu_button_frame(rect); #if !defined(OS_CHROMEOS) menu_button_frame.set_width(kMenuButtonDimension); menu_button_frame.set_x(rect.right() - menu_button_frame.width() - kPadding); menu_button_frame.ClampToCenteredSize(gfx::Size(menu_button_frame.width(), kMenuButtonDimension)); menu_button_->SetBoundsRect(menu_button_frame); #else menu_button_frame.set_width(0); #endif gfx::Rect edit_frame(rect); edit_frame.set_x(icon_frame.right()); edit_frame.set_width( rect.width() - icon_frame.width() - kPadding - menu_button_frame.width()); edit_frame.ClampToCenteredSize( gfx::Size(edit_frame.width(), search_box_->GetPreferredSize().height())); search_box_->SetBoundsRect(edit_frame); } bool SearchBoxView::OnMouseWheel(const ui::MouseWheelEvent& event) { if (contents_view_) return contents_view_->OnMouseWheel(event); return false; } void SearchBoxView::UpdateModel() { // Temporarily remove from observer to ignore notifications caused by us. model_->RemoveObserver(this); model_->SetText(search_box_->text()); model_->SetSelectionModel(search_box_->GetSelectionModel()); model_->AddObserver(this); } void SearchBoxView::NotifyQueryChanged() { DCHECK(delegate_); delegate_->QueryChanged(this); } void SearchBoxView::ContentsChanged(views::Textfield* sender, const string16& new_contents) { UpdateModel(); NotifyQueryChanged(); } bool SearchBoxView::HandleKeyEvent(views::Textfield* sender, const ui::KeyEvent& key_event) { bool handled = false; if (contents_view_ && contents_view_->visible()) handled = contents_view_->OnKeyPressed(key_event); return handled; } void SearchBoxView::OnMenuButtonClicked(View* source, const gfx::Point& point) { menu_.RunMenuAt(menu_button_, menu_button_->GetBoundsInScreen().bottom_right()); } void SearchBoxView::IconChanged() { icon_view_->SetImage(model_->icon()); } void SearchBoxView::HintTextChanged() { search_box_->set_placeholder_text(model_->hint_text()); } void SearchBoxView::SelectionModelChanged() { search_box_->SelectSelectionModel(model_->selection_model()); } void SearchBoxView::TextChanged() { search_box_->SetText(model_->text()); } } // namespace app_list
5,269
1,781
#include <cmath> #include <cstdlib> #include <ctime> #include <iomanip> #include <iostream> using namespace std; #include "r8lib/r8lib.hpp" #pragma once //void daxpy ( int n, double da, double dx[], int incx, double dy[], int incy ); //double ddot ( int n, double dx[], int incx, double dy[], int incy ); //double dnrm2 ( int n, double x[], int incx ); //void drot ( int n, double x[], int incx, double y[], int incy, double c, double s ); //void drotg ( double *sa, double *sb, double *c, double *s ); //void dscal ( int n, double sa, double x[], int incx ); int dsvdc ( double a[], int lda, int m, int n, double s[], double e[], double u[], int ldu, double v[], int ldv, double work[], int job ); //void dswap ( int n, double x[], int incx, double y[], int incy ); void phi1 ( int n, double r[], double r0, double v[] ); void phi2 ( int n, double r[], double r0, double v[] ); void phi3 ( int n, double r[], double r0, double v[] ); void phi4 ( int n, double r[], double r0, double v[] ); double *r8mat_solve_svd ( int m, int n, double a[], double b[] ); double *rbf_interp ( int m, int nd, double xd[], double r0, void (*phi) ( int n, double r[], double r0, double v[] ), double w[], int ni, double xi[] ); double *rbf_weight ( int m, int nd, double xd[], double r0, void (*phi) ( int n, double r[], double r0, double v[] ), double fd[] ); #include <mkl.h> #define CBLAS #ifdef CBLAS #define BLASFunc(name) cblas_ ## name #else #define BLASFunc(name) name #endif //// //// Purpose: //// //// DAXPY computes constant times a vector plus a vector. //// //// Discussion: //// //// This routine uses unrolled loops for increments equal to one. //// //// Licensing: //// //// This code is distributed under the GNU LGPL license. //// //// Modified: //// //// 02 May 2005 //// //// Author: //// //// Original FORTRAN77 version by Charles Lawson, Richard Hanson, //// David Kincaid, Fred Krogh. //// C++ version by John Burkardt. //// //// Reference: //// //// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart, //// LINPACK User's Guide, //// SIAM, 1979, //// ISBN13: 978-0-898711-72-1, //// LC: QA214.L56. //// //// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh, //// Basic Linear Algebra Subprograms for Fortran Usage, //// Algorithm 539, //// ACM Transactions on Mathematical Software, //// Volume 5, Number 3, September 1979, pages 308-323. //// //// Parameters: //// //// Input, int N, the number of elements in DX and DY. //// //// Input, double DA, the multiplier of DX. //// //// Input, double DX[*], the first vector. //// //// Input, int INCX, the increment between successive entries of DX. //// //// Input/output, double DY[*], the second vector. //// On output, DY[*] has been replaced by DY[*] + DA * DX[*]. //// //// Input, int INCY, the increment between successive entries of DY. //// //void daxpy(int n, double da, double dx[], int incx, double dy[], int incy) //{ // int i; // int ix; // int iy; // int m; // // if (n <= 0) // { // return; // } // // if (da == 0.0) // { // return; // } // // // // Code for unequal increments or equal increments // // not equal to 1. // // // if (incx != 1 || incy != 1) // { // if (0 <= incx) // { // ix = 0; // } // else // { // ix = (-n + 1) * incx; // } // // if (0 <= incy) // { // iy = 0; // } // else // { // iy = (-n + 1) * incy; // } // // for (i = 0; i < n; ++i) // { // dy[iy] = dy[iy] + da * dx[ix]; // ix = ix + incx; // iy = iy + incy; // } // } // // // // Code for both increments equal to 1. // // // else // { // m = n % 4; // // for (i = 0; i < m; ++i) // { // dy[i] = dy[i] + da * dx[i]; // } // // for (i = m; i < n; i = i + 4) // { // dy[i] = dy[i] + da * dx[i]; // dy[i + 1] = dy[i + 1] + da * dx[i + 1]; // dy[i + 2] = dy[i + 2] + da * dx[i + 2]; // dy[i + 3] = dy[i + 3] + da * dx[i + 3]; // } // } // // return; //} // //// //// Purpose: //// //// DDOT forms the dot product of two vectors. //// //// Discussion: //// //// This routine uses unrolled loops for increments equal to one. //// //// Licensing: //// //// This code is distributed under the GNU LGPL license. //// //// Modified: //// //// 02 May 2005 //// //// Author: //// //// Original FORTRAN77 version by Charles Lawson, Richard Hanson, //// David Kincaid, Fred Krogh. //// C++ version by John Burkardt. //// //// Reference: //// //// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart, //// LINPACK User's Guide, //// SIAM, 1979, //// ISBN13: 978-0-898711-72-1, //// LC: QA214.L56. //// //// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh, //// Basic Linear Algebra Subprograms for Fortran Usage, //// Algorithm 539, //// ACM Transactions on Mathematical Software, //// Volume 5, Number 3, September 1979, pages 308-323. //// //// Parameters: //// //// Input, int N, the number of entries in the vectors. //// //// Input, double DX[*], the first vector. //// //// Input, int INCX, the increment between successive entries in DX. //// //// Input, double DY[*], the second vector. //// //// Input, int INCY, the increment between successive entries in DY. //// //// Output, double DDOT, the sum of the product of the corresponding //// entries of DX and DY. //// //double ddot(int n, double dx[], int incx, double dy[], int incy) //{ // double dtemp; // int i; // int ix; // int iy; // int m; // // dtemp = 0.0; // // if (n <= 0) // { // return dtemp; // } // // // // Code for unequal increments or equal increments // // not equal to 1. // // // if (incx != 1 || incy != 1) // { // if (0 <= incx) // { // ix = 0; // } // else // { // ix = (-n + 1) * incx; // } // // if (0 <= incy) // { // iy = 0; // } // else // { // iy = (-n + 1) * incy; // } // // for (i = 0; i < n; ++i) // { // dtemp = dtemp + dx[ix] * dy[iy]; // ix = ix + incx; // iy = iy + incy; // } // } // // // // Code for both increments equal to 1. // // // else // { // m = n % 5; // // for (i = 0; i < m; ++i) // { // dtemp = dtemp + dx[i] * dy[i]; // } // // for (i = m; i < n; i = i + 5) // { // dtemp = dtemp + dx[i] * dy[i] + dx[i + 1] * dy[i + 1] + // dx[i + 2] * dy[i + 2] + dx[i + 3] * dy[i + 3] + // dx[i + 4] * dy[i + 4]; // } // } // // return dtemp; //} // //// //// Purpose: //// //// DNRM2 returns the euclidean norm of a vector. //// //// Discussion: //// //// DNRM2 ( X ) = sqrt ( X' * X ) //// //// Licensing: //// //// This code is distributed under the GNU LGPL license. //// //// Modified: //// //// 02 May 2005 //// //// Author: //// //// Original FORTRAN77 version by Charles Lawson, Richard Hanson, //// David Kincaid, Fred Krogh. //// C++ version by John Burkardt. //// //// Reference: //// //// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart, //// LINPACK User's Guide, //// SIAM, 1979, //// ISBN13: 978-0-898711-72-1, //// LC: QA214.L56. //// //// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh, //// Basic Linear Algebra Subprograms for Fortran Usage, //// Algorithm 539, //// ACM Transactions on Mathematical Software, //// Volume 5, Number 3, September 1979, pages 308-323. //// //// Parameters: //// //// Input, int N, the number of entries in the vector. //// //// Input, double X[*], the vector whose norm is to be computed. //// //// Input, int INCX, the increment between successive entries of X. //// //// Output, double DNRM2, the Euclidean norm of X. //// //double dnrm2(int n, double x[], int incx) //{ // double absxi; // int i; // int ix; // double norm; // double scale; // double ssq; // double value; // // if (n < 1 || incx < 1) // { // norm = 0.0; // } // else if (n == 1) // { // norm = r8_abs(x[0]); // } // else // { // scale = 0.0; // ssq = 1.0; // ix = 0; // // for (i = 0; i < n; ++i) // { // if (x[ix] != 0.0) // { // absxi = r8_abs(x[ix]); // if (scale < absxi) // { // ssq = 1.0 + ssq * (scale / absxi) * (scale / absxi); // scale = absxi; // } // else // { // ssq = ssq + (absxi / scale) * (absxi / scale); // } // } // ix = ix + incx; // } // // norm = scale * sqrt(ssq); // } // // return norm; //} // //// //// Purpose: //// //// DROT applies a plane rotation. //// //// Licensing: //// //// This code is distributed under the GNU LGPL license. //// //// Modified: //// //// 02 May 2005 //// //// Author: //// //// Original FORTRAN77 version by Charles Lawson, Richard Hanson, //// David Kincaid, Fred Krogh. //// C++ version by John Burkardt. //// //// Reference: //// //// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart, //// LINPACK User's Guide, //// SIAM, 1979, //// ISBN13: 978-0-898711-72-1, //// LC: QA214.L56. //// //// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh, //// Basic Linear Algebra Subprograms for Fortran Usage, //// Algorithm 539, //// ACM Transactions on Mathematical Software, //// Volume 5, Number 3, September 1979, pages 308-323. //// //// Parameters: //// //// Input, int N, the number of entries in the vectors. //// //// Input/output, double X[*], one of the vectors to be rotated. //// //// Input, int INCX, the increment between successive entries of X. //// //// Input/output, double Y[*], one of the vectors to be rotated. //// //// Input, int INCY, the increment between successive elements of Y. //// //// Input, double C, S, parameters (presumably the cosine and //// sine of some angle) that define a plane rotation. //// //void drot(int n, double x[], int incx, double y[], int incy, double c, double s) //{ // int i; // int ix; // int iy; // double stemp; // // if (n <= 0) // { // } // else if (incx == 1 && incy == 1) // { // for (i = 0; i < n; ++i) // { // stemp = c * x[i] + s * y[i]; // y[i] = c * y[i] - s * x[i]; // x[i] = stemp; // } // } // else // { // if (0 <= incx) // { // ix = 0; // } // else // { // ix = (-n + 1) * incx; // } // // if (0 <= incy) // { // iy = 0; // } // else // { // iy = (-n + 1) * incy; // } // // for (i = 0; i < n; ++i) // { // stemp = c * x[ix] + s * y[iy]; // y[iy] = c * y[iy] - s * x[ix]; // x[ix] = stemp; // ix = ix + incx; // iy = iy + incy; // } // } // // return; //} // //// //// Purpose: //// //// DROTG constructs a Givens plane rotation. //// //// Discussion: //// //// Given values A and B, this routine computes //// //// SIGMA = sign ( A ) if abs ( A ) > abs ( B ) //// = sign ( B ) if abs ( A ) <= abs ( B ); //// //// R = SIGMA * ( A * A + B * B ); //// //// C = A / R if R is not 0 //// = 1 if R is 0; //// //// S = B / R if R is not 0, //// 0 if R is 0. //// //// The computed numbers then satisfy the equation //// //// ( C S ) ( A ) = ( R ) //// ( -S C ) ( B ) = ( 0 ) //// //// The routine also computes //// //// Z = S if abs ( A ) > abs ( B ), //// = 1 / C if abs ( A ) <= abs ( B ) and C is not 0, //// = 1 if C is 0. //// //// The single value Z encodes C and S, and hence the rotation: //// //// If Z = 1, set C = 0 and S = 1; //// If abs ( Z ) < 1, set C = sqrt ( 1 - Z * Z ) and S = Z; //// if abs ( Z ) > 1, set C = 1/ Z and S = sqrt ( 1 - C * C ); //// //// Licensing: //// //// This code is distributed under the GNU LGPL license. //// //// Modified: //// //// 15 May 2006 //// //// Author: //// //// Original FORTRAN77 version by Charles Lawson, Richard Hanson, //// David Kincaid, Fred Krogh. //// C++ version by John Burkardt. //// //// Reference: //// //// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart, //// LINPACK User's Guide, //// SIAM, 1979, //// ISBN13: 978-0-898711-72-1, //// LC: QA214.L56. //// //// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh, //// Basic Linear Algebra Subprograms for Fortran Usage, //// Algorithm 539, //// ACM Transactions on Mathematical Software, //// Volume 5, Number 3, September 1979, pages 308-323. //// //// Parameters: //// //// Input/output, double *SA, *SB, On input, SA and SB are the values //// A and B. On output, SA is overwritten with R, and SB is //// overwritten with Z. //// //// Output, double *C, *S, the cosine and sine of the Givens rotation. //// //void drotg(double *sa, double *sb, double *c, double *s) //{ // double r; // double roe; // double scale; // double z; // // if (r8_abs(*sb) < r8_abs(*sa)) // { // roe = *sa; // } // else // { // roe = *sb; // } // // scale = r8_abs(*sa) + r8_abs(*sb); // // if (scale == 0.0) // { // *c = 1.0; // *s = 0.0; // r = 0.0; // } // else // { // r = scale * // sqrt((*sa / scale) * (*sa / scale) + (*sb / scale) * (*sb / scale)); // r = r8_sign(roe) * r; // *c = *sa / r; // *s = *sb / r; // } // // if (0.0 < r8_abs(*c) && r8_abs(*c) <= *s) // { // z = 1.0 / *c; // } // else // { // z = *s; // } // // *sa = r; // *sb = z; // // return; //} // //// //// Purpose: //// //// DSCAL scales a vector by a constant. //// //// Licensing: //// //// This code is distributed under the GNU LGPL license. //// //// Modified: //// //// 02 May 2005 //// //// Author: //// //// Original FORTRAN77 version by Charles Lawson, Richard Hanson, //// David Kincaid, Fred Krogh. //// C++ version by John Burkardt. //// //// Reference: //// //// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart, //// LINPACK User's Guide, //// SIAM, 1979, //// ISBN13: 978-0-898711-72-1, //// LC: QA214.L56. //// //// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh, //// Basic Linear Algebra Subprograms for Fortran Usage, //// Algorithm 539, //// ACM Transactions on Mathematical Software, //// Volume 5, Number 3, September 1979, pages 308-323. //// //// Parameters: //// //// Input, int N, the number of entries in the vector. //// //// Input, double SA, the multiplier. //// //// Input/output, double X[*], the vector to be scaled. //// //// Input, int INCX, the increment between successive entries of X. //// //void dscal(int n, double sa, double x[], int incx) //{ // int i; // int ix; // int m; // // if (n <= 0) // { // } // else if (incx == 1) // { // m = n % 5; // // for (i = 0; i < m; ++i) // { // x[i] = sa * x[i]; // } // // for (i = m; i < n; i = i + 5) // { // x[i] = sa * x[i]; // x[i + 1] = sa * x[i + 1]; // x[i + 2] = sa * x[i + 2]; // x[i + 3] = sa * x[i + 3]; // x[i + 4] = sa * x[i + 4]; // } // } // else // { // if (0 <= incx) // { // ix = 0; // } // else // { // ix = (-n + 1) * incx; // } // // for (i = 0; i < n; ++i) // { // x[ix] = sa * x[ix]; // ix = ix + incx; // } // } // // return; //} // // Purpose: // // DSVDC computes the singular value decomposition of a real rectangular // matrix. // // Discussion: // // This routine reduces an M by N matrix A to diagonal form by orthogonal // transformations U and V. The diagonal elements S(I) are the singular // values of A. The columns of U are the corresponding left singular // vectors, and the columns of V the right singular vectors. // // The form of the singular value decomposition is then // // A(MxN) = U(MxM) * S(MxN) * V(NxN)' // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 03 May 2007 // // Author: // // Original FORTRAN77 version by Jack Dongarra, Cleve Moler, Jim Bunch, // Pete Stewart. // C++ version by John Burkardt. // // Reference: // // Jack Dongarra, Cleve Moler, Jim Bunch, Pete Stewart, // LINPACK User's Guide, // SIAM, (Society for Industrial and Applied Mathematics), // 3600 University City Science Center, // Philadelphia, PA, 19104-2688. // ISBN 0-89871-172-X // // Parameters: // // Input/output, double A[LDA*N]. On input, the M by N matrix whose // singular value decomposition is to be computed. On output, the matrix // has been destroyed. Depending on the user's requests, the matrix may // contain other useful information. // // Input, int LDA, the leading dimension of the array A. // LDA must be at least M. // // Input, int M, the number of rows of the matrix. // // Input, int N, the number of columns of the matrix A. // // Output, double S[MM], where MM = min(M+1,N). The first // min(M,N) entries of S contain the singular values of A arranged in // descending order of magnitude. // // Output, double E[MM], where MM = min(M+1,N), ordinarily contains zeros. // However see the discussion of INFO for exceptions. // // Output, double U[LDU*K]. If JOBA = 1 then K = M; // if 2 <= JOBA, then K = min(M,N). U contains the M by M matrix of left // singular vectors. U is not referenced if JOBA = 0. If M <= N or if JOBA // = 2, then U may be identified with A in the subroutine call. // // Input, int LDU, the leading dimension of the array U. // LDU must be at least M. // // Output, double V[LDV*N], the N by N matrix of right singular vectors. // V is not referenced if JOB is 0. If N <= M, then V may be identified // with A in the subroutine call. // // Input, int LDV, the leading dimension of the array V. // LDV must be at least N. // // Workspace, double WORK[M]. // // Input, int JOB, controls the computation of the singular // vectors. It has the decimal expansion AB with the following meaning: // A = 0, do not compute the left singular vectors. // A = 1, return the M left singular vectors in U. // A >= 2, return the first min(M,N) singular vectors in U. // B = 0, do not compute the right singular vectors. // B = 1, return the right singular vectors in V. // // Output, int *DSVDC, status indicator INFO. // The singular values (and their corresponding singular vectors) // S(*INFO+1), S(*INFO+2),...,S(MN) are correct. Here MN = min ( M, N ). // Thus if *INFO is 0, all the singular values and their vectors are // correct. In any event, the matrix B = U' * A * V is the bidiagonal // matrix with the elements of S on its diagonal and the elements of E on // its superdiagonal. Thus the singular values of A and B are the same. // int dsvdc(double a[], int lda, int m, int n, double s[], double e[], double u[], int ldu, double v[], int ldv, double work[], int job) { double b; double c; double cs; double el; double emm1; double f; double g; int i; int info; int iter; int j; int jobu; int k; int kase; int kk; int l; int ll; int lls; int ls; int lu; int maxit = 30; int mm; int mm1; int mn; int mp1; int nct; int nctp1; int ncu; int nrt; int nrtp1; double scale; double shift; double sl; double sm; double smm1; double sn; double t; double t1; double test; bool wantu; bool wantv; double ztest; // // Determine what is to be computed. // info = 0; wantu = false; wantv = false; jobu = (job % 100) / 10; if (1 < jobu) { ncu = i4_min(m, n); } else { ncu = m; } if (jobu != 0) { wantu = true; } if ((job % 10) != 0) { wantv = true; } // // Reduce A to bidiagonal form, storing the diagonal elements // in S and the super-diagonal elements in E. // nct = i4_min(m - 1, n); nrt = i4_max(0, i4_min(m, n - 2)); lu = i4_max(nct, nrt); for (l = 1; l <= lu; l++) { // // Compute the transformation for the L-th column and // place the L-th diagonal in S(L). // if (l <= nct) { s[l - 1] = BLASFunc(dnrm2)(m - l + 1, a + l - 1 + (l - 1) * lda, 1); if (s[l - 1] != 0.0) { if (a[l - 1 + (l - 1) * lda] != 0.0) { s[l - 1] = r8_sign(a[l - 1 + (l - 1) * lda]) * r8_abs(s[l - 1]); } BLASFunc(dscal)(m - l + 1, 1.0 / s[l - 1], a + l - 1 + (l - 1) * lda, 1); a[l - 1 + (l - 1) * lda] = 1.0 + a[l - 1 + (l - 1) * lda]; } s[l - 1] = -s[l - 1]; } for (j = l + 1; j <= n; ++j) { // // Apply the transformation. // if (l <= nct && s[l - 1] != 0.0) { t = -BLASFunc(ddot)(m - l + 1, a + l - 1 + (l - 1) * lda, 1, a + l - 1 + (j - 1) * lda, 1) / a[l - 1 + (l - 1) * lda]; BLASFunc(daxpy)(m - l + 1, t, a + l - 1 + (l - 1) * lda, 1, a + l - 1 + (j - 1) * lda, 1); } // // Place the L-th row of A into E for the // subsequent calculation of the row transformation. // e[j - 1] = a[l - 1 + (j - 1) * lda]; } // // Place the transformation in U for subsequent back multiplication. // if (wantu && l <= nct) { for (i = l; i <= m; ++i) { u[i - 1 + (l - 1) * ldu] = a[i - 1 + (l - 1) * lda]; } } if (l <= nrt) { // // Compute the L-th row transformation and place the // L-th superdiagonal in E(L). // e[l - 1] = BLASFunc(dnrm2)(n - l, e + l, 1); if (e[l - 1] != 0.0) { if (e[l] != 0.0) { e[l - 1] = r8_sign(e[l]) * r8_abs(e[l - 1]); } BLASFunc(dscal)(n - l, 1.0 / e[l - 1], e + l, 1); e[l] = 1.0 + e[l]; } e[l - 1] = -e[l - 1]; // // Apply the transformation. // if (l + 1 <= m && e[l - 1] != 0.0) { for (j = l + 1; j <= m; ++j) { work[j - 1] = 0.0; } for (j = l + 1; j <= n; ++j) { BLASFunc(daxpy)(m - l, e[j - 1], a + l + (j - 1) * lda, 1, work + l, 1); } for (j = l + 1; j <= n; ++j) { BLASFunc(daxpy)(m - l, -e[j - 1] / e[l], work + l, 1, a + l + (j - 1) * lda, 1); } } // // Place the transformation in V for subsequent back multiplication. // if (wantv) { for (j = l + 1; j <= n; ++j) { v[j - 1 + (l - 1) * ldv] = e[j - 1]; } } } } // // Set up the final bidiagonal matrix of order MN. // mn = i4_min(m + 1, n); nctp1 = nct + 1; nrtp1 = nrt + 1; if (nct < n) { s[nctp1 - 1] = a[nctp1 - 1 + (nctp1 - 1) * lda]; } if (m < mn) { s[mn - 1] = 0.0; } if (nrtp1 < mn) { e[nrtp1 - 1] = a[nrtp1 - 1 + (mn - 1) * lda]; } e[mn - 1] = 0.0; // // If required, generate U. // if (wantu) { for (i = 1; i <= m; ++i) { for (j = nctp1; j <= ncu; ++j) { u[(i - 1) + (j - 1) * ldu] = 0.0; } } for (j = nctp1; j <= ncu; ++j) { u[j - 1 + (j - 1) * ldu] = 1.0; } for (ll = 1; ll <= nct; ll++) { l = nct - ll + 1; if (s[l - 1] != 0.0) { for (j = l + 1; j <= ncu; ++j) { t = -BLASFunc(ddot)(m - l + 1, u + (l - 1) + (l - 1) * ldu, 1, u + (l - 1) + (j - 1) * ldu, 1) / u[l - 1 + (l - 1) * ldu]; BLASFunc(daxpy)(m - l + 1, t, u + (l - 1) + (l - 1) * ldu, 1, u + (l - 1) + (j - 1) * ldu, 1); } BLASFunc(dscal)(m - l + 1, -1.0, u + (l - 1) + (l - 1) * ldu, 1); u[l - 1 + (l - 1) * ldu] = 1.0 + u[l - 1 + (l - 1) * ldu]; for (i = 1; i <= l - 1; ++i) { u[i - 1 + (l - 1) * ldu] = 0.0; } } else { for (i = 1; i <= m; ++i) { u[i - 1 + (l - 1) * ldu] = 0.0; } u[l - 1 + (l - 1) * ldu] = 1.0; } } } // // If it is required, generate V. // if (wantv) { for (ll = 1; ll <= n; ll++) { l = n - ll + 1; if (l <= nrt && e[l - 1] != 0.0) { for (j = l + 1; j <= n; ++j) { t = -BLASFunc(ddot)(n - l, v + l + (l - 1) * ldv, 1, v + l + (j - 1) * ldv, 1) / v[l + (l - 1) * ldv]; BLASFunc(daxpy)(n - l, t, v + l + (l - 1) * ldv, 1, v + l + (j - 1) * ldv, 1); } } for (i = 1; i <= n; ++i) { v[i - 1 + (l - 1) * ldv] = 0.0; } v[l - 1 + (l - 1) * ldv] = 1.0; } } // // Main iteration loop for the singular values. // mm = mn; iter = 0; while (0 < mn) { // // If too many iterations have been performed, set flag and return. // if (maxit <= iter) { info = mn; return info; } // // This section of the program inspects for // negligible elements in the S and E arrays. // // On completion the variables KASE and L are set as follows: // // KASE = 1 if S(MN) and E(L-1) are negligible and L < MN // KASE = 2 if S(L) is negligible and L < MN // KASE = 3 if E(L-1) is negligible, L < MN, and // S(L), ..., S(MN) are not negligible (QR step). // KASE = 4 if E(MN-1) is negligible (convergence). // for (ll = 1; ll <= mn; ll++) { l = mn - ll; if (l == 0) { break; } test = r8_abs(s[l - 1]) + r8_abs(s[l]); ztest = test + r8_abs(e[l - 1]); if (ztest == test) { e[l - 1] = 0.0; break; } } if (l == mn - 1) { kase = 4; } else { mp1 = mn + 1; for (lls = l + 1; lls <= mn + 1; lls++) { ls = mn - lls + l + 1; if (ls == l) { break; } test = 0.0; if (ls != mn) { test = test + r8_abs(e[ls - 1]); } if (ls != l + 1) { test = test + r8_abs(e[ls - 2]); } ztest = test + r8_abs(s[ls - 1]); if (ztest == test) { s[ls - 1] = 0.0; break; } } if (ls == l) { kase = 3; } else if (ls == mn) { kase = 1; } else { kase = 2; l = ls; } } l = l + 1; // // Deflate negligible S(MN). // if (kase == 1) { mm1 = mn - 1; f = e[mn - 2]; e[mn - 2] = 0.0; for (kk = 1; kk <= mm1; kk++) { k = mm1 - kk + l; t1 = s[k - 1]; BLASFunc(drotg)(&t1, &f, &cs, &sn); s[k - 1] = t1; if (k != l) { f = -sn * e[k - 2]; e[k - 2] = cs * e[k - 2]; } if (wantv) { BLASFunc(drot)(n, v + 0 + (k - 1) * ldv, 1, v + 0 + (mn - 1) * ldv, 1, cs, sn); } } } // // Split at negligible S(L). // else if (kase == 2) { f = e[l - 2]; e[l - 2] = 0.0; for (k = l; k <= mn; k++) { t1 = s[k - 1]; BLASFunc(drotg)(&t1, &f, &cs, &sn); s[k - 1] = t1; f = -sn * e[k - 1]; e[k - 1] = cs * e[k - 1]; if (wantu) { BLASFunc(drot)(m, u + 0 + (k - 1) * ldu, 1, u + 0 + (l - 2) * ldu, 1, cs, sn); } } } // // Perform one QR step. // else if (kase == 3) { // // Calculate the shift. // scale = r8_max(r8_abs(s[mn - 1]), r8_max(r8_abs(s[mn - 2]), r8_max(r8_abs(e[mn - 2]), r8_max(r8_abs(s[l - 1]), r8_abs(e[l - 1]))))); sm = s[mn - 1] / scale; smm1 = s[mn - 2] / scale; emm1 = e[mn - 2] / scale; sl = s[l - 1] / scale; el = e[l - 1] / scale; b = ((smm1 + sm) * (smm1 - sm) + emm1 * emm1) / 2.0; c = (sm * emm1) * (sm * emm1); shift = 0.0; if (b != 0.0 || c != 0.0) { shift = sqrt(b * b + c); if (b < 0.0) { shift = -shift; } shift = c / (b + shift); } f = (sl + sm) * (sl - sm) - shift; g = sl * el; // // Chase zeros. // mm1 = mn - 1; for (k = l; k <= mm1; k++) { BLASFunc(drotg)(&f, &g, &cs, &sn); if (k != l) { e[k - 2] = f; } f = cs * s[k - 1] + sn * e[k - 1]; e[k - 1] = cs * e[k - 1] - sn * s[k - 1]; g = sn * s[k]; s[k] = cs * s[k]; if (wantv) { BLASFunc(drot)(n, v + 0 + (k - 1) * ldv, 1, v + 0 + k * ldv, 1, cs, sn); } BLASFunc(drotg)(&f, &g, &cs, &sn); s[k - 1] = f; f = cs * e[k - 1] + sn * s[k]; s[k] = -sn * e[k - 1] + cs * s[k]; g = sn * e[k]; e[k] = cs * e[k]; if (wantu && k < m) { BLASFunc(drot)(m, u + 0 + (k - 1) * ldu, 1, u + 0 + k * ldu, 1, cs, sn); } } e[mn - 2] = f; iter = iter + 1; } // // Convergence. // else if (kase == 4) { // // Make the singular value nonnegative. // if (s[l - 1] < 0.0) { s[l - 1] = -s[l - 1]; if (wantv) { BLASFunc(dscal)(n, -1.0, v + 0 + (l - 1) * ldv, 1); } } // // Order the singular value. // for (;;) { if (l == mm) { break; } if (s[l] <= s[l - 1]) { break; } t = s[l - 1]; s[l - 1] = s[l]; s[l] = t; if (wantv && l < n) { BLASFunc(dswap)(n, v + 0 + (l - 1) * ldv, 1, v + 0 + l * ldv, 1); } if (wantu && l < m) { BLASFunc(dswap)(m, u + 0 + (l - 1) * ldu, 1, u + 0 + l * ldu, 1); } l = l + 1; } iter = 0; mn = mn - 1; } } return info; } //// //// Purpose: //// //// DSWAP interchanges two vectors. //// //// Licensing: //// //// This code is distributed under the GNU LGPL license. //// //// Modified: //// //// 02 May 2005 //// //// Author: //// //// Original FORTRAN77 version by Charles Lawson, Richard Hanson, //// David Kincaid, Fred Krogh. //// C++ version by John Burkardt. //// //// Reference: //// //// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart, //// LINPACK User's Guide, //// SIAM, 1979, //// ISBN13: 978-0-898711-72-1, //// LC: QA214.L56. //// //// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh, //// Basic Linear Algebra Subprograms for Fortran Usage, //// Algorithm 539, //// ACM Transactions on Mathematical Software, //// Volume 5, Number 3, September 1979, pages 308-323. //// //// Parameters: //// //// Input, int N, the number of entries in the vectors. //// //// Input/output, double X[*], one of the vectors to swap. //// //// Input, int INCX, the increment between successive entries of X. //// //// Input/output, double Y[*], one of the vectors to swap. //// //// Input, int INCY, the increment between successive elements of Y. //// //void dswap(int n, double x[], int incx, double y[], int incy) //{ // int i; // int ix; // int iy; // int m; // double temp; // // if (n <= 0) // { // } // else if (incx == 1 && incy == 1) // { // m = n % 3; // // for (i = 0; i < m; ++i) // { // temp = x[i]; // x[i] = y[i]; // y[i] = temp; // } // // for (i = m; i < n; i = i + 3) // { // temp = x[i]; // x[i] = y[i]; // y[i] = temp; // // temp = x[i + 1]; // x[i + 1] = y[i + 1]; // y[i + 1] = temp; // // temp = x[i + 2]; // x[i + 2] = y[i + 2]; // y[i + 2] = temp; // } // } // else // { // if (0 <= incx) // { // ix = 0; // } // else // { // ix = (-n + 1) * incx; // } // // if (0 <= incy) // { // iy = 0; // } // else // { // iy = (-n + 1) * incy; // } // // for (i = 0; i < n; ++i) // { // temp = x[ix]; // x[ix] = y[iy]; // y[iy] = temp; // ix = ix + incx; // iy = iy + incy; // } // } // // return; //} // // Purpose: // // PHI1 evaluates the multiquadric radial basis function. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 30 June 2012 // // Author: // // John Burkardt // // Reference: // // William Press, Brian Flannery, Saul Teukolsky, William Vetterling, // Numerical Recipes in FORTRAN: The Art of Scientific Computing, // Third Edition, // Cambridge University Press, 2007, // ISBN13: 978-0-521-88068-8, // LC: QA297.N866. // // Parameters: // // Input, int N, the number of points. // // Input, double R[N], the radial separation. // 0 < R. // // Input, double R0, a scale factor. // // Output, double V[N], the value of the radial basis function. // void phi1(int n, double r[], double r0, double v[]) { int i; for (i = 0; i < n; ++i) { v[i] = sqrt(r[i] * r[i] + r0 * r0); } return; } // // Purpose: // // PHI2 evaluates the inverse multiquadric radial basis function. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 30 June 2012 // // Author: // // John Burkardt // // Reference: // // William Press, Brian Flannery, Saul Teukolsky, William Vetterling, // Numerical Recipes in FORTRAN: The Art of Scientific Computing, // Third Edition, // Cambridge University Press, 2007, // ISBN13: 978-0-521-88068-8, // LC: QA297.N866. // // Parameters: // // Input, int N, the number of points. // // Input, double R[N], the radial separation. // 0 < R. // // Input, double R0, a scale factor. // // Output, double V[N], the value of the radial basis function. // void phi2(int n, double r[], double r0, double v[]) { int i; for (i = 0; i < n; ++i) { v[i] = 1.0 / sqrt(r[i] * r[i] + r0 * r0); } return; } // // Purpose: // // PHI3 evaluates the thin-plate spline radial basis function. // // Discussion: // // Note that PHI3(R,R0) is negative if R < R0. Thus, for this basis // function, it may be desirable to choose a value of R0 smaller than any // possible R. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 30 June 2012 // // Author: // // John Burkardt // // Reference: // // William Press, Brian Flannery, Saul Teukolsky, William Vetterling, // Numerical Recipes in FORTRAN: The Art of Scientific Computing, // Third Edition, // Cambridge University Press, 2007, // ISBN13: 978-0-521-88068-8, // LC: QA297.N866. // // Parameters: // // Input, int N, the number of points. // // Input, double R[N], the radial separation. // 0 < R. // // Input, double R0, a scale factor. // // Output, double V[N], the value of the radial basis function. // void phi3(int n, double r[], double r0, double v[]) { int i; for (i = 0; i < n; ++i) { if (r[i] <= 0.0) { v[i] = 0.0; } else { v[i] = r[i] * r[i] * log(r[i] / r0); } } return; } // // Purpose: // // PHI4 evaluates the gaussian radial basis function. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 30 June 2012 // // Author: // // John Burkardt // // Reference: // // William Press, Brian Flannery, Saul Teukolsky, William Vetterling, // Numerical Recipes in FORTRAN: The Art of Scientific Computing, // Third Edition, // Cambridge University Press, 2007, // ISBN13: 978-0-521-88068-8, // LC: QA297.N866. // // Parameters: // // Input, int N, the number of points. // // Input, double R[N], the radial separation. // 0 < R. // // Input, double R0, a scale factor. // // Output, double V[N], the value of the radial basis function. // void phi4(int n, double r[], double r0, double v[]) { int i; for (i = 0; i < n; ++i) { v[i] = exp(-0.5 * r[i] * r[i] / r0 / r0); } return; } // // Purpose: // // R8MAT_SOLVE_SVD solves a linear system A*x=b using the SVD. // // Discussion: // // When the system is determined, the solution is the solution in the // ordinary sense, and A*x = b. // // When the system is overdetermined, the solution minimizes the // L2 norm of the residual ||A*x-b||. // // When the system is underdetermined, ||A*x-b|| should be zero, and // the solution is the solution of minimum L2 norm, ||x||. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 30 June 2012 // // Author: // // John Burkardt // // Parameters: // // Input, int M, N, the number of rows and columns // in the matrix A. // // Input, double A[M,*N], the matrix. // // Input, double B[M], the right hand side. // // Output, double R8MAT_SOLVE_SVD[N], the solution. // double *r8mat_solve_svd(int m, int n, double a[], double b[]) { double *a_copy; double *a_pseudo; double *e; int i; int info; int j; int k; int l; int lda; int ldu; int ldv; int job; int lwork; double *s; double *sp; double *sdiag; double *u; double *v; double *work; double *x; // // Compute the SVD decomposition. // a_copy = r8mat_copy_new(m, n, a); lda = m; sdiag = new double[i4_max(m + 1, n)]; e = new double[i4_max(m + 1, n)]; u = new double[m * m]; ldu = m; v = new double[n * n]; ldv = n; work = new double[m]; job = 11; //void dgesvd(const char* jobu, const char* jobvt, const MKL_INT* m, // const MKL_INT* n, double* a, const MKL_INT* lda, double* s, // double* u, const MKL_INT* ldu, double* vt, const MKL_INT* ldvt, // double* work, const MKL_INT* lwork, MKL_INT* info); info = dsvdc(a_copy, lda, m, n, sdiag, e, u, ldu, v, ldv, work, job); if (info != 0) { cerr << std::endl; cerr << "R8MAT_SOLVE_SVD - Fatal error!\n"; cerr << " The SVD could not be calculated.\n"; cerr << " LINPACK routine DSVDC returned a nonzero\n"; cerr << " value of the error flag, INFO = " << info << std::endl; exit(1); } s = new double[m * n]; for (j = 0; j < n; ++j) { for (i = 0; i < m; ++i) { s[i + j * m] = 0.0; } } for (i = 0; i < i4_min(m, n); ++i) { s[i + i * m] = sdiag[i]; } // // Compute the pseudo inverse. // sp = new double[n * m]; for (j = 0; j < m; ++j) { for (i = 0; i < n; ++i) { sp[i + j * m] = 0.0; } } for (i = 0; i < i4_min(m, n); ++i) { if (s[i + i * m] != 0.0) { sp[i + i * n] = 1.0 / s[i + i * m]; } } a_pseudo = new double[n * m]; for (j = 0; j < m; ++j) { for (i = 0; i < n; ++i) { a_pseudo[i + j * n] = 0.0; for (k = 0; k < n; k++) { for (l = 0; l < m; l++) { a_pseudo[i + j * n] = a_pseudo[i + j * n] + v[i + k * n] * sp[k + l * n] * u[j + l * m]; } } } } // // Compute x = A_pseudo * b. // x = r8mat_mv_new(n, m, a_pseudo, b); delete[] a_copy; delete[] a_pseudo; delete[] e; delete[] s; delete[] sdiag; delete[] sp; delete[] u; delete[] v; delete[] work; return x; } // // Purpose: // // RBF_INTERP_ND evaluates a radial basis function interpolant. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 30 June 2012 // // Author: // // John Burkardt // // Reference: // // William Press, Brian Flannery, Saul Teukolsky, William Vetterling, // Numerical Recipes in FORTRAN: The Art of Scientific Computing, // Third Edition, // Cambridge University Press, 2007, // ISBN13: 978-0-521-88068-8, // LC: QA297.N866. // // Parameters: // // Input, int M, the spatial dimension. // // Input, int ND, the number of data points. // // Input, double XD[M*ND], the data points. // // Input, double R0, a scale factor. R0 should be larger than the typical // separation between points, but smaller than the maximum separation. // The value of R0 has a significant effect on the resulting interpolant. // // Input, void PHI ( int N, double R[], double R0, double V[] ), a // function to evaluate the radial basis functions. // // Input, double W[ND], the weights, as computed by RBF_WEIGHTS. // // Input, int NI, the number of interpolation points. // // Input, double XI[M*NI], the interpolation points. // // Output, double RBF_INTERP_ND[NI], the interpolated values. // double *rbf_interp(int m, int nd, double xd[], double r0, void(*phi)(int n, double r[], double r0, double v[]), double w[], int ni, double xi[]) { double *fi; int i; int j; int k; double *r; double *v; fi = new double[ni]; r = new double[nd]; v = new double[nd]; for (i = 0; i < ni; ++i) { for (j = 0; j < nd; ++j) { r[j] = 0.0; for (k = 0; k < m; k++) { r[j] = r[j] + pow(xi[k + i * m] - xd[k + j * m], 2); } r[j] = sqrt(r[j]); } phi(nd, r, r0, v); fi[i] = r8vec_dot_product(nd, v, w); } delete[] r; delete[] v; return fi; } // // Purpose: // // RBF_WEIGHT computes weights for radial basis function interpolation. // // Discussion: // // We assume that there are N (nonsingular) equations in N unknowns. // // However, it should be clear that, if we are willing to do some kind // of least squares calculation, we could allow for singularity, // inconsistency, or underdetermine systems. This could be associated // with data points that are very close or repeated, a smaller number // of data points than function values, or some other ill-conditioning // of the system arising from a peculiarity in the point spacing. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 30 June 2012 // // Author: // // John Burkardt // // Reference: // // William Press, Brian Flannery, Saul Teukolsky, William Vetterling, // Numerical Recipes in FORTRAN: The Art of Scientific Computing, // Third Edition, // Cambridge University Press, 2007, // ISBN13: 978-0-521-88068-8, // LC: QA297.N866. // // Parameters: // // Input, int M, the spatial dimension. // // Input, int ND, the number of data points. // // Input, double XD[M*ND], the data points. // // Input, double R0, a scale factor. R0 should be larger than the typical // separation between points, but smaller than the maximum separation. // The value of R0 has a significant effect on the resulting interpolant. // // Input, void PHI ( int N, double R[], double R0, double V[] ), a // function to evaluate the radial basis functions. // // Input, double FD[ND], the function values at the data points. // // Output, double RBF_WEIGHT[ND], the weights. // double *rbf_weight(int m, int nd, double xd[], double r0, void(*phi)(int n, double r[], double r0, double v[]), double fd[]) { double *a; int i; int j; int k; double *r; double *v; double *w; a = new double[nd * nd]; r = new double[nd]; v = new double[nd]; for (i = 0; i < nd; ++i) { for (j = 0; j < nd; ++j) { r[j] = 0.0; for (k = 0; k < m; k++) { r[j] = r[j] + pow(xd[k + i * m] - xd[k + j * m], 2); } r[j] = sqrt(r[j]); } phi(nd, r, r0, v); for (j = 0; j < nd; ++j) { a[i + j * nd] = v[j]; } } // // Solve for the weights. // w = r8mat_solve_svd(nd, nd, a, fd); delete[] a; delete[] r; delete[] v; return w; }
48,543
18,499
// // Created by Chris Luttio on 3/27/21. // #include "initialize_client_requests_task.h" #include "load_requested_file_task.h" #include "general/utils.h" #include "general/route_resolver.h" #include "authorize_user_task.h" #include "jwt-cpp/jwt.h" #include "general/json.hpp" #include "objects/mail/email_parser.h" #include "models/email_model.h" using json = nlohmann::json; void InitializeClientRequestsTask::perform() { for (const auto& pair: state->requests) { auto request = std::make_shared<ClientRequest>(*pair.second); if (request->status == RequestStatus::New) { switch (request->type) { case RetrieveFile: { state->scheduler->add(std::make_shared<LoadRequestedFileTask>(_controller, request, state->config)); request->status = RequestStatus::Working; _controller->apply(Action(ModifyClientRequest, request)); break; } case ResolveRoute: { auto headers = request->http_request->headers; RouteResolver resolver; resolver.resolve(state->routes, request->uri.to_string()); bool authorized = false; if (resolver.attributes.find("Access") != resolver.attributes.end()) { std::string role = resolver.attributes["Access"]; if (role != "public") { if (headers.find("Authorization") != headers.end()) { auto authorization = headers["Authorization"]; auto components = split_string(" ", *authorization); if (components.size() == 2 && components[0] == "Bearer") { std::string access_token = components[1]; for (const auto& account : state->accounts) { if (account->role == role) { for (const auto& auth : account->authorizations) { if (auth.access_token == access_token) { auto decoded = jwt::decode(access_token); auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::hs256{"helloworld"}) .with_issuer("auth0"); authorized = true; try { verifier.verify(decoded); } catch (std::exception& e) { authorized = false; } break; } } if (authorized) break; } } } } } else { authorized = true; } } else { authorized = true; } if (authorized) { request->response_headers = resolver.attributes; request->uri = URL::parse(resolver.url); request->type = RetrieveFile; } else { request->type = Forbidden; request->status = Failed; } _controller->apply(Action(ModifyClientRequest, request)); break; } case Authorize: { state->scheduler->add(std::make_shared<AuthorizeUserTask>(state, _controller, request)); request->status = Working; _controller->apply(Action(ModifyClientRequest, request)); break; } case Refresh: { bool authorized = false; std::string new_token; if (!request->data->empty()) { json body = json::parse(*request->data); std::string refresh_token; if (body.find("refresh_token") != body.end()) refresh_token = body["refresh_token"]; for (const auto& account: state->accounts) { for (auto& auth: account->authorizations) { if (auth.refresh_token == refresh_token) { auto decoded = jwt::decode(refresh_token); auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::hs256{"helloworld"}) .with_issuer("auth0"); authorized = true; try { verifier.verify(decoded); } catch (std::exception& e) { authorized = false; } if (authorized) { auto now = std::chrono::system_clock::now(); auth.access_token = jwt::create() .set_issuer("auth0") .set_type("JWT") .set_issued_at(now) .set_expires_at(now + std::chrono::minutes{60}) .set_payload_claim("username", jwt::claim(std::string(account->username))) .set_payload_claim("password", jwt::claim(std::string(account->password))) .set_payload_claim("client_id", jwt::claim(auth.client_id)) .sign(jwt::algorithm::hs256{"helloworld"}); new_token = auth.access_token; } break; } } if (authorized) break; } } if (authorized) { json body({{"access_token", new_token}}); request->data = std::make_shared<std::string>(body.dump()); request->status = Complete; } else { request->type = Authorize; request->status = Failed; } _controller->apply(Action(ModifyClientRequest, request)); break; } case SendMail: { std::shared_ptr<UserAccount> user; if (authorize(request, user)) { json body = json::parse(*request->data); auto message = Email::create(body["from"], body["to"], body["subject"], std::make_shared<std::string>(body["body"])); state->mail->append_send_queue(message); request->status = Complete; } else { request->type = Forbidden; request->status = Failed; } _controller->apply(Action(ModifyClientRequest, request)); break; } case ListMail: { std::shared_ptr<UserAccount> user; if (authorize(request, user)) { auto sql = "SELECT * " "FROM emails_with_labels " "WHERE account_id = %0 " "ORDER BY id DESC"; auto list_query = state->database->query(sql); list_query.parse(); auto rows = list_query.store(user->id); int last_id = 0; std::vector<json> labels; json output; for (int i = 0; i < rows.size(); i++) { auto row = rows[i]; int id = atoi(row["id"]); if (!row["label_id"].is_null()) { json label; label["id"] = atoi(row["label_id"]); label["name"] = row["label_name"].c_str(); labels.push_back(label); } if ((i + 1 < rows.size() && atoi(rows[i + 1]["id"]) != id) || i + 1 == rows.size()) { json summary; summary["id"] = id; summary["message-id"] = row["name"].c_str(); summary["sender"] = row["sender"].c_str(); summary["to"] = row["to"].c_str(); summary["subject"] = row["subject"].c_str(); summary["created_at"] = row["created_at"].c_str(); summary["account_id"] = atoi(row["account_id"]); summary["labels"] = labels; output.push_back(summary); labels.clear(); } last_id = id; } request->data = std::make_shared<std::string>(output.dump()); request->response_headers["Content-Type"] = "application/json"; request->type = OK; request->status = Complete; } else { request->type = Forbidden; request->status = Failed; } _controller->apply(Action(ModifyClientRequest, request)); break; } case GetMail: { std::shared_ptr<UserAccount> user; if (authorize(request, user)) { request->type = NotFound; request->status = Complete; if (request->uri.components.size() == 2) { auto endpoint = request->uri.components[1]; std::string name; std::map<std::string, std::string> query; int i = 0; while (i < endpoint.size() && endpoint[i] != '?') i++; name = endpoint.substr(0, i); if (i < endpoint.size() && endpoint[i] == '?') { i++; while (i < endpoint.size()) { int s = i; while (i < endpoint.size() && endpoint[i] != '=') i++; std::string key = endpoint.substr(s, i - s); i++; s = i; std::string value; while (i < endpoint.size() && endpoint[i] != '&') { if (endpoint[i] == '_') { value += '/'; } else { value += endpoint[i]; } i++; } query[key] = value; i++; } } auto path = "emails/" + name + ".eml"; FILE* file = fopen(path.c_str(), "r"); if (file) { auto data = std::make_shared<std::string>(); const size_t len = 10 * 1024; char *buffer = new char[len]; size_t amount = 0; do { amount = fread(buffer, 1, len, file); data->append(std::string(buffer, buffer + amount)); } while (amount == len); delete[] buffer; fclose(file); auto output = std::make_shared<std::string>(); std::string type = "text/plain"; try { auto email = EmailParser::parse(data); auto content_type = email->header->get_content_type_header(); if (content_type == nullptr) { output->append(email->generate_body()); } else { if (content_type->type != "multipart") { output->append(email->generate_body()); } else { if (content_type->subtype == "alternative" && !query.empty()) { if (query.find("accept") != query.end()) type = query["accept"]; const BodyPart* part = email->body->find_alternative(type); if (part == nullptr) part = email->body->find_alternative("text/plain"); if (part != nullptr && part->content) { output->append(*part->content); } else { output->append(email->generate_body()); } } else { output->append(email->generate_body()); } } } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } request->type = OK; request->data = output; request->response_headers["Content-Type"] = type; } } } else { request->type = Forbidden; request->status = Failed; } _controller->apply(Action(ModifyClientRequest, request)); break; } default: break; } } } } bool InitializeClientRequestsTask::authorize(const std::shared_ptr<ClientRequest> &request, std::shared_ptr<UserAccount> &user) { std::string token; auto headers = request->http_request->headers; if (headers.find("Authorization") != headers.end()) { auto auth = headers["Authorization"]; if (auth->size() > 7) token = auth->substr(7); } return state->authenticator->authenicate(token, user); }
16,748
3,511
/* // Copyright (c) 2016 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #include "pooling_inst.h" #include "primitive_type_base.h" namespace cldnn { primitive_type_id pooling_type_id() { static primitive_type_base<pooling, pooling_inst> instance; return &instance; } layout pooling_inst::calc_output_layout(parent::typed_node const& node) { auto desc = node.get_primitive(); auto input_layout = node.input().get_output_layout(); auto input_spatial_size = node.input().get_output_layout().size.spatial.size(); if (input_spatial_size != 2) throw std::runtime_error("Only two dimensional spatials are supported by pooling"); auto input_offsets = desc->input_offset.sizes(); auto strides = desc->stride.sizes(); auto window_sizes = desc->size.sizes(); //TODO !!!implement correct output size calculation!!! auto output_sizes = input_layout.size.sizes(); auto spatial_offset = CLDNN_TENSOR_BATCH_DIM_MAX + CLDNN_TENSOR_FEATURE_DIM_MAX; for (decltype(input_spatial_size) i = spatial_offset; i < input_spatial_size + spatial_offset; i++) { // TODO: Consider moving general parameter verification to arguments constructor. if (strides[i] <= 0) throw std::runtime_error("Stride must be positive (>= 1)"); if (2 * input_offsets[i] >= output_sizes[i]) throw std::runtime_error("Input offset is greater than input data range. There is no input data to process"); output_sizes[i] = static_cast<cldnn::tensor::value_type>( 2 * input_offsets[i] < output_sizes[i] // ? std::max(output_sizes[i] - 2 * input_offsets[i] - window_sizes[i], 0) / strides[i] + 1 ? ceil_div(std::max(output_sizes[i] - 2 * input_offsets[i] - window_sizes[i], 0), strides[i]) + 1 : 0); } return{ input_layout.data_type, input_layout.format, output_sizes }; } std::string pooling_inst::to_string(pooling_node const& node) { std::stringstream primitive_description; auto desc = node.get_primitive(); auto input = node.input(); auto strd = desc->stride; auto kernel_size = desc->size; auto mode = desc->mode == pooling_mode::average ? "avarage" : "max"; primitive_description << "id: " << desc->id << ", type: pooling" << ", mode: " << mode << "\n\tinput: " << input.id() << ", count: " << input.get_output_layout().count() << ", size: " << input.get_output_layout().size << "\n\tstride: " << strd.spatial[0] << "x" << strd.spatial[1] << "\n\tkernel size: " << kernel_size.spatial[0] << "x" << kernel_size.spatial[1] << "\n\toutput padding lower size: " << desc->output_padding.lower_size() << "\n\toutput padding upper size: " << desc->output_padding.upper_size() << "\n\toutput: count: " << node.get_output_layout().count() << ", size: " << node.get_output_layout().size << '\n'; return primitive_description.str(); } }
3,591
1,162
/* StairCase Problem Send Feedback A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run up to the stairs. You need to return all possible number of ways. Time complexity of your code should be O(n). Since the answer can be pretty large print the answer % mod(10^9 +7) Input Format: First line will contain T (number of test case). Each test case is consists of a single line containing an integer N. Output Format: For each test case print the answer in new line Constraints : 1 <= T < = 10 1 <= N <= 10^5 */ #include <bits/stdc++.h> using namespace std; int steps(int n) { if (n == 0) return 1; if (n == 1) return 1; if (n == 2) return 2; return steps(n - 1) + steps(n - 2) + steps(n - 3); } int steps_memo(int n, long memo[]) { if (n == 0) return 1; if (n == 1) return 1; if (n == 2) return 2; if(memo[n] > 0){ return memo[n]; } int output = steps_memo(n-1, memo) + steps_memo(n-2, memo) + steps_memo(n-3, memo); memo[n] = output; return output; } int steps_iter(int n){ int arr[n+1]; arr[0] = 0; arr[1] = 1; arr[2] = 2; arr[3] = 3; for(int i = 4; i <= n; i++){ arr[i] = arr[i-1] + arr[i-2] + arr[i-3]; } return arr[n]; } int main() { freopen("/home/spy/Desktop/input.txt", "r", stdin); freopen("/home/spy/Desktop/output.txt", "w", stdout); int t; cin >> t; while (t--) { int n; cin >> n; // int ans = steps(n); // long memo[10000000] = {0}; // int ans = steps_memo(n, memo); int ans = steps_iter(n); cout << ans << endl; } return 0; }
1,806
703
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Claeys, Joshua Davis /// Copyright 2010-2017, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zero { /// Defines the collision volume for an ellipsoid (3 dimensional ellipse) defined by three radius values. class EllipsoidCollider : public Collider { public: ZilchDeclareType(TypeCopyMode::ReferenceType); EllipsoidCollider(); // Component interface void Serialize(Serializer& stream) override; void DebugDraw() override; // Collider Interface void ComputeWorldAabbInternal() override; void ComputeWorldBoundingSphereInternal() override; real ComputeWorldVolumeInternal() override; void ComputeLocalInverseInertiaTensor(real mass, Mat3Ref localInvInertia) override; void Support(Vec3Param direction, Vec3Ptr support) const override; /// The x, y, and z radius of the ellipsoid. Vec3 GetRadii() const; void SetRadii(Vec3Param radii); /// The radii of the ellipsoid after transform is applied (scale and rotation). Vec3 GetWorldRadii() const; private: Vec3 mRadii; }; }//namespace Zero
1,269
371
#include "template.hpp" int main() { ll(H, W); vin(string, S, H); auto dp = vecv(bool, H + 1, W + 1, true); rrep(i, H) { rrep(j, W) { if (S[i][j] == '#') { dp[i][j] = true; } else { dp[i][j] = not(dp[i + 1][j] and dp[i][j + 1] and dp[i + 1][j + 1]); } } } yes(dp[0][0], "First", "Second"); }
347
180
/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #include <memory> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "ProcessRegionAggregator.hpp" #include "record.hpp" #include "geopm_test.hpp" #include "MockApplicationSampler.hpp" using geopm::ProcessRegionAggregator; using geopm::ProcessRegionAggregatorImp; using geopm::record_s; using geopm::short_region_s; using geopm::EVENT_REGION_ENTRY; using geopm::EVENT_REGION_EXIT; using geopm::EVENT_SHORT_REGION; using testing::Return; class ProcessRegionAggregatorTest : public ::testing::Test { protected: void SetUp(); MockApplicationSampler m_app_sampler; std::shared_ptr<ProcessRegionAggregator> m_account; int m_num_process = 4; }; void ProcessRegionAggregatorTest::SetUp() { EXPECT_CALL(m_app_sampler, per_cpu_process()) .WillOnce(Return(std::vector<int>({11, 12, 13, 14}))); m_account = std::make_shared<ProcessRegionAggregatorImp>(m_app_sampler); } TEST_F(ProcessRegionAggregatorTest, entry_exit) { std::vector<record_s> records; { // enter region records = { {1.0, 12, EVENT_REGION_ENTRY, 0xDADA} }; m_app_sampler.inject_records(records); m_account->update(); EXPECT_DOUBLE_EQ(0.0, m_account->get_runtime_average(0xDADA)); EXPECT_DOUBLE_EQ(0.0, m_account->get_count_average(0xDADA)); } { // exit region records = { {2.6, 12, EVENT_REGION_EXIT, 0xDADA} }; m_app_sampler.inject_records(records); m_account->update(); EXPECT_DOUBLE_EQ(0.4, m_account->get_runtime_average(0xDADA)); EXPECT_DOUBLE_EQ(0.25, m_account->get_count_average(0xDADA)); } } TEST_F(ProcessRegionAggregatorTest, short_region) { std::vector<record_s> records; short_region_s short_region; { records = { {1.0, 12, EVENT_SHORT_REGION, 0} }; short_region = {0xDADA, 2, 1.0}; m_app_sampler.inject_records(records); EXPECT_CALL(m_app_sampler, get_short_region(0)) .WillOnce(Return(short_region)); m_account->update(); // average across 4 processes EXPECT_DOUBLE_EQ(0.25, m_account->get_runtime_average(0xDADA)); EXPECT_DOUBLE_EQ(0.5, m_account->get_count_average(0xDADA)); } { records = { {2.0, 12, EVENT_SHORT_REGION, 0} }; short_region = {0xDADA, 1, 0.5}; m_app_sampler.inject_records(records); EXPECT_CALL(m_app_sampler, get_short_region(0)) .WillOnce(Return(short_region)); m_account->update(); EXPECT_DOUBLE_EQ(1.5 / m_num_process, m_account->get_runtime_average(0xDADA)); EXPECT_DOUBLE_EQ(0.75, m_account->get_count_average(0xDADA)); } } TEST_F(ProcessRegionAggregatorTest, multiple_processes) { std::vector<record_s> records; short_region_s short_region; { // enter region records = { {1.1, 11, EVENT_REGION_ENTRY, 0xDADA}, {1.2, 12, EVENT_REGION_ENTRY, 0xDADA}, {1.3, 13, EVENT_REGION_ENTRY, 0xDADA}, {1.4, 14, EVENT_REGION_ENTRY, 0xDADA}, }; m_app_sampler.inject_records(records); m_account->update(); EXPECT_DOUBLE_EQ(0.0, m_account->get_runtime_average(0xDADA)); EXPECT_DOUBLE_EQ(0.0, m_account->get_count_average(0xDADA)); EXPECT_DOUBLE_EQ(0.0, m_account->get_runtime_average(0xBEAD)); EXPECT_DOUBLE_EQ(0.0, m_account->get_count_average(0xBEAD)); } { records = { {2.2, 11, EVENT_REGION_EXIT, 0xDADA}, {2.4, 11, EVENT_SHORT_REGION, 0}, {2.0, 12, EVENT_SHORT_REGION, 1}, {2.0, 13, EVENT_SHORT_REGION, 2}, {2.0, 14, EVENT_SHORT_REGION, 3}, {2.8, 14, EVENT_REGION_EXIT, 0xDADA}, }; m_app_sampler.inject_records(records); short_region = {0xBEAD, 2, 0.15}; EXPECT_CALL(m_app_sampler, get_short_region(0)) .WillOnce(Return(short_region)); short_region = {0xBEAD, 2, 0.25}; EXPECT_CALL(m_app_sampler, get_short_region(1)) .WillOnce(Return(short_region)); short_region = {0xBEAD, 1, 0.35}; EXPECT_CALL(m_app_sampler, get_short_region(2)) .WillOnce(Return(short_region)); short_region = {0xBEAD, 1, 0.45}; EXPECT_CALL(m_app_sampler, get_short_region(3)) .WillOnce(Return(short_region)); m_account->update(); EXPECT_DOUBLE_EQ((1.1 + 1.4) / m_num_process, m_account->get_runtime_average(0xDADA)); EXPECT_DOUBLE_EQ(2.0 / m_num_process, m_account->get_count_average(0xDADA)); EXPECT_DOUBLE_EQ((0.15 + 0.25 + 0.35 + 0.45) / m_num_process, m_account->get_runtime_average(0xBEAD)); EXPECT_DOUBLE_EQ( 6.0 / m_num_process, m_account->get_count_average(0xBEAD)); } { records = { {3.2, 12, EVENT_REGION_EXIT, 0xDADA}, {3.3, 13, EVENT_REGION_EXIT, 0xDADA}, {2.0, 12, EVENT_SHORT_REGION, 0}, {2.0, 13, EVENT_SHORT_REGION, 1}, }; m_app_sampler.inject_records(records); short_region = {0xBEAD, 1, 0.15}; EXPECT_CALL(m_app_sampler, get_short_region(0)) .WillOnce(Return(short_region)); short_region = {0xBEAD, 2, 0.25}; EXPECT_CALL(m_app_sampler, get_short_region(1)) .WillOnce(Return(short_region)); m_account->update(); // average of all procs EXPECT_DOUBLE_EQ((1.1 + 2.0 + 2.0 + 1.4) / m_num_process, m_account->get_runtime_average(0xDADA)); EXPECT_DOUBLE_EQ(1.0, m_account->get_count_average(0xDADA)); EXPECT_DOUBLE_EQ((0.15 + 0.25 + 0.35 + 0.45 + 0.15 + 0.25) / m_num_process, m_account->get_runtime_average(0xBEAD)); EXPECT_DOUBLE_EQ((6.0 + 3.0) / m_num_process, m_account->get_count_average(0xBEAD)); } }
6,055
2,548
/**@file test_replace.cpp * An example of doing regex replace with JPCRE2 * @include test_replace.cpp * @author [Md Jahidul Hamid](https://github.com/neurobin) * */ #include <iostream> #include "jpcre2.hpp" typedef jpcre2::select<char> jp; int main(){ jp::Regex re; //Compile the pattern re.setPattern("(?:(?<word>[?.#@:]+)|(?<word>\\w+))\\s*(?<digit>\\d+)") //Set various parameters .addModifier("Jin") // .addPcre2Option(0) //... .compile(); //Finally compile it. if(!re){std::cerr<<re.getErrorMessage();} //subject string std::string s="I am a string with words and digits 45 and specials chars: ?.#@ 443 เฆ… เฆ† เฆ• เฆ– เฆ— เฆ˜ 56"; std::cout<<"\nreplaced string: \n"<< re.initReplace() //create replace object .setSubject(s) //Set various parameters .setReplaceWith("(replaced:$1)(replaced:$2)(replaced:${word})") //... .addModifier("xE") // .addPcre2Option(0) //... .replace(); //Finally perform the replace operation. if(!re){std::cerr<<re.getErrorMessage();} return 0; }
1,527
449
#include "PoweredByWindow.h" #include "screen.h" CPoweredByWindow::CPoweredByWindow() { mGUI = DynaGUI::getInstance(); // mText = mGUI->createWindow( BetaGUI::MAX, BetaGUI::CENTERED ); mWindow = mGUI->createWindow( DWindow::MAX, DWindow::CENTERED ); mWindow->addText( "Powered by :", 175 ); mWindow->newLine(); mLogo = mWindow->addImage( 175,50, "Logo/Ogre" ); /* float screenwidth = CScreen::getInstance()->getRenderWindow()->getWidth(); float screenheight = CScreen::getInstance()->getRenderWindow()->getHeight(); float width = 175; float height = 50; float x = screenwidth - width - 20; float y = (screenheight - height) / 2 + 32; */ mLogoNames.push_back("Logo/Ogre"); mLogoNames.push_back("Logo/OgreOde"); mLogoNames.push_back("Logo/ODE"); mLogoNames.push_back("Logo/OpenAL"); mLogoNames.push_back("Logo/SQlite"); mCurrentLogo = mLogoNames.begin(); //mLogo=mGUI->createImage(Ogre::Vector4(x,y,width, height), (*mCurrentLogo) ); mLogo->setMaterial( (*mCurrentLogo) ); mFadeOutDone = false; mDelay = new CDelay( 2000 ); } void CPoweredByWindow::run() { if( mDelay->isOver() ) { if( mFadeOutDone ) { mCurrentLogo++; if( mCurrentLogo == mLogoNames.end() ) mCurrentLogo = mLogoNames.begin() ; mLogo->setMaterial( (*mCurrentLogo) ); mFadeOutDone = false; mDelay->restart(); } else { // mLogo->setTransparency( ... ); mFadeOutDone = true; } } } CPoweredByWindow::~CPoweredByWindow() { mGUI->destroyWindow( mWindow ); delete( mDelay ); }
1,701
645
#include "winheaders.h" #include <cmath> #include <functional> #include <future> #include <iostream> #include <queue> #include <thread> #include <utility> #include "HCNetSDK.h" #include "bgwin.h" #include "cursors.h" #include "main.h" #include "synchronized_ostream.h" #include "util.h" #include "soap.h" namespace app { auto zoom_func = [](BGWindow* w, float zdelta) -> bool { return w->updateZPos(zdelta); }; auto pt_func = [](BGWindow* w, float p, float t) -> bool { soap::soap_thread.queue( new soap::SoapStartContinuousMoveAction(soap::soap_thread, soap::do_nothing_runner, p, t)); return true; }; auto zoom_accumulate = [](const std::queue<std::tuple<float>>& q) -> std::tuple<float> { float z_total = 0; auto queue_copy = q; while (!queue_copy.empty()) { int elem = std::get<0>(queue_copy.front()); queue_copy.pop(); z_total += elem; } return std::make_tuple(z_total); }; auto pt_accumulate = [](const std::queue<std::tuple<float, float>>& q) -> std::tuple<float, float> { return q.back(); }; BGWindow::BGWindow() : m_dwnd(nullptr), m_onDraw(false), update_z_thread_(std::bind(zoom_func, this, std::placeholders::_1), zoom_accumulate), update_pt_thread_(std::bind(pt_func, this, std::placeholders::_1, std::placeholders::_2), pt_accumulate) {} BGWindow::~BGWindow() {} const MainWindow* BGWindow::DrawingWindow() const { return this->m_dwnd; } MainWindow*& BGWindow::DrawingWindow() { return this->m_dwnd; } void BGWindow::setOnDraw(bool onDraw) { std::unique_lock<std::mutex> lock(this->m_lock); this->m_onDraw = onDraw; } bool BGWindow::onDraw() { std::unique_lock<std::mutex> lock(this->m_lock); return this->m_onDraw; } LRESULT BGWindow::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CREATE: { update_z_thread_.run(); update_pt_thread_.run(); return 0; } case WM_DESTROY: { PostQuitMessage(0); return 0; } case WM_PAINT: { PAINTSTRUCT ps; if (BeginPaint(this->Window(), &ps)) EndPaint(this->Window(), &ps); return 0; } case WM_WINDOWPOSCHANGING: { auto& pos = *reinterpret_cast<WINDOWPOS*>(lParam); if (DrawingWindow()) pos.hwndInsertAfter = m_dwnd->Window(); return DefWindowProc(this->Window(), uMsg, wParam, lParam); } case WM_WINDOWPOSCHANGED: { RECT r; ::GetClientRect(this->Window(), &r); config.streamResolution = {r.right - r.left, r.bottom - r.top}; if (this->DrawingWindow()) { POINT p = {0, 0}; ::ClientToScreen(m_hwnd, &p); ::SetWindowPos(m_dwnd->Window(), 0, p.x, p.y, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME); } return 0; } case WM_LBUTTONDOWN: { setOnDraw(true); ::SetCapture(this->Window()); if (onDraw() && this->DrawingWindow()) { start_pt_move_thread_wrapper(); } return 0; } case WM_MOUSEMOVE: { if (onDraw()) start_pt_move_thread_wrapper(); return 0; } case WM_LBUTTONUP: { if (onDraw() && this->DrawingWindow()) ::InvalidateRgn(this->DrawingWindow()->Window(), nullptr, true); soap::soap_thread.queue( new soap::SoapStopContinuousMoveAction(soap::soap_thread, *this)); setOnDraw(false); ::ReleaseCapture(); return 0; } case WM_MOUSEWHEEL: { auto zDelta = GET_WHEEL_DELTA_WPARAM(wParam); update_z_thread_.queue(zDelta); return 0; } } return DefWindowProc(this->Window(), uMsg, wParam, lParam); } bool BGWindow::updateZPos(int zDelta) { if (zDelta == 0) return true; clog.log("BGWindow::updatezpos: zDelta = ", zDelta); float d = (zDelta * config.z_sensitivity) / (20.f * WHEEL_DELTA); clog.log("BGWindow::updateZPos: initial dz = ", d); d = std::max(-1.f, std::min(1.f, d)); clog.log("BGWindow::updateZPos: final dz = ", d); update_z_thread_.block_process(); const auto action = new soap::SoapRelativeMoveAction(soap::soap_thread, *this, 0.f, 0.f, d); soap::soap_thread.queue(action); return true; } bool BGWindow::start_pt_move_thread_wrapper() { clog.log("start_pt_move_thread_wrapper: Invoked"); RECT rect; ::GetClientRect(this->Window(), &rect); POINT p; ::GetCursorPos(&p); ::ScreenToClient(m_hwnd, &p); if (p.x < rect.left || p.x >= rect.right || p.y < rect.top || p.y >= rect.bottom) return false; clog.log("start_pt_move_thread_wrapper: position changed."); const auto lx = rect.right - rect.left; const auto ly = rect.bottom - rect.top; const auto dx = 2 * ((p.x - lx / 2) * 1. / lx); const auto dy = 2 * -((p.y - ly / 2) * 1. / ly); clog.log("Queueing [dp=", dx, ", dt=", dy, "]"); soap::soap_thread.queue( new soap::SoapStartContinuousMoveAction(soap::soap_thread, *this, dx, dy)); return true; } void BGWindow::soap_absolute_move_is_done(soap::SoapAbsoluteMove* action) { globalwin_->refresh_bars(); clog.log("BGWindow::soap_absolute_move_is_done"); } void BGWindow::soap_relative_move_is_done(soap::SoapRelativeMoveAction* action) { clog.log("BGWindow::soap_relative_move_is_done"); update_z_thread_.unblock_process(); } void BGWindow::start_continuous_move_is_done(soap::SoapStartContinuousMoveAction* action) { clog.log("BGWindow::start_continuous_move_is_done: start"); clog.log("BGWindow::start_continuous_move_is_done: done"); } void BGWindow::stop_continuous_move_is_done(soap::SoapStopContinuousMoveAction* action) { clog.log("BGWindow::stop_continuous_move_is_done: start"); globalwin_->refresh_bars(); clog.log("BGWindow::stop_continuous_move_is_done: done"); } } // namespace app
5,968
2,274
#include "vtb/Render.hpp" #include "vtb/Device.hpp" #include "vtb/SwapChain.hpp" #include "vtb/Semaphore.hpp" VTB_BEGIN void Render::Create( const Device& device, const SwapChain& swapChain, const std::vector<VkCommandBuffer>& buffers) { device_ = &device; swapChain_ = &swapChain; commandBuffers_ = &buffers; imageReadySemaphor_.Create(device.Get()); renderFinishedSemaphore_.Create(device.Get()); } void Render::Destroy() { imageReadySemaphor_.Destroy(); renderFinishedSemaphore_.Destroy(); } void Render::Draw() const { // wait for last frame VTB_CALL(vkQueueWaitIdle(device_->PresentQueue())); // get next frame uint32_t imageIndex = swapChain_->Next(imageReadySemaphor_.Get()); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore waitSemaphores[] = { imageReadySemaphor_.Get()}; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffers_->at(imageIndex); VkSemaphore signalSemaphores[] = { renderFinishedSemaphore_.Get() }; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores; // The last parameter references an optional fence that will be signaled when the command buffers finish execution. // We're using semaphores for synchronization, so we'll just pass a VK_NULL_HANDLE. VTB_CALL(vkQueueSubmit(device_->GraphicsQueue(), 1, &submitInfo, VK_NULL_HANDLE)); // Submit the result back to the swap chain to have it eventually show up on the screen. VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = signalSemaphores; // specify the swap chains to present images to and the index of the image for each swap chain. VkSwapchainKHR swapChains[] = { swapChain_->Get() }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VTB_CALL(vkQueuePresentKHR(device_->PresentQueue(), &presentInfo)); } VTB_END
2,352
811
/* * Example program for the Allegro library, by Peter Wang. * * Test audio properties (gain and panning, for now). */ #include "allegro5/allegro.h" #include "allegro5/allegro_image.h" #include "allegro5/allegro_font.h" #include "allegro5/allegro_primitives.h" #include "allegro5/allegro_audio.h" #include "allegro5/allegro_acodec.h" #include "nihgui.hpp" #include <cstdio> #include "common.c" ALLEGRO_FONT *font_gui; ALLEGRO_SAMPLE *sample; ALLEGRO_SAMPLE_INSTANCE *sample_inst; class Prog { private: Dialog d; ToggleButton pan_button; HSlider pan_slider; Label speed_label; HSlider speed_slider; ToggleButton bidir_button; Label gain_label; VSlider gain_slider; Label mixer_gain_label; VSlider mixer_gain_slider; Label two_label; Label one_label; Label zero_label; public: Prog(const Theme & theme, ALLEGRO_DISPLAY *display); void run(); void update_properties(); }; Prog::Prog(const Theme & theme, ALLEGRO_DISPLAY *display) : d(Dialog(theme, display, 40, 20)), pan_button(ToggleButton("Pan")), pan_slider(HSlider(1000, 2000)), speed_label(Label("Speed")), speed_slider(HSlider(1000, 5000)), bidir_button(ToggleButton("Bidir")), gain_label(Label("Gain")), gain_slider(VSlider(1000, 2000)), mixer_gain_label(Label("Mixer gain")), mixer_gain_slider(VSlider(1000, 2000)), two_label(Label("2.0")), one_label(Label("1.0")), zero_label(Label("0.0")) { pan_button.set_pushed(true); d.add(pan_button, 2, 10, 4, 1); d.add(pan_slider, 6, 10, 22, 1); d.add(speed_label, 2, 12, 4, 1); d.add(speed_slider, 6, 12, 22, 1); d.add(bidir_button, 2, 14, 4, 1); d.add(gain_label, 29, 1, 2, 1); d.add(gain_slider, 29, 2, 2, 17); d.add(mixer_gain_label, 33, 1, 6, 1); d.add(mixer_gain_slider, 35, 2, 2, 17); d.add(two_label, 32, 2, 2, 1); d.add(one_label, 32, 10, 2, 1); d.add(zero_label, 32, 18, 2, 1); } void Prog::run() { d.prepare(); while (!d.is_quit_requested()) { if (d.is_draw_requested()) { update_properties(); al_clear_to_color(al_map_rgb(128, 128, 128)); d.draw(); al_flip_display(); } d.run_step(true); } } void Prog::update_properties() { float pan; float speed; float gain; float mixer_gain; if (pan_button.get_pushed()) pan = pan_slider.get_cur_value() / 1000.0f - 1.0f; else pan = ALLEGRO_AUDIO_PAN_NONE; al_set_sample_instance_pan(sample_inst, pan); speed = speed_slider.get_cur_value() / 1000.0f; al_set_sample_instance_speed(sample_inst, speed); if (bidir_button.get_pushed()) al_set_sample_instance_playmode(sample_inst, ALLEGRO_PLAYMODE_BIDIR); else al_set_sample_instance_playmode(sample_inst, ALLEGRO_PLAYMODE_LOOP); gain = gain_slider.get_cur_value() / 1000.0f; al_set_sample_instance_gain(sample_inst, gain); mixer_gain = mixer_gain_slider.get_cur_value() / 1000.0f; al_set_mixer_gain(al_get_default_mixer(), mixer_gain); } int main(int argc, char **argv) { ALLEGRO_DISPLAY *display; const char *filename; if (argc >= 2) { filename = argv[1]; } else { filename = "data/testing.ogg"; } if (!al_init()) { abort_example("Could not init Allegro\n"); return 1; } al_install_keyboard(); al_install_mouse(); al_init_image_addon(); al_init_font_addon(); al_init_primitives_addon(); al_init_acodec_addon(); if (!al_install_audio()) { abort_example("Could not init sound!\n"); return 1; } if (!al_reserve_samples(1)) { abort_example("Could not set up voice and mixer.\n"); return 1; } sample = al_load_sample(filename); if (!sample) { abort_example("Could not load sample from '%s'!\n", filename); } al_set_new_display_flags(ALLEGRO_GENERATE_EXPOSE_EVENTS); display = al_create_display(640, 480); if (!display) { abort_example("Unable to create display\n"); return 1; } font_gui = al_load_font("data/fixed_font.tga", 0, 0); if (!font_gui) { abort_example("Failed to load data/fixed_font.tga\n"); return 1; } /* Loop the sample. */ sample_inst = al_create_sample_instance(sample); al_set_sample_instance_playmode(sample_inst, ALLEGRO_PLAYMODE_LOOP); al_attach_sample_instance_to_mixer(sample_inst, al_get_default_mixer()); al_play_sample_instance(sample_inst); /* Don't remove these braces. */ { Theme theme(font_gui); Prog prog(theme, display); prog.run(); } al_destroy_sample_instance(sample_inst); al_destroy_sample(sample); al_uninstall_audio(); al_destroy_font(font_gui); return 0; (void)argc; (void)argv; } /* vim: set sts=3 sw=3 et: */
4,778
2,059
/* * Copyright 2021 Assured Information Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ #pragma once #include "HBASE_BLOCK_IMPL.hh" #include "windows/kernel/nt/structs/structs.hh" #include <introvirt/core/memory/guest_ptr.hh> #include <introvirt/fwd.hh> #include <introvirt/windows/kernel/nt/types/registry/CM_KEY_NODE.hh> #include <introvirt/windows/kernel/nt/types/registry/HIVE.hh> #include <memory> #include <optional> namespace introvirt { namespace windows { namespace nt { template <typename PtrType> class NtKernelImpl; template <typename PtrType> class CM_KEY_NODE_IMPL; template <typename PtrType> class HIVE_IMPL final : public HIVE { public: const std::string& FileFullPath() const override; const std::string& FileUserName() const override; const std::string& HiveRootPath() const override; const HBASE_BLOCK& BaseBlock() const override; const CM_KEY_NODE* RootKeyNode() const override; const CM_KEY_NODE* KeyNode(uint32_t KeyIndex) const override; GuestVirtualAddress CellAddress(uint32_t KeyIndex) const override; const HIVE* PreviousHive() const override; const HIVE* NextHive() const override; uint32_t HiveFlags() const override; GuestVirtualAddress address() const override; HIVE_IMPL(const NtKernelImpl<PtrType>& kernel, const GuestVirtualAddress& gva); ~HIVE_IMPL() override; private: GuestVirtualAddress getBlockAddress(GuestVirtualAddress pEntry) const; const NtKernelImpl<PtrType>& kernel_; const GuestVirtualAddress gva_; const structs::CMHIVE* cmhive_; const structs::DUAL* dual_; const structs::HMAP_ENTRY* hmap_entry_; guest_ptr<char[]> cmhive_buffer_; mutable std::unordered_map<uint32_t, std::unique_ptr<CM_KEY_NODE_IMPL<PtrType>>> KeyIndexNodeMap_; mutable std::optional<HBASE_BLOCK_IMPL<PtrType>> BaseBlock_; mutable std::string FileFullPath_; mutable std::string FileUserName_; mutable std::string HiveRootPath_; mutable std::unique_ptr<HIVE_IMPL<PtrType>> PreviousHive_; mutable std::unique_ptr<HIVE_IMPL<PtrType>> NextHive_; }; } // namespace nt } // namespace windows } // namespace introvirt
2,698
880
#include "RenderSettings.h" RenderSettings g_renderSettings = {0, 0};
70
24
๏ปฟ#include "search.h" #include <math.h> Search::Search() { } //function negamax(node, depth, ฮฑ, ฮฒ, color) int Search::negamax(Position& position, int depth, int alpha, int beta) { if (stopThinking) throw exit_search(); // From https://en.wikipedia.org/wiki/Negamax //alphaOrig : = ฮฑ int alpha_original = alpha; // Transposition Table Lookup; node is the lookup key for ttEntry //ttEntry : = TranspositionTableLookup(node) auto tt_entry = tt->retrieve(zobristHash); //if ttEntry is valid and ttEntry.depth โ‰ฅ depth if (tt_entry != NULL && tt_entry->depth >= depth) { // Add depth punishment if there's a checkmate coming up int retrieved_eval = tt_entry->eval; //if ttEntry.Flag = EXACT if (tt_entry->flag == TranspositionTable::EntryType::EXACT) //return ttEntry.Value return retrieved_eval; //else if ttEntry.Flag = LOWERBOUND else if (tt_entry->flag == TranspositionTable::EntryType::LOWER) //ฮฑ : = max(ฮฑ, ttEntry.Value) alpha = max(alpha, retrieved_eval); //else if ttEntry.Flag = UPPERBOUND else if (tt_entry->flag == TranspositionTable::EntryType::UPPER) //ฮฒ : = min(ฮฒ, ttEntry.Value) beta = min(beta, retrieved_eval); //if ฮฑ โ‰ฅ ฮฒ if (alpha >= beta) //return ttEntry.Value return tt_entry->eval; } //if depth = 0 or node is a terminal node if (depth == 0) //return color * the heuristic value of node return sideSign(sideToMove) * calculateStaticEval(); //bestValue : = -โˆž int best_value = -CHECKMATE_VALUE; //childNodes : = GenerateMoves(node) auto move_list = genMoves(); // If this is a terminal node return the checkmate or stalemate score if (move_list.size() == 0) { int ending_value = checkCheck(sideToMove) ? -CHECKMATE_VALUE : 0; tt->insert(zobristHash, ending_value, depth, TranspositionTable::EntryType::EXACT); return ending_value; } //childNodes : = OrderMoves(childNodes) sort(move_list.begin(), move_list.end(), Move::greater); //foreach child in childNodes for (auto move : move_list) { performMove(&move); //v : = -negamax(child, depth - 1, -ฮฒ, -ฮฑ, -color) int value = -negamax(depth - 1, -beta, -alpha); undoMove(&move); //bestValue : = max(bestValue, v) best_value = max(best_value, value); //ฮฑ : = max(ฮฑ, v) alpha = max(alpha, value); //if ฮฑ โ‰ฅ ฮฒ if (alpha >= beta) //break break; } // Transposition Table Store; node is the lookup key for ttEntry TranspositionTable::EntryType entry_type; //ttEntry.Value : = bestValue //if bestValue โ‰ค alphaOrig if (best_value <= alpha_original) //ttEntry.Flag : = UPPERBOUND entry_type = TranspositionTable::EntryType::UPPER; //else if bestValue โ‰ฅ ฮฒ else if (best_value >= beta) //ttEntry.Flag : = LOWERBOUND entry_type = TranspositionTable::EntryType::LOWER; //else else //ttEntry.Flag : = EXACT entry_type = TranspositionTable::EntryType::EXACT; //endif //ttEntry.depth : = depth //TranspositionTableStore(node, ttEntry) tt->insert(zobristHash, best_value, depth, entry_type); //return bestValue return best_value; } int Search::terminateSearch(int alpha, int beta) { if (stopThinking) throw exit_search(); vector<Move> move_list = genMoves(); move_list.erase(remove_if(move_list.begin(), move_list.end(), Move::isNotCapture), move_list.end()); if (move_list.size() == 0) return calculateStaticEval(); int best_value = sideToMove == WHITE ? INT_MIN : INT_MAX; sort(move_list.begin(), move_list.end(), sideToMove == WHITE ? Move::greater : Move::lesser); for (auto& move : move_list) { int eval; performMove(&move); auto tt_entry = tt->retrieve(zobristHash); if (tt_entry == NULL) { eval = terminateSearch(alpha, beta); tt->insert(zobristHash, eval, 1, TranspositionTable::EntryType::EXACT); } else eval = tt_entry->eval; undoMove(&move); best_value = sideToMove == WHITE ? max(best_value, eval) : min(best_value, eval); sideToMove == WHITE ? alpha = max(alpha, eval) : beta = min(beta, eval); if (beta <= alpha) break; } return best_value; } /* ponder - analyse the position without care for depth of the search */ void Search::ponderPosition(Position& position) { ponderPosition(position, 0); } /* ponder - analyse the position without care for depth of the search */ void Search::ponderPosition(Position& position, int depth) { if (stopThinking) return; try { string send = "info score cp "; int score = sideSign(sideToMove) * negamax(depth, INT_MIN, INT_MAX); send += to_string(score) + " depth " + to_string(depth) + " pv"; auto pvs = new vector<Move>(); getPV(pvs, depth); for (auto it : *pvs) send += " " + it.getName(); output->output(send); } catch (exit_search e) {} vector<Move> move_list = genMoves(); if (move_list.size() == 0) return; sort(move_list.begin(), move_list.end(), Move::greater); auto best_move = move_list.at(0); if (abs(best_move.eval) > CHECKMATE_THRESHOLD) output->debug("Found a checkmate in " + to_string(best_move.depth) + " starting with " + best_move.getName()); int padding = 10; string debugStringMoveName = "Move |"; string debugStringEval = "Eval |"; string debugStringDepth = "Depth |"; for (auto move : move_list) { string move_name = move.getName(); string move_eval = to_string(move.eval); string move_depth = to_string(move.depth); debugStringMoveName += " " + string(10 - move_name.length(), ' ') + move.getName() + " |"; debugStringEval += " " + string(10 - move_eval.length(), ' ') + to_string(move.eval) + " |"; debugStringDepth += " " + string(10 - move_depth.length(), ' ') + to_string(move.depth) + " |"; } output->debug("Debug: move list\n" + debugStringMoveName + "\n" + debugStringEval + "\n" + debugStringDepth + "\n"); output->debug("Debug: bestmove " + best_move.getName()); ponder(depth + 1); } /* getPV - return what the engine considers the best line for the given depth */ void Search::getPV(vector<Move>* move_list, int depth) { Move* pv = topMove(); if (pv == NULL) return; move_list->push_back(Move(*pv)); performMove(pv); if (depth > 0) getPV(move_list, depth - 1); undoMove(pv); } /* topMove - Return the current top move */ Move* Search::topMove() { // Evaluate each move vector<Move> move_list = genMoves(); sort(move_list.begin(), move_list.end(), Move::greater); if (move_list.size() == 0) return NULL; return new Move(move_list[0]); }
7,129
2,365
#include "statusobject.h" //(c) Adrian Boeing 2004, see liscence.txt (BSD liscence) /* Abstract: Status object for message/error passing, without exceptions Author: Adrian Boeing Revision History: Version 1.1 : 04/08/03 TODO: -Allow integration of status tracker, or similar, to enable multiple path error recovery. */ #ifndef NULL #define NULL 0 #endif StatusObject::StatusObject() : m_pParent(0), m_StatusCode(SOK) { } StatusObject::StatusObject(const StatusObject& so) : m_pParent(so.m_pParent), m_StatusCode(so.m_StatusCode) { } StatusObject::~StatusObject() {} void StatusObject::SetStatus(StatusCode Statuscode) { if (m_StatusCode & TEST_ERROR) return; //dont overwrite existing errors m_StatusCode = Statuscode; if (m_pParent!=NULL) { if (!(m_pParent->m_StatusCode & TEST_ERROR) ) { m_pParent->SetStatus(Statuscode); //dont overwrite existing errors } } } void StatusObject::ClearStatus(StatusCode Statuscode) { m_StatusCode = Statuscode; if (m_pParent!=NULL) m_pParent->ClearStatus(Statuscode); } void StatusObject::SetParent(StatusObject *pParent) { m_pParent=pParent; } StatusObject *StatusObject::GetParent() { return m_pParent; }
1,188
440
// ---------------------------------------------------- // AIMP DotNet SDK // Copyright (c) 2014 - 2020 Evgeniy Bogdan // https://github.com/martin211/aimp_dotnet // Mail: mail4evgeniy@gmail.com // ---------------------------------------------------- #include "Stdafx.h" #include "AimpDataFilterGroup.h" #include "AimpDataFieldFilter.h" #include "AimpDataFieldFilterByArray.h" using namespace AIMP::SDK; // TODO: #18 AimpDataFilterGroup::AimpDataFilterGroup(IAIMPMLDataFilterGroup* filterGroup) : AimpObject(filterGroup, false) { } FilterGroupOperationType AimpDataFilterGroup::Operation::get() { return FilterGroupOperationType(PropertyListExtension::GetInt32(InternalAimpObject, AIMPML_FILTERGROUP_OPERATION)); } void AimpDataFilterGroup::Operation::set(FilterGroupOperationType val) { PropertyListExtension::SetInt32(InternalAimpObject, AIMPML_FILTERGROUP_OPERATION, static_cast<int>(val)); } AimpActionResult<IAimpDataFieldFilter^>^ AimpDataFilterGroup::Add( String^ field, Object^ value1, Object^ value2, FieldFilterOperationType operation) { IAimpDataFieldFilter^ filter = nullptr; IAIMPMLDataFieldFilter* nativeFilter = nullptr; ActionResultType result = ActionResultType::Fail; VARIANT val1 = AimpConverter::ToNativeVariant(value1); VARIANT val2 = AimpConverter::ToNativeVariant(value2); VARIANT v1; VariantInit(&v1); auto sField = AimpConverter::ToAimpString(field); try { result = CheckResult(InternalAimpObject->Add( sField, &val1, &val2, static_cast<int>(operation), &nativeFilter)); if (result == ActionResultType::OK && nativeFilter != nullptr) { filter = gcnew AimpDataFieldFilter(nativeFilter); } } finally { if (sField != nullptr) { sField->Release(); sField = nullptr; } } return gcnew AimpActionResult<IAimpDataFieldFilter^>(result, filter); } AimpActionResult<IAimpDataFieldFilterByArray^>^ AimpDataFilterGroup::Add( String^ field, array<Object^>^ values, int count) { IAIMPMLDataFieldFilterByArray* nativeObj = nullptr; auto cnt = values->Length; VARIANT* variants = new VARIANT[cnt]; IAimpDataFieldFilterByArray^ filter = nullptr; for (int i = 0; i < values->Length; i++) { variants[i] = AimpConverter::ToNativeVariant(values[i]); } const auto result = CheckResult(InternalAimpObject->Add2( AimpConverter::ToAimpString(field), &variants[0], count, &nativeObj)); if (result == ActionResultType::OK && nativeObj != nullptr) { filter = gcnew AimpDataFieldFilterByArray(nativeObj); } return gcnew AimpActionResult<IAimpDataFieldFilterByArray^>(result, filter); } AimpActionResult<IAimpDataFilterGroup^>^ AimpDataFilterGroup::AddGroup() { IAIMPMLDataFilterGroup* nativeGroup = nullptr; const ActionResultType result = CheckResult(InternalAimpObject->AddGroup(&nativeGroup)); IAimpDataFilterGroup^ group = nullptr; if (result == ActionResultType::OK && nativeGroup != nullptr) { group = gcnew AimpDataFilterGroup(nativeGroup); } return gcnew AimpActionResult<IAimpDataFilterGroup^>(result, group); } ActionResult AimpDataFilterGroup::Clear() { return ACTION_RESULT(CheckResult(InternalAimpObject->Clear())); } ActionResult AimpDataFilterGroup::Delete(int index) { return ACTION_RESULT(CheckResult(InternalAimpObject->Delete(index))); } int AimpDataFilterGroup::GetChildCount() { return InternalAimpObject->GetChildCount(); } AimpActionResult<IAimpDataFilterGroup^>^ AimpDataFilterGroup::GetFilterGroup(int index) { IAimpDataFilterGroup^ group = nullptr; IAIMPMLDataFilterGroup* child = nullptr; const auto result = CheckResult( InternalAimpObject->GetChild(index, IID_IAIMPMLDataFilterGroup, reinterpret_cast<void**>(&child))); if (result == ActionResultType::OK && child != nullptr) { group = gcnew AimpDataFilterGroup(child); } return gcnew AimpActionResult<IAimpDataFilterGroup^>(result, group); } AimpActionResult<IAimpDataFieldFilter^>^ AimpDataFilterGroup::GetFieldFilter(int index) { IAimpDataFieldFilter^ fieldFilter = nullptr; IAIMPMLDataFieldFilter* child = nullptr; const auto result = CheckResult( InternalAimpObject->GetChild(index, IID_IAIMPMLDataFieldFilter, reinterpret_cast<void**>(&child))); if (result == ActionResultType::OK && child != nullptr) { fieldFilter = gcnew AimpDataFieldFilter(child); } return gcnew AimpActionResult<IAimpDataFieldFilter^>(result, fieldFilter); } void AimpDataFilterGroup::BeginUpdate() { InternalAimpObject->BeginUpdate(); } void AimpDataFilterGroup::EndUpdate() { InternalAimpObject->EndUpdate(); }
4,839
1,522
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*===================================================================== ** ** Source: MoveFileA.c ** ** Purpose: Tests the PAL implementation of the MoveFileA function. ** ** **===================================================================*/ #include <palsuite.h> LPSTR lpSource[4] = {"src_existing.txt", "src_non-existant.txt", "src_dir_existing", "src_dir_non-existant"}; LPSTR lpDestination[4] = {"dst_existing.txt", "dst_non-existant.txt", "dst_dir_existing", "dst_dir_non-existant"}; /* Create all the required test files */ int createExisting(void) { FILE* tempFile = NULL; DWORD dwError; BOOL bRc = FALSE; char szBuffer[100]; /* create the src_existing file */ tempFile = fopen(lpSource[0], "w"); if (tempFile != NULL) { fprintf(tempFile, "MoveFileA test file: src_existing.txt\n"); fclose(tempFile); } else { Trace("ERROR: couldn't create %s\n", lpSource[0]); return FAIL; } /* create the src_dir_existing directory and files */ bRc = CreateDirectoryA(lpSource[2], NULL); if (bRc != TRUE) { Trace("MoveFileA: ERROR: couldn't create \"%s\" because of " "error code %ld\n", lpSource[2], GetLastError()); return FAIL; } memset(szBuffer, 0, 100); sprintf_s(szBuffer, _countof(szBuffer), "%s/test01.txt", lpSource[2]); tempFile = fopen(szBuffer, "w"); if (tempFile != NULL) { fprintf(tempFile, "MoveFileA test file: %s\n", szBuffer); fclose(tempFile); } else { Trace("ERROR[%ld]:MoveFileA couldn't create %s\n", GetLastError(), szBuffer); return FAIL; } memset(szBuffer, 0, 100); sprintf_s(szBuffer, _countof(szBuffer), "%s/test02.txt", lpSource[2]); tempFile = fopen(szBuffer, "w"); if (tempFile != NULL) { fprintf(tempFile, "MoveFileA test file: %s\n", szBuffer); fclose(tempFile); } else { Trace("ERROR[%ld]: couldn't create %s\n", GetLastError(), szBuffer); return FAIL; } /* create the dst_existing file */ tempFile = fopen(lpDestination[0], "w"); if (tempFile != NULL) { fprintf(tempFile, "MoveFileA test file: dst_existing.txt\n"); fclose(tempFile); } else { Trace("ERROR[%ld]:MoveFileA couldn't create \"%s\"\n", GetLastError(), lpDestination[0]); return FAIL; } /* create the dst_dir_existing directory and files */ bRc = CreateDirectoryA(lpDestination[2], NULL); if (bRc != TRUE) { dwError = GetLastError(); Trace("Error[%ld]:MoveFileA: couldn't create \"%s\"\n", GetLastError(), lpDestination[2]); return FAIL; } tempFile = fopen("dst_dir_existing/test01.txt", "w"); if (tempFile != NULL) { fprintf(tempFile, "MoveFileA test file: dst_dir_existing/test01.txt\n"); fclose(tempFile); } else { Trace("ERROR: couldn't create dst_dir_existing/test01.txt\n"); return FAIL; } tempFile = fopen("dst_dir_existing/test02.txt", "w"); if (tempFile != NULL) { fprintf(tempFile, "MoveFileA test file: dst_dir_existing/test02.txt\n"); fclose(tempFile); } else { Trace("ERROR[%ul]: couldn't create dst_dir_existing/test02.txt\n", GetLastError()); return FAIL; } return PASS; } void removeDirectoryHelper(LPSTR dir, int location) { DWORD dwAtt = GetFileAttributesA(dir); if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) ) { if(!RemoveDirectoryA(dir)) { Fail("ERROR: Failed to remove Directory [%s], Error Code [%d], location [%d]\n", dir, GetLastError(), location); } } } void removeFileHelper(LPSTR pfile, int location) { FILE *fp; fp = fopen( pfile, "r"); if (fp != NULL) { if(fclose(fp)) { Fail("ERROR: Failed to close the file [%s], Error Code [%d], location [%d]\n", pfile, GetLastError(), location); } if(!DeleteFileA(pfile)) { Fail("ERROR: Failed to delete file [%s], Error Code [%d], location [%d]\n", pfile, GetLastError(), location); } else { // Trace("Success: deleted file [%S], Error Code [%d], location [%d]\n", wfile, GetLastError(), location); } } } /* remove all created files in preparation for the next test */ void removeAll(void) { char szTemp[40]; DWORD dwAtt; /* get rid of source dirs and files */ removeFileHelper(lpSource[0], 1); removeFileHelper(lpSource[1], 2); dwAtt = GetFileAttributesA(lpSource[2]); if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) ) { sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[2]); removeFileHelper(szTemp, 18); sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[2]); removeFileHelper(szTemp, 19); removeDirectoryHelper(lpSource[2], 103); } else { removeFileHelper(lpSource[2], 17); } dwAtt = GetFileAttributesA(lpSource[3]); if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) ) { sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[3]); removeFileHelper(szTemp, 18); sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[3]); removeFileHelper(szTemp, 19); removeDirectoryHelper(lpSource[3], 103); } else { removeFileHelper(lpSource[3], 17); } /* get rid of destination dirs and files */ dwAtt = GetFileAttributesA(lpDestination[0]); if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) ) { sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[0]); removeFileHelper(szTemp, 18); sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[0]); removeFileHelper(szTemp, 19); removeDirectoryHelper(lpDestination[0], 103); } else { removeFileHelper(lpDestination[0], 17); } dwAtt = GetFileAttributesA(lpDestination[1]); if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) ) { sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[1]); removeFileHelper(szTemp, 18); sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[1]); removeFileHelper(szTemp, 19); removeDirectoryHelper(lpDestination[1], 103); } else { removeFileHelper(lpDestination[1], 17); } dwAtt = GetFileAttributesA(lpDestination[2]); if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) ) { sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[2]); removeFileHelper(szTemp, 18); sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[2]); removeFileHelper(szTemp, 19); removeDirectoryHelper(lpDestination[2], 103); } else { removeFileHelper(lpDestination[2], 17); } dwAtt = GetFileAttributesA(lpDestination[3]); if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) ) { sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[3]); removeFileHelper(szTemp, 18); sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[3]); removeFileHelper(szTemp, 19); removeDirectoryHelper(lpDestination[3], 103); } else { removeFileHelper(lpDestination[3], 17); } } int __cdecl main(int argc, char *argv[]) { BOOL bRc = TRUE; BOOL bSuccess = TRUE; char results[40]; FILE* resultsFile = NULL; int nCounter = 0; int i, j; char tempSource[] = {'t','e','m','p','k','.','t','m','p','\0'}; char tempDest[] = {'t','e','m','p','2','.','t','m','p','\0'}; HANDLE hFile; DWORD result; if (0 != PAL_Initialize(argc,argv)) { return FAIL; } /* read in the expected results to compare with actual results */ memset (results, 0, 20); resultsFile = fopen("expectedresults.txt", "r"); if (resultsFile == NULL) { Fail("MoveFileA ERROR[%ul]: Unable to open \"expectedresults.txt\"\n", GetLastError()); } fgets(results, 20, resultsFile); fclose(resultsFile); /* clean the slate */ removeAll(); if (createExisting() != 0) { removeAll(); } /* lpSource loop */ for (i = 0; i < 4; i++) { /* lpDestination loop */ for (j = 0; j < 4; j++) { bRc = MoveFileA(lpSource[i], lpDestination[j]); if (!( ((bRc == TRUE) && (results[nCounter] == '1')) || ((bRc == FALSE ) && (results[nCounter] == '0')) ) ) { Trace("MoveFileA: FAILED: test[%d][%d]: \"%s\" -> \"%s\"\n", i, j, lpSource[i], lpDestination[j]); bSuccess = FALSE; } /* undo the last move */ removeAll(); createExisting(); nCounter++; } } removeAll(); if (bSuccess == FALSE) { Fail("MoveFileA: Test Failed"); } /* create the temp source file */ hFile = CreateFileA(tempSource, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if( hFile == INVALID_HANDLE_VALUE ) { Fail("Error[%ul]:MoveFileA: CreateFile failed to " "create the file correctly.\n", GetLastError()); } bRc = CloseHandle(hFile); if(!bRc) { Trace("MoveFileA: CloseHandle failed to close the " "handle correctly. ERROR:%u\n",GetLastError()); /* delete the created file */ bRc = DeleteFileA(tempSource); if(!bRc) { Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the" "file correctly.\n", GetLastError()); } Fail(""); } /* set the file attributes to be readonly */ bRc = SetFileAttributesA(tempSource, FILE_ATTRIBUTE_READONLY); if(!bRc) { Trace("MoveFileA: SetFileAttributes failed to set file " "attributes correctly. GetLastError returned %u\n",GetLastError()); /* delete the created file */ bRc = DeleteFileA(tempSource); if(!bRc) { Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the" "file correctly.\n", GetLastError()); } Fail(""); } /* move the file to the new location */ bRc = MoveFileA(tempSource, tempDest); if(!bRc) { /* delete the created file */ bRc = DeleteFileA(tempSource); if(!bRc) { Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the" "file correctly.\n", GetLastError()); } Fail("Error[%ul]:MoveFileA(%S, %S): GetFileAttributes " "failed to get the file's attributes.\n", GetLastError(), tempSource, tempDest); } /* check that the newly moved file has the same file attributes as the original */ result = GetFileAttributesA(tempDest); if(result == 0) { /* delete the created file */ bRc = DeleteFileA(tempDest); if(!bRc) { Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the" "file correctly.\n", GetLastError()); } Fail("Error[%ul]:MoveFileA: GetFileAttributes failed to get " "the file's attributes.\n", GetLastError()); } if((result & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY) { /* delete the newly moved file */ bRc = DeleteFileA(tempDest); if(!bRc) { Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the" "file correctly.\n", GetLastError()); } Fail("Error[%ul]MoveFileA: GetFileAttributes failed to get " "the correct file attributes.\n", GetLastError()); } /* set the file attributes back to normal, to be deleted */ bRc = SetFileAttributesA(tempDest, FILE_ATTRIBUTE_NORMAL); if(!bRc) { /* delete the newly moved file */ bRc = DeleteFileA(tempDest); if(!bRc) { Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the" "file correctly.\n", GetLastError()); } Fail("Error[%ul]:MoveFileA: SetFileAttributes failed to set " "file attributes correctly.\n", GetLastError()); } /* delete the newly moved file */ bRc = DeleteFileA(tempDest); if(!bRc) { Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the" "file correctly.\n", GetLastError()); } PAL_Terminate(); return PASS; }
13,491
4,647
/* ///////////////////////////////////////////////////////////////////////// * File: inetstl/error/exceptions.hpp * * Purpose: Contains the internet_exception class. * * Created: 25th April 2004 * Updated: 10th August 2009 * * Home: http://stlsoft.org/ * * Copyright (c) 2004-2009, Matthew Wilson and Synesis Software * 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(s) of Matthew Wilson and Synesis Software nor the names of * any 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. * * ////////////////////////////////////////////////////////////////////// */ /** \file inetstl/error/exceptions.hpp * * \brief [C++ only] Definition of the inetstl::internet_exception and * exception class and the inetstl::throw_internet_exception_policy * exception policy class * (\ref group__library__error "Error" Library). */ #ifndef INETSTL_INCL_INETSTL_ERROR_HPP_EXCEPTIONS #define INETSTL_INCL_INETSTL_ERROR_HPP_EXCEPTIONS #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION # define INETSTL_VER_INETSTL_ERROR_HPP_EXCEPTIONS_MAJOR 4 # define INETSTL_VER_INETSTL_ERROR_HPP_EXCEPTIONS_MINOR 2 # define INETSTL_VER_INETSTL_ERROR_HPP_EXCEPTIONS_REVISION 1 # define INETSTL_VER_INETSTL_ERROR_HPP_EXCEPTIONS_EDIT 42 #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////// * Compatibility */ /* [DocumentationStatus:Ready] */ /* ///////////////////////////////////////////////////////////////////////// * Includes */ #ifndef INETSTL_INCL_INETSTL_H_INETSTL # include <inetstl/inetstl.h> #endif /* !INETSTL_INCL_INETSTL_H_INETSTL */ #ifndef STLSOFT_INCL_STLSOFT_ERROR_HPP_EXCEPTIONS # include <stlsoft/error/exceptions.hpp> #endif /* !STLSOFT_INCL_STLSOFT_ERROR_HPP_EXCEPTIONS */ #ifndef STLSOFT_INCL_STLSOFT_UTIL_HPP_EXCEPTION_STRING # include <stlsoft/util/exception_string.hpp> #endif /* !STLSOFT_INCL_STLSOFT_UTIL_HPP_EXCEPTION_STRING */ #ifndef INETSTL_OS_IS_WINDOWS # include <errno.h> #endif /* !INETSTL_OS_IS_WINDOWS */ #ifndef STLSOFT_CF_EXCEPTION_SUPPORT # error This file cannot be included when exception-handling is not supported #endif /* !STLSOFT_CF_EXCEPTION_SUPPORT */ /* ///////////////////////////////////////////////////////////////////////// * Namespace */ #ifndef _INETSTL_NO_NAMESPACE # if defined(_STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) /* There is no stlsoft namespace, so must define ::inetstl */ namespace inetstl { # else /* Define stlsoft::inetstl_project */ namespace stlsoft { namespace inetstl_project { # endif /* _STLSOFT_NO_NAMESPACE */ #endif /* !_INETSTL_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * Classes */ /** \brief General exception class for internet-related failures. * * \ingroup group__library__error * */ class internet_exception : public os_exception { /// \name Types /// @{ protected: typedef stlsoft_ns_qual(exception_string) string_type; public: typedef os_exception parent_class_type; #ifdef INETSTL_OS_IS_WINDOWS typedef is_dword_t error_code_type; #else /* ? INETSTL_OS_IS_WINDOWS */ typedef int error_code_type; #endif /* INETSTL_OS_IS_WINDOWS */ typedef internet_exception class_type; /// @} /// \name Construction /// @{ public: ss_explicit_k internet_exception(error_code_type err) : m_reason() , m_errorCode(err) {} internet_exception(class_type const& rhs) : m_reason(rhs.m_reason) , m_errorCode(rhs.m_errorCode) {} internet_exception(char const* reason, error_code_type err) : m_reason(class_type::create_reason_(reason, err)) , m_errorCode(err) {} protected: internet_exception(string_type const& reason, error_code_type err) : m_reason(reason) , m_errorCode(err) {} public: /// Destructor /// /// \note This does not do have any implementation, but is required to placate /// the Comeau and GCC compilers, which otherwise complain about mismatched /// exception specifications between this class and its parent virtual ~internet_exception() stlsoft_throw_0() {} /// @} /// \name Accessors /// @{ public: virtual char const* what() const stlsoft_throw_0() { if(!m_reason.empty()) { return m_reason.c_str(); } else { return "internet failure"; } } /// The error code associated with the exception error_code_type get_error_code() const stlsoft_throw_0() { return m_errorCode; } /// [DEPRECATED] The error code associated with the exception /// /// \deprecated Use get_error_code() instead. error_code_type last_error() const stlsoft_throw_0() { return get_error_code(); } /// [DEPRECATED] The error code associated with the exception /// /// \deprecated Use get_error_code() instead. error_code_type error() const stlsoft_throw_0() { return get_error_code(); } /// @} /// \name Implementation /// @{ private: static string_type create_reason_(char const* reason, error_code_type err) { #ifdef INETSTL_OS_IS_WINDOWS if( err == static_cast<error_code_type>(E_OUTOFMEMORY) || err == static_cast<error_code_type>(ERROR_OUTOFMEMORY) || NULL == reason || '\0' == reason[0]) { return string_type(); } else #endif /* INETSTL_OS_IS_WINDOWS */ { return string_type(reason); } } /// @} /// \name Members /// @{ private: const string_type m_reason; error_code_type m_errorCode; /// @} /// \name Not to be implemented /// @{ private: class_type& operator =(class_type const&); /// @} }; /* ///////////////////////////////////////////////////////////////////////// * Policies */ /** \brief The policy class, which throws a internet_exception class. * * \ingroup group__library__error * */ // [[synesis:class:exception-policy: throw_internet_exception_policy]] struct throw_internet_exception_policy { /// \name Member Types /// @{ public: /// The thrown type typedef internet_exception thrown_type; typedef internet_exception::error_code_type error_code_type; /// @} /// \name Operators /// @{ public: /// Function call operator, taking no parameters void operator ()() const { #ifdef INETSTL_OS_IS_WINDOWS STLSOFT_THROW_X(thrown_type(::GetLastError())); #else /* ? INETSTL_OS_IS_WINDOWS */ STLSOFT_THROW_X(thrown_type(errno)); #endif /* INETSTL_OS_IS_WINDOWS */ } /// Function call operator, taking one parameter void operator ()(error_code_type err) const { STLSOFT_THROW_X(thrown_type(err)); } /// Function call operator, taking two parameters void operator ()(char const* reason, error_code_type err) const { STLSOFT_THROW_X(thrown_type(reason, err)); } /// @} }; /* ////////////////////////////////////////////////////////////////////// */ #ifndef _INETSTL_NO_NAMESPACE # if defined(_STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) } // namespace inetstl # else } // namespace inetstl_project } // namespace stlsoft # endif /* _STLSOFT_NO_NAMESPACE */ #endif /* !_INETSTL_NO_NAMESPACE */ /* ////////////////////////////////////////////////////////////////////// */ #endif /* INETSTL_INCL_INETSTL_ERROR_HPP_EXCEPTIONS */ /* ///////////////////////////// end of file //////////////////////////// */
9,369
3,208
//<Snippet3> using namespace System; void main() { // Define an array of 16-bit integer values. array<Int16>^ values = { Int16::MinValue, Int16::MaxValue, 0xFFF, 12345, -10000 }; // Convert each value to a Decimal. for each (Int16 value in values) { Decimal decValue = value; Console::WriteLine("{0} ({1}) --> {2} ({3})", value, value.GetType()->Name, decValue, decValue.GetType()->Name); } } // The example displays the following output: // -32768 (Int16) --> -32768 (Decimal) // 32767 (Int16) --> 32767 (Decimal) // 4095 (Int16) --> 4095 (Decimal) // 12345 (Int16) --> 12345 (Decimal) // -10000 (Int16) --> -10000 (Decimal) //</Snippet3>
792
303
#include "PanelConfiguration.h" #include "Application.h" #include "ModuleWindow.h" #include "ModuleRender.h" #include "ModuleCamera.h" #include "ModuleInput.h" #include "ModuleTextures.h" #include "ModuleScene.h" #include "ModuleScript.h" #include "ModuleUI.h" #include "ModuleAudioManager.h" #include "imgui.h" #include "Math/MathConstants.h" #define NUMFPS 100 PanelConfiguration::PanelConfiguration() { fps.reserve(NUMFPS); ms.reserve(NUMFPS); } PanelConfiguration::~PanelConfiguration() { } void PanelConfiguration::Draw() { if (!ImGui::Begin("Configuration", &enabled)) { ImGui::End(); return; } if (ImGui::CollapsingHeader("Application")) { UpdateExtrems(); DrawFPSgraph(); DrawMSgraph(); DrawMemoryStats(); } if (ImGui::CollapsingHeader("Window")) { App->window->DrawGUI(); } if (ImGui::CollapsingHeader("Camera")) { App->camera->DrawGUI(); } if (ImGui::CollapsingHeader("Render")) { App->renderer->DrawGUI(); } if (ImGui::CollapsingHeader("Input")) { App->input->DrawGUI(); } if (ImGui::CollapsingHeader("Textures")) { App->textures->DrawGUI(); } if (ImGui::CollapsingHeader("Scene")) { App->scene->DrawGUI(); } if (ImGui::CollapsingHeader("UI")) { App->ui->DrawGUI(); } if (ImGui::CollapsingHeader("Audio")) { App->audioManager->DrawGUI(); } if (ImGui::CollapsingHeader("Scripts")) { App->scripting->DrawGUI(); } if (ImGui::CollapsingHeader("Skybox")) { App->renderer->DrawSkyboxGUI(); } ImGui::End(); } void PanelConfiguration::DrawFPSgraph() const { if (fps.size() == 0) return; char avg[32]; char showmin[32]; sprintf_s(avg, "%s%.2f", "avg:", totalfps / fps.size()); sprintf_s(showmin, "%s%.2f", "min:", minfps); ImGui::PlotHistogram("FPS", &fps[0], fps.size(), 0, avg, 0.0f, 300.0f, ImVec2(0, 80)); ImGui::Text(showmin); } void PanelConfiguration::DrawMSgraph() const { if (ms.size() == 0) return; char avg[32]; char showmax[32]; sprintf_s(avg, "%s%.2f", "avg:", totalms / ms.size()); sprintf_s(showmax, "%s%.2f", "max:", maxms); ImGui::PlotHistogram("MS", &ms[0], ms.size(), 0, avg, 0.0f, 20.0f, ImVec2(0, 80)); ImGui::Text(showmax); } void PanelConfiguration::AddFps(float dt) { if (dt == 0.0f) return; if (fps.size() == NUMFPS) { totalfps -= fps.back(); fps.pop_back(); totalms -= ms.back(); ms.pop_back(); } float newfps = 1 / dt; float newms = dt * 1000; fps.insert(fps.begin(), newfps); ms.insert(ms.begin(), newms); totalfps += newfps; totalms += newms; } void PanelConfiguration::UpdateExtrems() { minfps = 1000.f; maxms = 0.f; for (unsigned i = 0; i < fps.size(); i++) { minfps = MIN(minfps, fps[i]); maxms = MAX(maxms, ms[i]); } } void PanelConfiguration::DrawMemoryStats() const { //sMStats stats = m_getMemoryStatistics(); //ImGui::Text("Total Reported Mem: %u", stats.totalReportedMemory); //ImGui::Text("Total Actual Mem: %u", stats.totalActualMemory); //ImGui::Text("Peak Reported Mem: %u", stats.peakReportedMemory); //ImGui::Text("Peak Actual Mem: %u", stats.peakActualMemory); //ImGui::Text("Accumulated Reported Mem: %u", stats.accumulatedReportedMemory); //ImGui::Text("Accumulated Actual Mem: %u", stats.accumulatedActualMemory); //ImGui::Text("Accumulated Alloc Unit Count: %u", stats.accumulatedAllocUnitCount); //ImGui::Text("Total Alloc Unit Count: %u", stats.totalAllocUnitCount); //ImGui::Text("Peak Alloc Unit Count: %u", stats.peakAllocUnitCount); }
3,434
1,469
int phoneCall(int min1, int min2_10, int min11, int s) { if (s < min1) { return 0; } for (int i = 2; i <= 10; i++) { if (s < min1 + min2_10 * (i - 1)) { return i - 1; } } return 10 + (s - min1 - min2_10 * 9) / min11; }
248
130
/* * Copyright (c) 2015-2019 Dubalu LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "convex.h" #include <algorithm> #include <cmath> void Convex::simplify() { if (!simplified) { // Sort circles. std::sort(circles.begin(), circles.end(), std::less<>()); sign = Sign::ZERO; for (auto it = circles.begin(); it != circles.end(); ++it) { sign = static_cast<Convex::Sign>(static_cast<uint8_t>(sign) & static_cast<uint8_t>(it->constraint.sign)); for (auto it_n = it + 1; it_n != circles.end(); ) { auto gamma = std::acos(it->constraint.center * it_n->constraint.center); if (gamma >= (it->constraint.arcangle + it_n->constraint.arcangle)) { // Empty intersection. circles.clear(); sign = Sign::ZERO; simplified = true; return; } // Deleting redundants circles. if ((it_n->constraint.arcangle - it->constraint.arcangle) >= gamma) { it_n = circles.erase(it_n); } else { ++it_n; } } } simplified = true; } } int Convex::insideVertex(const Cartesian& v) const noexcept { for (const auto& circle : circles) { if (!HTM::insideVertex_Constraint(v, circle.constraint)) { return 0; } } return 1; } bool Convex::intersectCircles(const Constraint& bounding_circle) const { for (const auto& circle : circles) { if (!HTM::intersectConstraints(circle.constraint, bounding_circle)) { return false; } } return true; } TypeTrixel Convex::verifyTrixel(const Cartesian& v0, const Cartesian& v1, const Cartesian& v2) const { int F = ( (insideVertex(v0) != 0 ? 1 : 0) + (insideVertex(v1) != 0 ? 1 : 0) + (insideVertex(v2) != 0 ? 1 : 0) ); switch (F) { case 0: { // If bounding circle doesnot intersect all circles, the trixel is considered OUTSIDE. if (!intersectCircles(HTM::getBoundingCircle(v0, v1, v2))) { return TypeTrixel::OUTSIDE; } if (sign == Sign::NEG) { // In this point might have very complicated patterns inside the triangle, so we just assume partial to be certain. return TypeTrixel::PARTIAL; } // For positive, zero and mixed convex. auto it = circles.begin(); const auto& smallest_c = it->constraint; // The smallest constraint intersect with an edge of trixel (v0, v1, v2). if (HTM::intersectConstraint_EdgeTrixel(smallest_c, v0, v1, v2)) { const auto it_e = circles.end(); // Any other positive constraint not intersect with an enge of trixel (v0, v1, v2). for (++it; it != it_e && it->constraint.sign == Constraint::Sign::POS; ++it) { if (!HTM::intersectConstraint_EdgeTrixel(it->constraint, v0, v1, v2)) { // Constraint center inside trixel (v0, v1, v2). if (HTM::insideVertex_Trixel(it->constraint.center, v0, v1, v2)) { return TypeTrixel::PARTIAL; } // The triangle is inside of constraint. if (HTM::insideVertex_Constraint(v0, it->constraint)) { return TypeTrixel::PARTIAL; } return TypeTrixel::OUTSIDE; } } // In this point for mixed convex might have very complicated patterns inside the triangle, so we just assume partial to be certain. return TypeTrixel::PARTIAL; } if (sign == Sign::POS || sign == Sign::ZERO) { // Constraint center inside trixel (v0, v1, v2). if (HTM::insideVertex_Trixel(smallest_c.center, v0, v1, v2)) { return TypeTrixel::PARTIAL; } // The triangle is inside of constraint. if (HTM::insideVertex_Constraint(v0, smallest_c)) { return TypeTrixel::PARTIAL; } return TypeTrixel::OUTSIDE; } // In this point might have very complicated patterns inside the triangle, so we just assume partial to be certain. return TypeTrixel::PARTIAL; } case 1: case 2: return TypeTrixel::PARTIAL; case 3: { // For negative or mixed convex we need to test further. if (sign == Sign::NEG || sign == Sign::MIXED) { for (const auto& circle : circles) { if (circle.constraint.sign == Constraint::Sign::NEG) { // Constraint center inside trixel (there is a hole). if (HTM::insideVertex_Trixel(circle.constraint.center, v0, v1, v2)) { return TypeTrixel::PARTIAL; } // Negative constraint intersect with a side. if (HTM::intersectConstraint_EdgeTrixel(circle.constraint, v0, v1, v2)) { return TypeTrixel::PARTIAL; } } } } return TypeTrixel::FULL; } default: return TypeTrixel::OUTSIDE; } } void Convex::lookupTrixel(const Cartesian& v0, const Cartesian& v1, const Cartesian& v2, std::string name, trixel_data& data, uint8_t level) const { // Finish the recursion. if (level == data.max_level) { data.aux_trixels.push_back(std::move(name)); return; } auto w2 = HTM::midPoint(v0, v1); auto w0 = HTM::midPoint(v1, v2); auto w1 = HTM::midPoint(v2, v0); TypeTrixel type_trixels[4] = { verifyTrixel(v0, w2, w1), verifyTrixel(v1, w0, w2), verifyTrixel(v2, w1, w0), verifyTrixel(w0, w1, w2) }; // Number of full subtrixels. int F = ( (type_trixels[0] == TypeTrixel::FULL ? 1 : 0) + (type_trixels[1] == TypeTrixel::FULL ? 1 : 0) + (type_trixels[2] == TypeTrixel::FULL ? 1 : 0) + (type_trixels[3] == TypeTrixel::FULL ? 1 : 0) ); // Finish the recursion. if (F == 4) { data.trixels.push_back(std::move(name)); return; } ++level; switch (type_trixels[0]) { case TypeTrixel::FULL: data.trixels.push_back(name + "0"); break; case TypeTrixel::PARTIAL: lookupTrixel(v0, w2, w1, name + "0", data, level); break; default: break; } switch (type_trixels[1]) { case TypeTrixel::FULL: data.trixels.push_back(name + "1"); break; case TypeTrixel::PARTIAL: lookupTrixel(v1, w0, w2, name + "1", data, level); break; default: break; } switch (type_trixels[2]) { case TypeTrixel::FULL: data.trixels.push_back(name + "2"); break; case TypeTrixel::PARTIAL: lookupTrixel(v2, w1, w0, name + "2", data, level); break; default: break; } switch (type_trixels[3]) { case TypeTrixel::FULL: data.trixels.push_back(name + "3"); break; case TypeTrixel::PARTIAL: lookupTrixel(w0, w1, w2, name + "3", data, level); break; default: break; } } void Convex::lookupTrixel(const Cartesian& v0, const Cartesian& v1, const Cartesian& v2, uint64_t id, range_data& data, uint8_t level) const { // Finish the recursion. if (level == data.max_level) { HTM::insertGreaterRange(data.aux_ranges, HTM::getRange(id, level)); return; } auto w2 = HTM::midPoint(v0, v1); auto w0 = HTM::midPoint(v1, v2); auto w1 = HTM::midPoint(v2, v0); TypeTrixel type_trixels[4] = { verifyTrixel(v0, w2, w1), verifyTrixel(v1, w0, w2), verifyTrixel(v2, w1, w0), verifyTrixel(w0, w1, w2) }; // Number of full subtrixels. int F = ( (type_trixels[0] == TypeTrixel::FULL ? 1 : 0) + (type_trixels[1] == TypeTrixel::FULL ? 1 : 0) + (type_trixels[2] == TypeTrixel::FULL ? 1 : 0) + (type_trixels[3] == TypeTrixel::FULL ? 1 : 0) ); // Finish the recursion. if (F == 4) { HTM::insertGreaterRange(data.ranges, HTM::getRange(id, level)); return; } ++level; id <<= 2; switch (type_trixels[0]) { case TypeTrixel::FULL: HTM::insertGreaterRange(data.ranges, HTM::getRange(id, level)); break; case TypeTrixel::PARTIAL: lookupTrixel(v0, w2, w1, id, data, level); break; default: break; } switch (type_trixels[1]) { case TypeTrixel::FULL: HTM::insertGreaterRange(data.ranges, HTM::getRange(id + 1, level)); break; case TypeTrixel::PARTIAL: lookupTrixel(v1, w0, w2, id + 1, data, level); break; default: break; } switch (type_trixels[2]) { case TypeTrixel::FULL: HTM::insertGreaterRange(data.ranges, HTM::getRange(id + 2, level)); break; case TypeTrixel::PARTIAL: lookupTrixel(v2, w1, w0, id + 2, data, level); break; default: break; } switch (type_trixels[3]) { case TypeTrixel::FULL: HTM::insertGreaterRange(data.ranges, HTM::getRange(id + 3, level)); break; case TypeTrixel::PARTIAL: lookupTrixel(w0, w1, w2, id + 3, data, level); break; default: break; } } std::string Convex::toWKT() const { std::string wkt("CONVEX"); wkt.append(to_string()); return wkt; } std::string Convex::to_string() const { if (circles.empty()) { return std::string(" EMPTY"); } std::string str("("); for (const auto& constraint : circles) { auto str_constraint = constraint.to_string(); str.reserve(str.length() + str_constraint.length() + 1); str.append(str_constraint).push_back(','); } str.back() = ')'; return str; } std::vector<std::string> Convex::getTrixels(bool partials, double error) const { if (error < HTM_MIN_ERROR || error > HTM_MAX_ERROR) { THROW(HTMError, "Error must be in [{}, {}]", HTM_MIN_ERROR, HTM_MAX_ERROR); } trixel_data data(partials, HTM_MAX_LEVEL); error = error * circles.begin()->constraint.radius; for (size_t i = 0; i < HTM_MAX_LEVEL; ++i) { if (ERROR_NIVEL[i] < error) { data.max_level = i; break; } } if (verifyTrixel(start_vertices[start_trixels[0].v0], start_vertices[start_trixels[0].v1], start_vertices[start_trixels[0].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[0].v0], start_vertices[start_trixels[0].v1], start_vertices[start_trixels[0].v2], start_trixels[0].name, data, 0); } if (verifyTrixel(start_vertices[start_trixels[1].v0], start_vertices[start_trixels[1].v1], start_vertices[start_trixels[1].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[1].v0], start_vertices[start_trixels[1].v1], start_vertices[start_trixels[1].v2], start_trixels[1].name, data, 0); } if (verifyTrixel(start_vertices[start_trixels[2].v0], start_vertices[start_trixels[2].v1], start_vertices[start_trixels[2].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[2].v0], start_vertices[start_trixels[2].v1], start_vertices[start_trixels[2].v2], start_trixels[2].name, data, 0); } if (verifyTrixel(start_vertices[start_trixels[3].v0], start_vertices[start_trixels[3].v1], start_vertices[start_trixels[3].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[3].v0], start_vertices[start_trixels[3].v1], start_vertices[start_trixels[3].v2], start_trixels[3].name, data, 0); } if (verifyTrixel(start_vertices[start_trixels[4].v0], start_vertices[start_trixels[4].v1], start_vertices[start_trixels[4].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[4].v0], start_vertices[start_trixels[4].v1], start_vertices[start_trixels[4].v2], start_trixels[4].name, data, 0); } if (verifyTrixel(start_vertices[start_trixels[5].v0], start_vertices[start_trixels[5].v1], start_vertices[start_trixels[5].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[5].v0], start_vertices[start_trixels[5].v1], start_vertices[start_trixels[5].v2], start_trixels[5].name, data, 0); } if (verifyTrixel(start_vertices[start_trixels[6].v0], start_vertices[start_trixels[6].v1], start_vertices[start_trixels[6].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[6].v0], start_vertices[start_trixels[6].v1], start_vertices[start_trixels[6].v2], start_trixels[6].name, data, 0); } if (verifyTrixel(start_vertices[start_trixels[7].v0], start_vertices[start_trixels[7].v1], start_vertices[start_trixels[7].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[7].v0], start_vertices[start_trixels[7].v1], start_vertices[start_trixels[7].v2], start_trixels[7].name, data, 0); } return data.getTrixels(); } std::vector<range_t> Convex::getRanges(bool partials, double error) const { if (error < HTM_MIN_ERROR || error > HTM_MAX_ERROR) { THROW(HTMError, "Error must be in [{}, {}]", HTM_MIN_ERROR, HTM_MAX_ERROR); } range_data data(partials, HTM_MAX_LEVEL); error = error * circles.begin()->constraint.radius; for (size_t i = 0; i < HTM_MAX_LEVEL; ++i) { if (ERROR_NIVEL[i] < error) { data.max_level = i; break; } } if (verifyTrixel(start_vertices[start_trixels[0].v0], start_vertices[start_trixels[0].v1], start_vertices[start_trixels[0].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[0].v0], start_vertices[start_trixels[0].v1], start_vertices[start_trixels[0].v2], start_trixels[0].id, data, 0); } if (verifyTrixel(start_vertices[start_trixels[1].v0], start_vertices[start_trixels[1].v1], start_vertices[start_trixels[1].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[1].v0], start_vertices[start_trixels[1].v1], start_vertices[start_trixels[1].v2], start_trixels[1].id, data, 0); } if (verifyTrixel(start_vertices[start_trixels[2].v0], start_vertices[start_trixels[2].v1], start_vertices[start_trixels[2].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[2].v0], start_vertices[start_trixels[2].v1], start_vertices[start_trixels[2].v2], start_trixels[2].id, data, 0); } if (verifyTrixel(start_vertices[start_trixels[3].v0], start_vertices[start_trixels[3].v1], start_vertices[start_trixels[3].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[3].v0], start_vertices[start_trixels[3].v1], start_vertices[start_trixels[3].v2], start_trixels[3].id, data, 0); } if (verifyTrixel(start_vertices[start_trixels[4].v0], start_vertices[start_trixels[4].v1], start_vertices[start_trixels[4].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[4].v0], start_vertices[start_trixels[4].v1], start_vertices[start_trixels[4].v2], start_trixels[4].id, data, 0); } if (verifyTrixel(start_vertices[start_trixels[5].v0], start_vertices[start_trixels[5].v1], start_vertices[start_trixels[5].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[5].v0], start_vertices[start_trixels[5].v1], start_vertices[start_trixels[5].v2], start_trixels[5].id, data, 0); } if (verifyTrixel(start_vertices[start_trixels[6].v0], start_vertices[start_trixels[6].v1], start_vertices[start_trixels[6].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[6].v0], start_vertices[start_trixels[6].v1], start_vertices[start_trixels[6].v2], start_trixels[6].id, data, 0); } if (verifyTrixel(start_vertices[start_trixels[7].v0], start_vertices[start_trixels[7].v1], start_vertices[start_trixels[7].v2]) != TypeTrixel::OUTSIDE) { lookupTrixel(start_vertices[start_trixels[7].v0], start_vertices[start_trixels[7].v1], start_vertices[start_trixels[7].v2], start_trixels[7].id, data, 0); } return data.getRanges(); } std::vector<Cartesian> Convex::getCentroids() const { // FIXME: Efficient way for calculate centroids for a Convex. return std::vector<Cartesian>(); }
15,718
6,930
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systemsยฎ. 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 "jiface.hpp" #include "dadfs.hpp" #include "eclhelper.hpp" #include "thspill.ipp" class SpillActivityMaster : public CMasterActivity { Owned<IFileDescriptor> fileDesc; StringArray clusters; __int64 recordsProcessed; Owned<IDistributedFile> file; StringAttr fileName; public: SpillActivityMaster(CMasterGraphElement *info) : CMasterActivity(info) { recordsProcessed = 0; } virtual void init() { CMasterActivity::init(); IHThorSpillArg *helper = (IHThorSpillArg *)queryHelper(); IArrayOf<IGroup> groups; OwnedRoxieString helperFileName = helper->getFileName(); StringBuffer expandedFileName; queryThorFileManager().addScope(container.queryJob(), helperFileName, expandedFileName, true); fileName.set(expandedFileName); fillClusterArray(container.queryJob(), fileName, clusters, groups); fileDesc.setown(queryThorFileManager().create(container.queryJob(), fileName, clusters, groups, true, TDWnoreplicate+TDXtemporary)); IPropertyTree &props = fileDesc->queryProperties(); bool blockCompressed=false; void *ekey; size32_t ekeylen; helper->getEncryptKey(ekeylen,ekey); if (ekeylen) { memset(ekey,0,ekeylen); free(ekey); props.setPropBool("@encrypted", true); blockCompressed = true; } else if (0 != (helper->getFlags() & TDWnewcompress) || 0 != (helper->getFlags() & TDXcompress)) blockCompressed = true; if (blockCompressed) props.setPropBool("@blockCompressed", true); if (0 != (helper->getFlags() & TDXgrouped)) fileDesc->queryProperties().setPropBool("@grouped", true); props.setProp("@kind", "flat"); if (container.queryOwner().queryOwner() && (!container.queryOwner().isGlobal())) // I am in a child query { // do early, because this will be local act. and will not come back to master until end of owning graph. container.queryTempHandler()->registerFile(fileName, container.queryOwner().queryGraphId(), helper->getTempUsageCount(), TDXtemporary & helper->getFlags(), getDiskOutputKind(helper->getFlags()), &clusters); queryThorFileManager().publish(container.queryJob(), fileName, *fileDesc); } } virtual void serializeSlaveData(MemoryBuffer &dst, unsigned slave) { IHThorSpillArg *helper = (IHThorSpillArg *)queryHelper(); IPartDescriptor *partDesc = fileDesc->queryPart(slave); partDesc->serialize(dst); dst.append(helper->getTempUsageCount()); } virtual void done() { CMasterActivity::done(); if (!container.queryOwner().queryOwner() || container.queryOwner().isGlobal()) // I am in a child query { IHThorSpillArg *helper = (IHThorSpillArg *)queryHelper(); container.queryTempHandler()->registerFile(fileName, container.queryOwner().queryGraphId(), helper->getTempUsageCount(), TDXtemporary & helper->getFlags(), getDiskOutputKind(helper->getFlags()), &clusters); IPropertyTree &props = fileDesc->queryProperties(); props.setPropInt64("@recordCount", recordsProcessed); queryThorFileManager().publish(container.queryJob(), fileName, *fileDesc); } } virtual void slaveDone(size32_t slaveIdx, MemoryBuffer &mb) { if (mb.length()) // if 0 implies aborted out from this slave. { rowcount_t slaveProcessed; mb.read(slaveProcessed); recordsProcessed += slaveProcessed; offset_t size, physicalSize; mb.read(size); mb.read(physicalSize); unsigned fileCrc; mb.read(fileCrc); CDateTime modifiedTime(mb); StringBuffer timeStr; modifiedTime.getString(timeStr); IPartDescriptor *partDesc = fileDesc->queryPart(slaveIdx); IPropertyTree &props = partDesc->queryProperties(); props.setPropInt64("@size", size); props.setPropInt64("@recordCount", slaveProcessed); if (fileDesc->isCompressed()) props.setPropInt64("@compressedSize", physicalSize); props.setPropInt("@fileCrc", fileCrc); props.setProp("@modified", timeStr.str()); } } }; CActivityBase *createSpillActivityMaster(CMasterGraphElement *info) { return new SpillActivityMaster(info); }
5,324
1,482
/* * Problem: If a three-digit number is input through the keyboard, write a program to * calculate the sum of its digits. (Hint: Use the modulus operator %) * * Example * Case (1) * i/p: 369 * o/p: 18 * * Case (2) * i/p: 999 * o/p: 27 */ #include <iostream> using namespace std; int main() { // Declare all the variables int threeDigitNumber; int singleDigit, sum = 0; // Take the inputs from the user cin >> threeDigitNumber; // Extract the last most digit singleDigit = threeDigitNumber % 10; sum += singleDigit; // Add it to the sum // Remove the last most digit // Three digit number -> two digit number threeDigitNumber /= 10; // This is extracting the 2nd digit from the two digit number singleDigit = threeDigitNumber % 10; sum += singleDigit; // Add it to the sum // Remove the last most digit // Two digit number -> one digit number threeDigitNumber /= 10; sum += threeDigitNumber; // Add it to the sum // Print the values of the variables on display cout << sum << endl; return 0; }
1,102
361