blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
77f5545c72223029be66419b5f91660641522577
e73121fcfcc4df2e7092a82f4810ce9615e9dd83
/Codeforces/Cormen --- The Best Friend Of a Man.cpp
a27d4eb99aa987fe2d92b35cae113e70ec18bee0
[]
no_license
Redwanuzzaman/Online-Judge-Problem-Solutions
1aba5eda26a03ed8cafaf6281618bf13bea7699b
f2f4ccac708bd49e825f2788da886bf434523d3c
refs/heads/master
2022-08-29T04:10:31.084874
2022-08-14T18:20:30
2022-08-14T18:20:30
142,601,682
0
0
null
null
null
null
UTF-8
C++
false
false
489
cpp
Cormen --- The Best Friend Of a Man.cpp
//Rechecking #include <bits/stdc++.h> using namespace std; int main() { int n, k, sum = 0, tmp, dif; cin >> n >> k; int arr[n+2]; for(int i = 0; i < n; i++) cin >> arr[i]; for(int i = 1; i < n; i++) { tmp = arr[i] + arr[i-1]; if(tmp < k) { dif = k - tmp; sum += dif; arr[i] += dif; } else continue; } cout << sum << endl; for(int i = 0; i < n; i++) cout << arr[i] << " "; }
8650f9d1647f67f875a03dcb32491264156d0c5d
31e417531ed8dfc2f49db0626aa2694c3221f39d
/Synchronisation.ino
19538e02aac0802879f7ad6ca60bb213b98416bc
[]
no_license
DmitriySM/C_code_sample_embedded
c5c1899cc05a2151d5b3aa09caa16b7e49eedb7c
0814253176f9e491ca2830138cc71e023f17e8f7
refs/heads/master
2020-05-22T08:54:47.496205
2019-05-12T18:35:14
2019-05-12T18:35:14
186,289,514
0
0
null
null
null
null
UTF-8
C++
false
false
4,259
ino
Synchronisation.ino
char buffer[100]; int servo1pos; void syncWithPC() { boolean communicationComplete = false; char str[100]; int i = 0; while (!backFlag) { while (ReceivedChar != '\n') { if ( backFlag == true) break; if (in_char) { in_char = 0; str[i] = ReceivedChar; i++; } } UCSR0B |= ( 0 << RXCIE0) | ( 0 << TXCIE0); // Disable TX RX interrupts if (backFlag == true) { backFlag == false; state = sTime; displayMenu(); return; } //Serial.println(readString); //see what was received String readString = String(str); int commaIndex = readString.indexOf(' '); String firstValue = readString.substring(0, commaIndex); servo1pos = firstValue.toInt(); switch (servo1pos) { case 150: /*Serial.println(F("Set personal data..."));*/ delay(30); set_personal(readString); break; case 254: /*Serial.println(F("Set time")); */set_time(readString); break; case 222: readString = ""; /*Serial.println(F("erase memory"));*/ eraseMemory(); break; case 133: { //Serial.println("Fetching data"); delay(25); fetchingData(); readString = ""; state = sTime; return; } case 111: readString = ""; /*Serial.println(F("Return!"));*/ readString = ""; state = sTime; displayMenu(); return; } readString = ""; UCSR0B |= ( 1 << RXCIE0) | ( 1 << TXCIE0); // Disable TX RX interrupts } //очистим строку communicationComplete = false; state = sTime; return; } // Serial.end(); //} void set_time(String str) { int hours, minutes, seconds; char hours_c[5]; char minutes_c[5]; char seconds_c[5]; char dayOfWeek_c[5]; char day_c[5]; char month_c[5]; char year_c[5]; int count_time = 0; str.toCharArray(buffer, 30); char* command = strtok(buffer, ","); char* separator = strchr(command, ':'); char* token; token = strtok(separator, ":"); while (token != 0) { switch (count_time) { case 0: strncpy(hours_c, token, 5); break; case 1: strncpy(minutes_c, token, 5); break; case 2: strncpy(seconds_c, token, 5); break; case 3: strncpy(dayOfWeek_c, token, 5); break; case 4: strncpy(day_c, token, 5); break; case 5: strncpy(month_c, token, 5); break; case 6: strncpy(year_c, token, 5); break; } ++count_time; token = strtok(NULL, ":"); } setDS3232time(atoi(seconds_c), atoi(minutes_c), atoi(hours_c), atoi(dayOfWeek_c), atoi(day_c), atoi(month_c), atoi(year_c)); delay(5); //queue_display(); } void set_personal(String str) { struct { char uName[6]; char uWeight[5]; char uHeight[5]; char uHR[5]; char uDocDate[11]; } personal_data_struct; str.toCharArray(buffer, 100); //Serial.println(buffer); // printing buffer int count_personal = 0; char* command = strtok(buffer, ","); //char uName[20], uWeight[5], uHR[5], uDocDate[11]; char* separator = strchr(command, ':'); char* token; token = strtok(separator, ":"); while (token != 0) { switch (count_personal) { case 0: strcpy(personal_data_struct.uName, token); break; case 1: strcpy(personal_data_struct.uHeight, token); break; case 2: strcpy(personal_data_struct.uWeight, token); break; case 3: strcpy(personal_data_struct.uHR, token); break; case 4: strcpy(personal_data_struct.uDocDate, token); break; } ++count_personal; token = strtok(NULL, ":"); } eeprom_write_block(personal_data_struct.uName, &Ep.user_name, sizeof(personal_data_struct.uName)); eeprom_busy_wait(); eeprom_write_block(personal_data_struct.uHR, &Ep.user_heartRate, 4); eeprom_busy_wait(); eeprom_write_block(personal_data_struct.uDocDate, &Ep.doctor_Date , sizeof(personal_data_struct.uDocDate)); eeprom_busy_wait(); eeprom_write_block(personal_data_struct.uWeight, &Ep.user_weight, 4); eeprom_busy_wait(); eeprom_write_block(personal_data_struct.uHeight, &Ep.user_height, 4); eeprom_busy_wait(); //Serial.println(F("Personal data is set")); delay(30); } void eraseMemory() { EraseEEPROM(); wkCounter = 0; eeprom_write_word(&Ep.wkCount_backup, wkCounter); eeprom_busy_wait(); }
ee5915bf6470b3cf7d10b62df4c0c1e989de328a
d86b6c6d4a2f099b4689e8fd5524c128ce603941
/CatMullRomSpline.h
d77e4b10394eea06a18a9d3bfb6d21f3b4ef7a5f
[]
no_license
nikodems/tools-programming
931f874b4c37a42152c8edcec107c75267ac4dba
29476aa0e967a98baad7b268e85549999c1770fe
refs/heads/master
2022-11-13T16:21:13.163141
2020-07-08T17:11:45
2020-07-08T17:11:45
278,148,829
0
0
null
null
null
null
UTF-8
C++
false
false
466
h
CatMullRomSpline.h
#ifndef _CAT_MULL_ROM_SPLINE_H #define _CAT_MULL_ROM_SPLINE_H #include <d3d11.h> #include <SimpleMath.h> #include "SceneObject.h" #include <vector> #include <algorithm> class CatMullRomSpline { public: CatMullRomSpline(); ~CatMullRomSpline(); std::vector<std::vector<SceneObject>> FindAIObjects(std::vector<SceneObject> sceneGraph); std::vector<DirectX::SimpleMath::Vector3> CalcPoints(std::vector<SceneObject> pathVector); }; #endif _CAT_MULL_ROM_SPLINE_H
eff2e89570cc898b0ab9ba2dcf77be236c8d7d19
b9bd6891231d2c78d058db5d19571975424e7376
/Array/1.Sort Colors.cpp
0a75933d941a3e56253bddf62673b78663d78aba
[]
no_license
suresh213/Dsa-practice
7f70aa318638cef327b3d695dd0acb3b4b76db63
e1031f734ebe4f4127bddb3b2c6d4065ef1c894d
refs/heads/master
2023-06-29T18:32:30.542208
2021-08-06T18:52:52
2021-08-06T18:52:52
387,693,096
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
1.Sort Colors.cpp
//Time complexity: o(nlogn) using merge sort //Time complexity: o(n) count 0,1,2 and make while to to rearrange; //Time complexity: o(n) //Single traversal void sortColors(vector<int>& nums) { int start=0,mid=0,end=nums.size()-1; while(mid<=end){ if(nums[mid]==0){ swap(nums[start++],nums[mid++]); } else if(nums[mid]==1){ mid++; } else{ swap(nums[mid],nums[end--]); } } }
0aaaac1fde81719eb736537ef6c78333f8d7e8c4
f34b5a529e2fa17b5d83a1e4a11115d591414ffa
/lib/Implementation/aerosol_extinction_log_test.cc
b78f4a5abfac4d407197ff23e65b8ec15ab99210
[]
no_license
ReFRACtor/framework
89917d05e22dd031e12d12389157eb24cebeaada
882e13c3e94e6faa1281a0445abc0e08b2f8bf30
refs/heads/master
2022-12-08T17:12:49.696855
2022-11-28T23:30:50
2022-11-28T23:30:50
98,920,384
4
7
null
null
null
null
UTF-8
C++
false
false
872
cc
aerosol_extinction_log_test.cc
#include "aerosol_extinction_log.h" #include "met_data_fixture.h" #include "unit_test_support.h" using namespace FullPhysics; using namespace blitz; BOOST_FIXTURE_TEST_SUITE(aerosol_extinction_log, MetDataFixture) BOOST_AUTO_TEST_CASE(basic) { // Arrays defining coeffs blitz::Array<double, 1> aext(20); aext = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20; // Check that the mapped_state of aext matches what we put in AerosolExtinctionLog aer_water_log = AerosolExtinctionLog(pressure, aext, "Water"); BOOST_CHECK_MATRIX_CLOSE_TOL(aer_water_log.aerosol_extinction().value(), aext, 1e-14); // Check that coefficients are stored in log within SubStateVectorArray for(int j = 0; j < aext.rows(); j++) { BOOST_CHECK_CLOSE(aer_water_log.coefficient().value()(j), log(aext(j)), 1e-8); } } BOOST_AUTO_TEST_SUITE_END()
175d06a7bc0a58f46b92f28e2d4c60719d1d45d6
a181e4c65ccef369d4ab7e182e2818aa622debc1
/yact/stub_dlls/msacm32_stub/msacm32.cpp
9153fd0b959ebfa3039a609f8ea1ebb26cd42ef1
[]
no_license
c1p31065/Win86emu
259c32eb5bac1ed9c4f5ceebe2ca0aa07fdf4843
71c723fcab44d5aae3b6b3c86c87154ad3c4abb5
refs/heads/master
2021-12-02T18:24:51.564748
2014-02-06T14:12:11
2014-02-06T14:12:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,451
cpp
msacm32.cpp
#include "dllstub_def.h" static const char DLL_NAME[]="msacm32.nt.dll"; DEFINE_FUNC5(DriverProc) DEFINE_FUNC9(XRegThunkEntry) DEFINE_FUNC5(acmDriverAddA) DEFINE_FUNC5(acmDriverAddW) DEFINE_FUNC2(acmDriverClose) DEFINE_FUNC3(acmDriverDetailsA) DEFINE_FUNC3(acmDriverDetailsW) DEFINE_FUNC3(acmDriverEnum) DEFINE_FUNC3(acmDriverID) DEFINE_FUNC4(acmDriverMessage) DEFINE_FUNC3(acmDriverOpen) DEFINE_FUNC3(acmDriverPriority) DEFINE_FUNC2(acmDriverRemove) DEFINE_FUNC1(acmFilterChooseA) DEFINE_FUNC1(acmFilterChooseW) DEFINE_FUNC3(acmFilterDetailsA) DEFINE_FUNC3(acmFilterDetailsW) DEFINE_FUNC5(acmFilterEnumA) DEFINE_FUNC5(acmFilterEnumW) DEFINE_FUNC3(acmFilterTagDetailsA) DEFINE_FUNC3(acmFilterTagDetailsW) DEFINE_FUNC5(acmFilterTagEnumA) DEFINE_FUNC5(acmFilterTagEnumW) DEFINE_FUNC1(acmFormatChooseA) DEFINE_FUNC1(acmFormatChooseW) DEFINE_FUNC3(acmFormatDetailsA) DEFINE_FUNC3(acmFormatDetailsW) DEFINE_FUNC5(acmFormatEnumA) DEFINE_FUNC5(acmFormatEnumW) DEFINE_FUNC5(acmFormatSuggest) DEFINE_FUNC3(acmFormatTagDetailsA) DEFINE_FUNC3(acmFormatTagDetailsW) DEFINE_FUNC5(acmFormatTagEnumA) DEFINE_FUNC5(acmFormatTagEnumW) DEFINE_FUNC0(acmGetVersion) DEFINE_FUNC6(acmMessage32) DEFINE_FUNC3(acmMetrics) DEFINE_FUNC2(acmStreamClose) DEFINE_FUNC3(acmStreamConvert) DEFINE_FUNC4(acmStreamMessage) DEFINE_FUNC8(acmStreamOpen) DEFINE_FUNC3(acmStreamPrepareHeader) DEFINE_FUNC2(acmStreamReset) DEFINE_FUNC4(acmStreamSize) DEFINE_FUNC3(acmStreamUnprepareHeader)
8f43933cf2c60b53af552775fdf951e407e7bc4d
c56c93f5e983fdca9a43f4ef6b04a673d745da44
/transfer/common/server.cc
e308c998c2996d26c4edbaff293edc05bdda97b7
[ "MIT" ]
permissive
djpetti/CSCI4230-DES
b138a510ad3b898592127ad2edb6759dffee2997
6a561987f0b658f6f7ca404ebcbf5b9b33d65091
refs/heads/master
2020-03-28T21:07:32.022321
2018-11-04T13:08:15
2018-11-04T13:11:21
149,130,499
0
0
null
null
null
null
UTF-8
C++
false
false
2,990
cc
server.cc
#include "server.h" #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <algorithm> namespace hw1 { namespace transfer { namespace common { namespace { // Binds a socket to a port. // Args: // socket: The socket fd. // port: The port to bind to. // Returns: // True if binding succeeded, false otherwise. static bool bindSocket(int socket, int port) { // Set up the address specifier. struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port); // Bind it. if (bind(socket, (struct sockaddr *)&addr, sizeof(addr)) < 0) { // Binding failed. perror("ERROR"); return false; } return true; } } // namespace Server::Server(const uint8_t *key, uint32_t chunk_size) : SecureNode(key, chunk_size) {} Server::~Server() { // Cleanup the client and close the server. CleanUp(); close(socket_); } bool Server::Listen(uint16_t port) { // Create the socket. socket_ = socket(AF_INET, SOCK_STREAM, 0); if (socket_ < 0) { perror("ERROR"); return false; } // Bind it to the port. if (!bindSocket(socket_, port)) { return false; } // Start listening on the socket. if (listen(socket_, 5) < 0) { perror("ERROR"); return false; } printf("Server listening on port %u.\n", port); return true; } bool Server::WaitForConnection() { // First, accept the client. struct sockaddr_in client_addr; int client_len = sizeof(client_addr); client_sock_ = accept(socket_, (struct sockaddr *)&client_addr, (socklen_t *)&client_len); if (client_sock_ < 0) { // Accept failed for some reason. perror("ERROR"); return false; } printf("Received connection from %s.\n", inet_ntoa(client_addr.sin_addr)); return true; } uint32_t Server::ReceiveChunk(char **buffer) { return SecureNode::ReceiveChunk(client_sock_, buffer); } uint32_t Server::ReceiveChunk(char **buffer, uint32_t length) { return SecureNode::ReceiveChunk(client_sock_, buffer, length); } uint32_t Server::ReceiveAndDecryptChunk(char **buffer) { return SecureNode::ReceiveAndDecryptChunk(client_sock_, buffer); } uint32_t Server::ReceiveAndDecryptChunk(char **buffer, uint32_t length) { return SecureNode::ReceiveAndDecryptChunk(client_sock_, buffer, length); } uint32_t Server::SendChunk(const char *buffer, uint32_t length) { return SecureNode::SendChunk(client_sock_, buffer, length); } uint32_t Server::EncryptAndSendChunk(const char *buffer, uint32_t length) { return SecureNode::EncryptAndSendChunk(client_sock_, buffer, length); } bool Server::ClientConnected() { return client_sock_ != -1; } void Server::CleanUp() { printf("Client disconnected.\n"); close(client_sock_); // Indicate that no client is connected. client_sock_ = -1; } } // namespace common } // namespace transfer } // namespace hw1
0eba56a4225c1a0e25b3de0b465e8a4d2569f639
e302db77bdfc8c088cd8acbdce3eb2d7f6c20aa1
/Unit.h
f4648ddae0ad1a318c6c39ac45f0fd9abd427445
[]
no_license
dong-yeon-lee/git_starcraft
e34b609362bc2065291d23102453f74b4ba5a89b
d1c8511d72ce120dfd40a2d5b94000041ba3438d
refs/heads/master
2023-03-12T06:30:41.294222
2021-03-02T07:08:05
2021-03-02T07:08:05
343,677,596
0
0
null
null
null
null
UTF-8
C++
false
false
680
h
Unit.h
#pragma once #include <iostream> #include <cmath> using namespace std; struct Location { float x; float y; }; class Unit { public: Unit(); Unit(Location currentLocation_ , Location targetLocation_); Unit(const Unit& other); virtual ~Unit(); virtual void SetLocation(const float x, const float y); virtual Location GetLocation() const; virtual void Move() = 0; virtual void DisplayCurrentLocation() const; virtual void SetTargetLocation(const Location targetLocation_); virtual Location GetTargetLocation() const; private: Location currentLocation_; Location targetLocation_; };
fca91a0af4fc54fb8fa6aa7fb983fb1ddea50ae7
1755e560141b34c4d5323ee7afe30caf7bffde92
/include/ModuleGraph/Module.h
560165a2e7855f86295ee8f2f57c6d78b5d0d0ce
[]
no_license
marakj/RealityNotFound
c9b969ee9c8842285e36c9b9cb5b0974eaca7291
b848fb7107e6c33a11bf44431ec96314837729d9
refs/heads/develop
2020-04-08T11:04:00.106525
2017-05-01T09:24:52
2017-05-01T09:24:52
31,653,340
0
0
null
2017-05-16T13:15:31
2015-03-04T11:21:59
C++
UTF-8
C++
false
false
556
h
Module.h
#pragma once #include <osg/PositionAttitudeTransform> namespace ModuleGraph { /** * \class Module * \brief * \author Denis Illes * \date 9. 11. 2016 */ class Module : public osg::PositionAttitudeTransform { public: Module(); float getLength(); float getWidth(); float getHeigth(); void setLength( float newLength ); void setWidth( float newWidth ); void setHeigth( float newHeigth ); void setModuleSize( float newLength, float newWidth, float newHeigth ); void refresh(); private: float length; float width; float heigth; }; }
33f9bfa6aa5ca26164ca6fb70801044b2eeb01eb
a8915f0f1f95ba0902bf0873da013e7e8524bcc3
/packages/UGV/octomap_scout/src/location/mapLoader.cpp
8ee49883199a7e89dbe874427502e9baff75aaf4
[]
no_license
FamiliennameistChow/ROS_beginner
b9007ff97d85ec0d0f80edad9ccf30ebe4f59c39
43edd30928f264fc0b2146e73ced08261e668956
refs/heads/master
2022-07-08T03:20:42.220520
2022-06-25T09:14:04
2022-06-25T09:14:04
206,729,014
14
7
null
null
null
null
UTF-8
C++
false
false
3,014
cpp
mapLoader.cpp
#include "mapLoader.h" MapLoader::MapLoader(ros::NodeHandle &nh){ std::string pcd_file_path, map_topic; nh.param<std::string>("pcd_path", pcd_file_path, ""); nh.param<std::string>("map_topic", map_topic, "point_map"); init_tf_params(nh); pc_map_pub_ = nh.advertise<sensor_msgs::PointCloud2>(map_topic, 10, true); file_list_.push_back(pcd_file_path); auto pc_msg = CreatePcd(); auto out_msg = TransformMap(pc_msg); if (out_msg.width != 0) { out_msg.header.frame_id = "map"; pc_map_pub_.publish(out_msg); } } void MapLoader::init_tf_params(ros::NodeHandle &nh){ nh.param<float>("x", tf_x_, 0.0); nh.param<float>("y", tf_y_, 0.0); nh.param<float>("z", tf_z_, 0.0); nh.param<float>("roll", tf_roll_, 0.0); nh.param<float>("pitch", tf_pitch_, 0.0); nh.param<float>("yaw", tf_yaw_, 0.0); ROS_INFO_STREAM("x: " << tf_x_ <<"y: "<<tf_y_<<"z: "<<tf_z_<<"roll: " <<tf_roll_<<" pitch: "<< tf_pitch_<<"yaw: "<<tf_yaw_); } sensor_msgs::PointCloud2 MapLoader::TransformMap(sensor_msgs::PointCloud2 & in){ pcl::PointCloud<pcl::PointXYZ>::Ptr in_pc(new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(in, *in_pc); pcl::PointCloud<pcl::PointXYZ>::Ptr transformed_pc_ptr(new pcl::PointCloud<pcl::PointXYZ>); Eigen::Translation3f tl_m2w(tf_x_, tf_y_, tf_z_); // tl: translation Eigen::AngleAxisf rot_x_m2w(tf_roll_, Eigen::Vector3f::UnitX()); // rot: rotation Eigen::AngleAxisf rot_y_m2w(tf_pitch_, Eigen::Vector3f::UnitY()); Eigen::AngleAxisf rot_z_m2w(tf_yaw_, Eigen::Vector3f::UnitZ()); Eigen::Matrix4f tf_m2w = (tl_m2w * rot_z_m2w * rot_y_m2w * rot_x_m2w).matrix(); pcl::transformPointCloud(*in_pc, *transformed_pc_ptr, tf_m2w); SaveMap(transformed_pc_ptr); sensor_msgs::PointCloud2 output_msg; pcl::toROSMsg(*transformed_pc_ptr, output_msg); return output_msg; } void MapLoader::SaveMap(const pcl::PointCloud<pcl::PointXYZ>::Ptr map_pc_ptr){ pcl::io::savePCDFile("/tmp/transformed_map.pcd", *map_pc_ptr); } sensor_msgs::PointCloud2 MapLoader::CreatePcd() { sensor_msgs::PointCloud2 pcd, part; for (const std::string& path : file_list_) { // Following outputs are used for progress bar of Runtime Manager. if (pcd.width == 0) { if (pcl::io::loadPCDFile(path.c_str(), pcd) == -1) { std::cerr << "load failed " << path << std::endl; } } else { if (pcl::io::loadPCDFile(path.c_str(), part) == -1) { std::cerr << "load failed " << path << std::endl; } pcd.width += part.width; pcd.row_step += part.row_step; pcd.data.insert(pcd.data.end(), part.data.begin(), part.data.end()); } std::cerr << "load " << path << std::endl; if (!ros::ok()) break; } return pcd; } int main(int argc, char** argv) { ros::init(argc, argv, "map_loader"); ROS_INFO("\033[1;32m---->\033[0m Map Loader Started."); ros::NodeHandle nh("~"); MapLoader map_loader(nh); ros::spin(); return 0; }
a0df0b242d8fd1fe5bade379bfad09801af50b00
39bcafc5f6b1672f31f0f6ea9c8d6047ee432950
/src/main/database_path_and_type.cpp
64f1f9cee426747eb181f839413ceb21c2c4643f
[ "MIT" ]
permissive
duckdb/duckdb
315270af6b198d26eb41a20fc7a0eda04aeef294
f89ccfe0ec01eb613af9c8ac7c264a5ef86d7c3a
refs/heads/main
2023-09-05T08:14:21.278345
2023-09-05T07:28:59
2023-09-05T07:28:59
138,754,790
8,964
986
MIT
2023-09-14T18:42:49
2018-06-26T15:04:45
C++
UTF-8
C++
false
false
866
cpp
database_path_and_type.cpp
#include "duckdb/main/database_path_and_type.hpp" #include "duckdb/main/extension_helper.hpp" #include "duckdb/storage/magic_bytes.hpp" namespace duckdb { DBPathAndType DBPathAndType::Parse(const string &combined_path, const DBConfig &config) { auto extension = ExtensionHelper::ExtractExtensionPrefixFromPath(combined_path); if (!extension.empty()) { // path is prefixed with an extension - remove it auto path = StringUtil::Replace(combined_path, extension + ":", ""); auto type = ExtensionHelper::ApplyExtensionAlias(extension); return {path, type}; } // if there isn't - check the magic bytes of the file (if any) auto file_type = MagicBytes::CheckMagicBytes(config.file_system.get(), combined_path); if (file_type == DataFileType::SQLITE_FILE) { return {combined_path, "sqlite"}; } return {combined_path, string()}; } } // namespace duckdb
52711e7c0cf9e3dc6742ba130231f13f1ae3ebbc
921772e18425b0532d71c051a8b189253ecbf600
/큰 넓이 구하기/solution.cpp
56d32bbaaff85bbde0a4840097f085829e6942dd
[]
no_license
alps-jbnu/alps-acm-problems-2015
afd96548ce1312ea8825e9bf7669842c61a53f0c
e4a2611e456b41076ed53f006453f0a57cf12170
refs/heads/master
2020-12-28T22:52:59.168553
2015-09-24T00:32:06
2015-09-24T00:32:06
36,120,249
0
1
null
2015-06-01T03:43:26
2015-05-23T11:27:52
C++
UTF-8
C++
false
false
347
cpp
solution.cpp
#include <iostream> using namespace std; int main() { double a, b, c, d; cin >> a >> b >> c >> d; double triangle = c * d / 2.0; double rectangle = a * b - triangle; cout.setf(ios::fixed); cout.precision(1); if (triangle > rectangle) cout << triangle; else cout << rectangle; cout << endl; }
a5125c569a373c1127ed6816b518a1fac1e409d0
b75a312629ad5a68aa2cb377785acf2019514a4c
/Qt/mainwindow.h
ad45af4d738da401fe50e4e7d28021e18598f48c
[]
no_license
IvanRamyk/QChess
69bb89b954feab2b601b65ab6f36b5cd972ac66e
a4b468a6a659754ac9447ffd0e153c7c6920be40
refs/heads/master
2020-09-29T06:23:40.144323
2019-12-17T10:43:21
2019-12-17T10:43:21
226,974,316
1
2
null
2019-12-16T19:30:43
2019-12-09T21:47:49
C++
UTF-8
C++
false
false
3,367
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPainter> #include <QMenuBar> #include <QMouseEvent> #include <QLabel> #include <QTextBrowser> #include <QPoint> #include <QCheckBox> #include <string> #include <iostream> #include <string> #include "images.h" #include "field.h" #include "../src/Stockfish/Stockfish.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); protected: void paintEvent(QPaintEvent *event){ QPainter painter(this); //painter.drawImage(Qt::AlignCenter,this->menuBar()->geometry().height(), painter.drawImage(QRect(left_board, up_board, width_board, height_board), pictures->get("board")); painter.drawImage(field->getX(),this->menuBar() ->geometry().height()+field->getY(), field->getImage()); move_color->clear(); move_color->setGeometry(left_board, up_board - height * 0.075, width_board, height * 0.05); move_color->setStyleSheet("background-color: transparent;\n" "font-size:18pt;\n" "text-align: center;"); QString text = ""; if (field->getColor() == Color::White) text = "White "; else text = "Black "; if (field->getState() == State::Checkmate) { text = field->getColor() == Color::White ? "Black" : "White"; text += " win"; } else text += "move"; if (field->getState() == State::Stalemate) { text = "Stalemate"; } move_color->setText(text); move_color->show(); notation->clear(); notation->setGeometry(left_board + width_board + 0.075 * height, up_board + height * 0.075, height * 0.3, height * 0.7); notation->setStyleSheet("background-color: transparent;\n" "font-size:18pt;\n" "text-align: center;"); notation->setText(QString::fromUtf8(field->getNotation().c_str())); notation->show(); evaluation->clear(); if (stockfish_evaluation->isChecked()){ evaluation->setGeometry(width*0.85, height*0.018, width*0.2, width*0.05); evaluation->setStyleSheet("background-color: transparent;\n" "font-size:18pt;\n" "text-align: center;"); evaluation->setText(QString::fromUtf8((std::to_string(field->getEvaluation())).c_str())); evaluation->show(); } } void mousePressEvent (QMouseEvent *event) { QPoint position=event->pos(); QPoint on_field = field->getCoordinate(position.x(), position.y()); if (on_field.x() != -1) field->handleClick(on_field); this->update(); } private slots: void actionStart(){ } private: Ui::MainWindow *ui; Images *pictures; Field *field; int height, width, left_board, up_board, height_board, width_board; QTextBrowser *move_color; QTextBrowser *notation; QTextBrowser *evaluation; QCheckBox *stockfish_evaluation; }; #endif // MAINWINDOW_H
0cac7f18d2dca79b7cede8d5a78cc0817c921b63
b647c14c77df2d3c412fa2953ce63f15a2e08457
/Regulator.hpp
bc4b1ba9ec28b0b9adce808faab30c94071ee68d
[]
no_license
AndreiMoiceanu29/DC-Motor-RPM-Control
aea54308462796619f1d93c54adc230bb1fda233
d4b731b84437dce366b4c53ab428ce5ab42220fa
refs/heads/main
2023-03-23T18:15:48.239180
2021-03-18T20:29:16
2021-03-18T20:29:16
349,208,582
1
0
null
null
null
null
UTF-8
C++
false
false
217
hpp
Regulator.hpp
#include "Semnal.hpp" #include "Interval.hpp" #ifndef H_REGULATOR #define H_REGULATOR class Regulator { virtual Semnal genereaza_comanda(Semnal) = 0; virtual Semnal calculeaza_eroare(Semnal, Semnal) = 0; }; #endif
633d726fc8ebf77faeb33c8a4af99217d66776ba
445818eb70a629c9f4fa68142d8bfd944bacd3a7
/source/drivers/system/system_intf.hpp
1da321202a830390404ebc304e872671f220d04e
[ "MIT" ]
permissive
brandonbraun653/Chimera
7528520d9406f6c57e90c6d8e8451882abfa6e11
b25d699f392882d7f4b3b1305f6181f5a5e1fbc1
refs/heads/master
2023-08-17T01:32:39.583277
2023-05-27T00:31:03
2023-05-27T00:31:03
127,049,804
3
0
null
null
null
null
UTF-8
C++
false
false
937
hpp
system_intf.hpp
/****************************************************************************** * File Name: * system_intf.hpp * * Description: * Models the Chimera system interface * * 2019-2020 | Brandon Braun | brandonbraun653@gmail.com *****************************************************************************/ #pragma once #ifndef CHIMERA_SYSTEM_INTERFACE_HPP #define CHIMERA_SYSTEM_INTERFACE_HPP /* STL Includes */ #include <cstdint> /* Chimera Includes */ #include <Chimera/common> #include <Chimera/source/drivers/system/system_types.hpp> namespace Chimera::System { namespace Backend { /** * Registers the backend driver with Chimera * * @param[in] registry Chimera's copy of the driver interface * @return Chimera::Status_t */ extern Chimera::Status_t registerDriver( DriverConfig &registry ); } } // namespace Chimera::System #endif /* !CHIMERA_SYSTEM_INTERFACE_HPP */
9559d8c54faa439378e9e5e5d1863533425211b7
4fd9f29b20e26b7cc80d748abd8f1dcd94fbbfdd
/Software rasterizer/Lukas Hermanns/SoftPixelEngine/sources/Framework/Sound/spOpenSLESSoundDevice.hpp
c78152db783db6cc38d266c5a6b9691345c7c19e
[ "Zlib" ]
permissive
Kochise/3dglrtvr
53208109ca50e53d8380bed0ebdcb7682a2e9438
dcc2bf847ca26cd6bbd5644190096c27432b542a
refs/heads/master
2021-12-28T03:24:51.116120
2021-08-02T18:55:21
2021-08-02T18:55:21
77,951,439
8
5
null
null
null
null
UTF-8
C++
false
false
1,952
hpp
spOpenSLESSoundDevice.hpp
/* * OpenSL|ES sound device header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_AUDIO_SOUNDDEVICE_OPENSLES_H__ #define __SP_AUDIO_SOUNDDEVICE_OPENSLES_H__ #include "Base/spStandard.hpp" #if defined(SP_COMPILE_WITH_OPENSLES) #include "Framework/Sound/spSoundDevice.hpp" #include "Framework/Sound/spOpenSLESSound.hpp" namespace sp { namespace audio { class SP_EXPORT OpenSLESSoundDevice : public SoundDevice { public: OpenSLESSoundDevice(); ~OpenSLESSoundDevice(); /* Functions */ io::stringc getInterface() const; OpenSLESSound* createSound(const ESoundModes Mode = SOUND_DYNAMIC); private: friend class OpenSLESSound; /* Functions */ bool createSoundEngine(); bool createOutputMixer(); static bool checkForError( const SLresult Result, const io::stringc &ErrorMessage = "OpenSL|ES audio error" ); static bool objectRealize( SLObjectItf &Object, const io::stringc &ObjectName = "OpenSL|ES object" ); static bool objectGetInterface( SLObjectItf &Object, const SLInterfaceID ID, void* Interface, const io::stringc &ObjectName = "OpenSL|ES object" ); static void releaseObject(SLObjectItf &Object); /* Members */ SLEngineItf Engine_; SLObjectItf EngineObject_; SLObjectItf OutputMixer_; SLEnvironmentalReverbItf EnvReverbInterface_; }; } // /namespace audio } // /namespace sp #endif #endif // ================================================================================
3271af3c83c12a921799e21ed16b39c0cfa052fd
6d6560e5a4a46dfe2e3570608812750245eb7c9c
/test/signal-pmf.cpp
bdc8eabe88e09a98c6cf0d937e825829b3a9d6ca
[ "MIT" ]
permissive
palacaze/sigslot
627647b3f9c66d049ded980bc926c38eed6f6036
da1a8b262b79da8f67ceca72c4e9318445beadba
refs/heads/master
2023-08-30T18:28:22.193674
2023-08-27T16:46:29
2023-08-27T17:05:09
90,383,729
587
101
MIT
2023-07-06T01:38:11
2017-05-05T14:21:32
C++
UTF-8
C++
false
false
2,422
cpp
signal-pmf.cpp
#include <algorithm> #include <iostream> #include <memory> #include <string> #include <vector> // A program that computes the function pointer size and uniqueness for a variety // of cases. void fun() {} struct b1 { virtual ~b1() = default; static void sm() {} void m() {} virtual void vm() {} }; struct b2 { virtual ~b2() = default; static void sm() {} void m() {} virtual void vm() {} }; struct c { virtual ~c() = default; virtual void w() {} }; struct d : b1 { static void sm() {} void m() {} void vm() override {} }; struct e : b1, c { static void sm() {} void m() {} void vm() override{} }; template <typename T> union sizer { T t; char data[sizeof(T)]; }; template <typename T> std::string ptr_string(const T&t) { sizer<T> ss; std::uninitialized_fill(std::begin(ss.data), std::end(ss.data), '\0'); ss.t = t; std::string addr; for (char i : ss.data) { char b[] = "00"; std::snprintf(b, 3, "%02X", static_cast<unsigned char>(i)); addr += b; } // shorten string while (addr.size() >= 2) { auto si = addr.size(); if (addr[si-1] == '0' && addr[si-2] == '0') { addr.pop_back(); addr.pop_back(); } else { break; } } return addr; } template <typename T> std::string print(std::string name, const T&t) { auto addr = ptr_string(t); std::cout << name << "\t" << sizeof(t) << "\t0x" << addr << std::endl; return addr; } int main(int, char **) { std::vector<std::string> addrs; addrs.push_back(print("fun", &fun)); addrs.push_back(print("&b1::sm", &b1::sm)); addrs.push_back(print("&b1::m", &b1::m)); addrs.push_back(print("&b1::vm", &b1::vm)); addrs.push_back(print("&b2::sm", &b2::sm)); addrs.push_back(print("&b2::m", &b2::m)); addrs.push_back(print("&b2::vm", &b2::vm)); addrs.push_back(print("&d::sm", &d::sm)); addrs.push_back(print("&d::m", &d::m)); addrs.push_back(print("&d::vm", &d::vm)); addrs.push_back(print("&e::sm", &e::sm)); addrs.push_back(print("&e::m", &e::m)); addrs.push_back(print("&e::vm", &e::vm)); std::sort(addrs.begin(), addrs.end()); auto last = std::unique(addrs.begin(), addrs.end()); std::cout << "Address duplicates: " << std::distance(last, addrs.end()) << std::endl; return 0; }
9902c69570af1205ded4a57e596ac829aa1c1f4a
6ea59bbb80568313db82a3394f23225c01694fe5
/Coursework_Edmand_Karp_max_flow/Test_Coursework/Edmonds_Karp_Unit_test.cpp
319a309e57cffaf044c2ac663df3e3ca3c6d0bd2
[]
no_license
RaifGaripov/Cantina
ccdbb08bcf30d9fe30fcf9c7c18bae49787fa508
45b6069795c1fa08204749c315b348a208994f55
refs/heads/testing
2021-07-16T06:21:38.604600
2020-05-31T08:04:44
2020-05-31T08:04:44
160,087,286
0
0
null
2020-05-14T11:54:03
2018-12-02T19:58:59
C++
WINDOWS-1252
C++
false
false
1,371
cpp
Edmonds_Karp_Unit_test.cpp
#include "pch.h" #include "CppUnitTest.h" #include "C:\Users\raifg\source\repos\Coursework_Emdomds_Carp_max_flow\Coursework_Emdomds_Carp_max_flow\Edmonds_Karp.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace EdmondsKarpUnittest { TEST_CLASS(EdmondsKarpUnittest) { private: Network network; public: TEST_METHOD(test_read_file_wrong_file) { try { network.read_file("lajshfbjla.txt"); } catch (exception exception) { Assert::AreEqual("Error, file is not open!", exception.what()); } } TEST_METHOD(test_read_file_wrong_input) { try { network.read_file("C:\\Users\\raifg\\source\\repos\\Coursework_Emdomds_Carp_max_flow\\Edmonds_Karp_Unit_test\\test_incorrect_input.txt"); } catch (exception exception) { Assert::AreEqual("Error, graph must begin with “S” and end with “T”!", exception.what()); } } TEST_METHOD(test_max_flow_empty_graph) { try { network.max_flow(); } catch (runtime_error exception) { Assert::AreEqual("Error, graph is empty", exception.what()); } } TEST_METHOD(test_max_flow_correct) { network.read_file("C:\\Users\\raifg\\source\\repos\\Coursework_Emdomds_Carp_max_flow\\Edmonds_Karp_Unit_test\\test_correct.txt"); Assert::AreEqual(5, network.max_flow()); } }; }
e64759aa8b9c29cadc0fc8629d1e3128b5fcea9a
caf39a18af33704a23fdf5389c45b35f48f45163
/Code/Objeto.h
4820ca4fe1519377f7d5bf207940a979be437e52
[]
no_license
fulano7/PGProjeto1
c2532c1aa7820de972f32c61311305af6800a4ee
4eb85a9b8d39a95070827f9ec20352136e2e3e0e
refs/heads/master
2021-01-10T21:22:57.610310
2015-06-19T17:27:27
2015-06-19T17:27:27
35,845,591
1
1
null
null
null
null
ISO-8859-1
C++
false
false
3,023
h
Objeto.h
#ifndef _OBJETO_H_ #define _OBJETO_H_ #include <vector> #include <string> #include <iostream> #include <fstream> #include <cstring> #include <cstdio> #include "common.h" #define MAX_CHARS_LINHA 201 #define MAX_OBJS_ARQUIVO 12 using std::vector; using std::string; /* modela um objeto. o atributo 'vertices' eh um vector de coordenadas (x,y,z) que representam cada ponto do objeto. o atributo 'normais' eh um vector de coordenadas (x, y, z) que representam os vetores normais descritos no arquivo ou calculados internamente conforme necessario. o atributo 'faces' eh um vector de array de inteiros em que cada elemento do vector eh um array no formato: (quant_vertices, v1, v2, ..., vn) -> array de tamanho (quant_vertices+1). na primeira posicao a quantidade de vertices da face e nas seguintes o conjunto de vetices que formam a face. o atributo 'indNormais' eh um vector de array de inteiros em que cada elemento do vector eh um array no formato: (quant_normais, vn1, vn2, ..., vnn) -> (analogo a 'faces') */ class Objeto { public: string nome; Objeto(); // construtor padrao ~Objeto(); // desenha o objeto com a biblioteca opengl. void renderizar(); /* conforme especificado, se destinara a ler estes arquivos .obj: http://cin.ufpe.br/~marcelow/Marcelow/arquivos_obj.html outros .obj podem nao ser suportados. carrega um arquivo .obj cujo caminho eh caminho_arquivo, armazena os objetos que estavam no arquivo no array 'array_de_objetos' e retorna a quantidade de objetos que estavam no arquivo. o numero maximo de objetos suportado num arquivo .obj eh fixado em MAX_OBJS_ARQUIVO. */ static int carregar_obj(Objeto*& array_de_objetos, const char *caminho_arquivo); //translada o obj no eixo selecionado em 0.2 void translateObj(int t, float s); //translada entre a origem e a pos inicial void tOriPos(double x, double y, double z); //aplia a operação de escala void escale(float i); void directEscale(float s); //roda o obj em um dos eixos void Objeto::rotateObj(int eixo); static float grau_para_rad(float grau); private: bool firstLoad = true; static const float PI_SOBRE_180; float initMod[4];//informações de escala [0] e translacao iniciais pra num criar um em cima do outro float cores[3]; double translacoes[3]; //guarda a translacao do eixo do mundo para a atual posicao do obj vector <float*> vertices; vector <int> vNormais;//contador de normais associadas aos vertices vector <float*> normais; vector <int*> faces; // lista de faces na forma (v1, v2, ..., vn) vector <int*> indNormais; //para o caso de "//" : lista de faces na forma (vn1, vn2, ..., vnn) // calcula as normais da face se for necessario. float* calcular_normais_face(int *atual); // calcula as normais dos vertices void calcular_normais_vert(); //retorna quantas vezes o caractere 'caractere' aparece na palavra 'palavra' static int ocorrencias(const char* palavra, const char caractere); }; #endif // _OBJETO_H_
cd7c42a8a7f0d2b302a740d79bc6758492333d52
e848b83f6add711fb40ce83fec70ba3ff976853d
/others/detect_vector4.cpp
dd6ead4f60e4b93a142f6a0efd10df065d768cfb
[]
no_license
xiongm/dotfiles
d81915fa9f684a84b55e1019b5a1e872bbf66bc8
3cc03b34f5ae26eb89e39e8f39e9ea7c41d37588
refs/heads/master
2020-04-06T05:06:36.356299
2019-10-17T05:14:39
2019-10-17T05:14:39
43,662,246
0
0
null
null
null
null
UTF-8
C++
false
false
1,218
cpp
detect_vector4.cpp
#include <type_traits> #include <theme/mpl/detection.hpp> #include <theme/mpl/static_if.hpp> #include <vector> #include <iostream> template <typename> struct is_vector : std::false_type {}; template <typename T> struct is_vector< std::vector<T> > : std::true_type {}; template <typename T> constexpr bool is_vector_v = is_vector<T>::value; template <typename T> using data_t = decltype(std::declval<T>().data); template <typename T> constexpr bool has_data_v = theme::mpl::is_detected_v<data_t, T>; template <typename T> constexpr bool is_data_vector_v = is_vector<data_t<T>>::value; struct Foo { int data; }; struct Bar { std::vector<int> data; }; struct Dummy { }; template <typename T> struct Base { template <typename U = T> void handle_object(U * = nullptr) { using namespace theme::mpl; static_if(is_vector<data_t<U>>()) .then([this] () { this->data.data = {1, 2, 3}; //for (auto i : this->data.data) //{ //std::cout << i << std::endl; //} }) .else_([this]() { //this->data.data = 1; //std::cout << this->data.data << std::endl; })(); } T data; }; int main() { Base<Foo> f; Base<Bar> b; f.handle_object(); b.handle_object(); return 0; }
66270f90675b82723b146ce8334370e182b435eb
bcfcad1c5d202cdaa172014afd260e02ad802cb4
/Utility/Include/MipMapGenerator.hpp
f59972bc1eefd759b7b365b8b3d563b63bad070a
[ "BSL-1.0", "LicenseRef-scancode-khronos", "Zlib", "MIT" ]
permissive
jordanlittlefair/Foundation
0ee67940f405573a41be6c46cd9d2e84e34ae8b1
ab737b933ea5bbe2be76133ed78c8e882f072fd0
refs/heads/master
2016-09-06T15:43:27.380878
2015-01-20T19:34:32
2015-01-20T19:34:32
26,716,271
0
0
null
null
null
null
UTF-8
C++
false
false
570
hpp
MipMapGenerator.hpp
#pragma once #ifndef _UTILITY_MIPMAPGENERATOR_HPP_ #define _UTILITY_MIPMAPGENERATOR_HPP_ #include "Image.hpp" #include <vector> namespace Fnd { namespace Utility { class MipMapGenerator { public: static unsigned int GetNumMipLevels( const Image& image ); static unsigned int GetNumMipLevels( unsigned int width, unsigned int height ); static std::vector<Image> GenerateMipMaps( const Image& image, unsigned int max_mip_level = ~0 ); static char Sample( const Image& image, float x, float y, char channel ); }; } } #endif
526a50be17b7f79a1f1840c4433d31841e2cc76a
03325a8cfe18e45996a9802d61537ccfb9cfde62
/LinkedList.h
913d5d3dac8d29f8f191e59d5a8d9cf9053ea614
[]
no_license
kamdibus/LinkedList-Vector
b56a58d031ed2ae738dc83c16d02bc93f71f8664
e1163f4430cbb9066646c9f915ab7d5db72a3be3
refs/heads/master
2021-03-27T20:01:49.187630
2017-07-09T18:47:15
2017-07-09T18:47:15
96,704,110
0
1
null
null
null
null
UTF-8
C++
false
false
9,841
h
LinkedList.h
#ifndef AISDI_LINEAR_LINKEDLIST_H #define AISDI_LINEAR_LINKEDLIST_H #include <cstddef> #include <initializer_list> #include <stdexcept> namespace aisdi { template <typename Type> class LinkedList { public: using difference_type = std::ptrdiff_t; using size_type = std::size_t; using value_type = Type; using pointer = Type*; using reference = Type&; using const_pointer = const Type*; using const_reference = const Type&; class ConstIterator; class Iterator; using iterator = Iterator; using const_iterator = ConstIterator; private: struct node{ const Type obj; node *prev; node *next; node(const Type &A) :obj(A) { next = NULL; prev = NULL; } ~node() { next = NULL; prev = NULL; } }; node *first; node *last; int length; public: LinkedList() { first = new node(Type()); last = new node(Type()); first->prev = NULL; first->next = last; last->prev = first; last->next = NULL; length = 0; } LinkedList(std::initializer_list<Type> l) :LinkedList() { for(auto it = l.begin(); it != (l.end()); ++it) append(*it); } LinkedList(const LinkedList& other) :LinkedList() { for(auto it = other.begin(); it != other.end(); ++it) append(*it); } LinkedList(LinkedList&& other) :LinkedList() { auto firstTemp = first; auto lengthTemp = length; auto lastTemp = last; first = other.first; length = other.length; last = other.last; other.first = firstTemp; other.length = lengthTemp; other.last = lastTemp; } ~LinkedList() { erase(begin(), end()); delete first; delete last; } LinkedList& operator=(const LinkedList& other) { erase(begin(), end()); for(auto it = other.begin(); it != other.end(); ++it) append(*it); return *this; } LinkedList& operator=(LinkedList&& other) { erase(begin(), end()); auto firstTemp = first; auto lengthTemp = length; auto lastTemp = last; first = other.first; length = other.length; last = other.last; other.first = firstTemp; other.length = lengthTemp; other.last = lastTemp; return *this; } bool isEmpty() const { return first-> next == last; } size_type getSize() const { return length; } void append(const Type& item) { node* newNode = new node(item); node* curr = last->prev; last->prev = newNode; newNode->next = last; newNode->prev = curr; curr->next = newNode; length++; } void prepend(const Type& item) { node* newNode = new node(item); node* curr = first->next; first->next = newNode; newNode->next = curr; newNode->prev = first; curr->prev = newNode; length++; } void insert(const const_iterator& insertPosition, const Type& item) { //Czy sprawdzać warunki i używać append/prepend //Nie ma takiej potrzeby, mamy 2 sentinele node* newNode = new node(item); node* prevNode = insertPosition.currNode->prev; newNode->next = insertPosition.currNode; newNode->prev = prevNode; prevNode->next = newNode; (insertPosition.currNode)->prev = newNode; length++; } Type popFirst() { if(isEmpty()) throw std::logic_error("Cannot pop when empty"); auto curr = *begin(); erase(begin()); return curr; } Type popLast() { if(isEmpty()) throw std::logic_error("Cannot pop when empty"); auto curr = *(--end()); erase(end()-1); return curr; } void erase(const const_iterator& possition) { if(possition == end()) throw std::out_of_range("Can't erase a sentinel node"); --length; possition.currNode->next->prev = possition.currNode->prev; possition.currNode->prev->next= possition.currNode->next; delete possition.currNode; } void erase(const const_iterator& firstIncluded, const const_iterator& lastExcluded) { for(auto it = firstIncluded; it != lastExcluded;) { auto itt=it+1; erase(it); it=itt; } } iterator begin() { return iterator(cbegin()); } iterator end() { return iterator(cend()); } const_iterator cbegin() const { if(isEmpty()) return ConstIterator(last); else return ConstIterator(first->next); } const_iterator cend() const { return ConstIterator(last);; } const_iterator begin() const { return cbegin(); } const_iterator end() const { return cend(); } }; template <typename Type> class LinkedList<Type>::ConstIterator { public: using iterator_category = std::bidirectional_iterator_tag; using value_type = typename LinkedList::value_type; using difference_type = typename LinkedList::difference_type; using pointer = typename LinkedList::const_pointer; using reference = typename LinkedList::const_reference; node* currNode; explicit ConstIterator() { currNode = NULL; } ConstIterator(node* n) { currNode = n; } reference operator*() const { if(currNode->next != NULL) return currNode->obj; else throw std::out_of_range("Can't shell when pointing to end"); } ConstIterator& operator++() { if(currNode->next != NULL) { currNode = currNode->next; return *this; } else throw std::out_of_range("Cannot increment when pointing to end"); } ConstIterator operator++(int) { if(currNode->next == NULL) throw std::out_of_range("Can't increment when pointing to end"); ConstIterator curr = *this; currNode = currNode->next; return curr; } ConstIterator& operator--() { if(currNode->prev->prev == NULL) throw std::out_of_range("Cannot decrement when pointing to first elem"); currNode = currNode->prev; return *this; } ConstIterator operator--(int) { if(currNode->prev->prev == NULL) throw std::out_of_range("Cannot decrement when pointing to first elem"); ConstIterator curr = *this; currNode = currNode->prev; return curr; } ConstIterator operator+(difference_type d) const { ConstIterator curr = *this; if(d < 0) while(d++ < 0) --curr; else while(d-- > 0) ++curr; return curr; } ConstIterator operator-(difference_type d) const { ConstIterator curr = *this; if(d <= 0) while(d++ < 0) --curr; else while(d-- > 0) --curr; return curr; } bool operator==(const ConstIterator& other) const { return currNode == other.currNode; } bool operator!=(const ConstIterator& other) const { return currNode != other.currNode; } }; template <typename Type> class LinkedList<Type>::Iterator : public LinkedList<Type>::ConstIterator { public: using pointer = typename LinkedList::pointer; using reference = typename LinkedList::reference; explicit Iterator() {} Iterator(const ConstIterator& other) : ConstIterator(other) {} Iterator& operator++() { ConstIterator::operator++(); return *this; } Iterator operator++(int) { auto result = *this; ConstIterator::operator++(); return result; } Iterator& operator--() { ConstIterator::operator--(); return *this; } Iterator operator--(int) { auto result = *this; ConstIterator::operator--(); return result; } Iterator operator+(difference_type d) const { return ConstIterator::operator+(d); } Iterator operator-(difference_type d) const { return ConstIterator::operator-(d); } reference operator*() const { // ugly cast, yet reduces code duplication. return const_cast<reference>(ConstIterator::operator*()); } }; } #endif // AISDI_LINEAR_LINKEDLIST_H
3b297de6e77002ebc3e29d4462a8dfcbd9197953
52d85cbcd60e01adbc7214a3511c5cfb2ae1e024
/SoundFontInfoLib/iffdigest.h
419f4864471e1729194ed31ed64bdb11595a3d68
[ "MIT" ]
permissive
TrendingTechnology/SoundFonts
0a9d6454bad7c6003a6c10e129a370423826f462
ca40757a5a16fe79dc24fa16244d491b7057b1ed
refs/heads/master
2021-03-01T02:32:13.381208
2020-03-08T01:09:40
2020-03-08T01:09:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,659
h
iffdigest.h
// Copyright (c) 2019 Brad Howes. All rights reserved. // // Loosely based on iffdigest v0.3 by Andrew C. Bulhak. This code has been modified to *only* work on IFF_FMT_RIFF, and // it safely parses bogus files by throwing an IFF_FMT_ERROR exception anytime there is an access outside of valid // memory. Additional cleanup and rework for modern C++ compilers. #ifndef __IFFPARSER_H #define __IFFPARSER_H #include <list> #include <string> /** We only operate with IFF_FMT_RIFF. */ enum IFFFormat { IFF_FMT_IFF85, IFF_FMT_RIFF, IFF_FMT_ERROR }; /** Each RIFF chunk or blob has a 4-character tag that uniquely identifies the contents of the chunk. This is also a 4-byte integer. */ class IFFChunkTag { public: IFFChunkTag(uint32_t tag) : tag_(tag) {} IFFChunkTag(const char* s) : IFFChunkTag(*(reinterpret_cast<const uint32_t*>(s))) {} IFFChunkTag(const void* s) : IFFChunkTag(static_cast<const char*>(s)) {} bool operator ==(const IFFChunkTag& rhs) const { return tag_ == rhs.tag_; } bool operator !=(const IFFChunkTag& rhs) const { return tag_ != rhs.tag_; } std::string toString() const { return std::string(reinterpret_cast<const char*>(&tag_), 4); } private: uint32_t tag_; }; class IFFChunk; typedef std::list<IFFChunk>::iterator IFFChunkIterator; /** List of IFFChunk instances. Provides simple searching based on IFFChunkId -- O(n) performance */ class IFFChunkList: public std::list<IFFChunk> { public: /** Search for the first chunk with a given IFFChunkId @param tag identifier for the chunk to look for @returns iterator to first chunk or end() if none found. */ IFFChunkIterator findChunk(const IFFChunkTag& tag); /** Search for the *next* chunk with a given IFFChunkId @param it iterator pointing to the first chunk to search @param tag identifier for the chunk to look for @returns iterator to the next chunk or end() if none found. */ IFFChunkIterator findNextChunk(IFFChunkIterator it, const IFFChunkTag& tag); }; /** A blob of data defined by a IFFChunkId. Internally, a chunk can just be a sequence of bytes or it can be a list of other IFFChunk instances. */ class IFFChunk { public: /** Constructor for a chunk of data @param tag identifier for this chunk @param ptr pointer to the data start @param size length of the data */ IFFChunk(const IFFChunkTag& tag, const char* ptr, uint32_t size) : tag_(tag), kind_(IFF_CHUNK_DATA), data_(ptr), size_(size), chunks_() {} /** Constructor for a list of chunks @param tag identifier for this chunk @param list list of chunks */ IFFChunk(const IFFChunkTag& tag, IFFChunkList&& list) : tag_(tag), kind_(IFF_CHUNK_LIST), data_(nullptr), size_(0), chunks_(list) {} /** @returns the chunk ID. */ const IFFChunkTag& tag() const { return tag_; } /** Obtain the pointer to the data blob. Only valid if kind_ == IFF_CHUNK_DATA @returns data blob pointer */ const char* dataPtr() const { return data_; } /** Obtain the size of the data blob. Only valid if kind_ == IFF_CHUNK_DATA @returns data blob size */ uint32_t size() const { return size_; } /** Obtain iterator that points to the first chunk. Only valid if kind_ == IFF_CHUNK_LIST @returns iterator to the first chunk */ IFFChunkIterator begin() { return chunks_.begin(); } /** Obtain iterator that points right after the last chunk. Only valid if kind_ == IFF_CHUNK_LIST @returns iterator after the last chunk */ IFFChunkIterator end() { return chunks_.end(); } /** Search for the first chunk with a given IFFChunkId @param tag identifier for the chunk to look for @returns iterator to first chunk or end() if none found. */ IFFChunkIterator find(const IFFChunkTag& tag) { return chunks_.findChunk(tag); } /** Search for the *next* chunk with a given IFFChunkId @param it iterator pointing to the first chunk to search @param tag identifier for the chunk to look for @returns iterator to the next chunk or end() if none found. */ IFFChunkIterator findNext(IFFChunkIterator it, const IFFChunkTag& tag) { return chunks_.findNextChunk(it, tag); } private: IFFChunkTag tag_; enum { IFF_CHUNK_DATA, IFF_CHUNK_LIST } kind_; const char* data_; uint32_t size_; IFFChunkList chunks_; }; /** SoundFont file parser */ class IFFParser { public: /** Attempt to parse a SoundFont resource. Any failures to do so will throw an IFF_FMT_ERROR exception. @param data pointer to the first byte of the SoundFont resource to parse @param size number of bytes in the resource */ static IFFParser parse(const void* data, size_t size); /** Obtain the tag for the file. @returns IFFChunkId tag for the file. */ const IFFChunkTag& tag() const { return tag_; } /** Obtain iterator to the first chunk in the resource. @returns iterator to first chunk. */ IFFChunkIterator begin() { return chunks_.begin(); } /** Obtain iterator to the position after the last chunk in the resource. @returns iterator to position after the last chunk */ IFFChunkIterator end() { return chunks_.end(); } /** Locate the first occurance of a chunk with the given tag value. @param tag the tag to look for @returns iterator to found chunk or end() */ IFFChunkIterator find(const IFFChunkTag& tag) { return chunks_.findChunk(tag); } /** Locate the first occurance of a chunk with the given tag value. @param it iterator pointing to the first chunk to search @param tag the tag to look for @returns iterator to found chunk or end() */ IFFChunkIterator findNext(IFFChunkIterator it, const IFFChunkTag& tag) { return chunks_.findNextChunk(it, tag); } private: IFFParser(const IFFChunkTag& tag, const void* raw, const IFFChunkList& chunks) : tag_(tag), raw_(raw), chunks_(chunks) {} IFFChunkTag tag_; const void* raw_; IFFChunkList chunks_; class Pos; static IFFChunk parseChunk(Pos& pos); static IFFChunkList parseChunks(Pos pos); }; inline IFFChunkIterator IFFChunkList::findNextChunk(IFFChunkIterator from, const IFFChunkTag& tag) { return find_if(++from, end(), [&] (const IFFChunk& value) { return value.tag()== tag; }); } inline IFFChunkIterator IFFChunkList::findChunk(const IFFChunkTag& tag) { return find_if(begin(), end(), [&] (const IFFChunk& value) { return value.tag() == tag; }); } #endif
d7b6c7cf4d032d31c9ad617fa3589f0ee9109aea
3fd7e61268ffbb2b27c66c49644997acf8136abc
/grammar/elkhound/elsa-and-friends-master/elsa/astvisit.cc
2127956b6643c5cee3158ef98c5e341e9730d73e
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yshinya6/ParserMark
765de07900e85a7df2093c14c8e572aabccbab6c
b04ee603d963f32d8a3d8634e648cf304dfab499
refs/heads/master
2021-01-19T05:44:01.521438
2017-02-20T05:09:52
2017-02-20T05:09:52
64,631,802
2
4
null
2017-02-17T04:57:51
2016-08-01T03:10:44
C
UTF-8
C++
false
false
3,360
cc
astvisit.cc
// astvisit.cc // code for astvisit.h #include "astvisit.h" // this module ASTVisitorEx::ASTVisitorEx() : loc(SL_UNKNOWN) {} void ASTVisitorEx::visitFunctionInstantiation(Function *obj) { obj->traverse(*this); } void ASTVisitorEx::foundAmbiguous(void *obj, void **ambig, char const *kind) {} bool ASTVisitorEx::visitFunction(Function *obj) { // template with instantiations to visit? if (obj->isTemplate()) { // instantiations are concrete Restorer<bool> r(inTemplate, false); TemplateInfo *ti = obj->nameAndParams->var->templateInfo(); SFOREACH_OBJLIST(Variable, ti->instantiations, iter) { Variable const *inst = iter.data(); if (inst->templateInfo()->instantiatedFunctionBody()) { visitFunctionInstantiation(inst->funcDefn); } } } return true; } // wrap the unsafe cast #define CAST_AMBIG(node) ((void**)(&((node)->ambiguity))) bool ASTVisitorEx::visitPQName(PQName *obj) { if (obj->loc != SL_UNKNOWN) { loc = obj->loc; } if (obj->isPQ_qualifier() && obj->asPQ_qualifier()->ambiguity) { foundAmbiguous(obj, CAST_AMBIG(obj->asPQ_qualifier()), "PQ_qualifier"); } return true; } // visit a node that has an ambiguity link #define VISIT_W_AMBIG(type) \ bool ASTVisitorEx::visit##type(type *obj) \ { \ if (obj->ambiguity) { \ foundAmbiguous(obj, CAST_AMBIG(obj), obj->kindName()); \ } \ return true; \ } // visit a node that has a source location #define VISIT_W_LOC(type) \ bool ASTVisitorEx::visit##type(type *obj) \ { \ if (obj->loc != SL_UNKNOWN) { \ loc = obj->loc; \ } \ return true; \ } // visit a node that has a source location and an ambiguity link #define VISIT_W_LOC_AMBIG(type) \ bool ASTVisitorEx::visit##type(type *obj) \ { \ if (obj->loc != SL_UNKNOWN) { \ loc = obj->loc; \ } \ if (obj->ambiguity) { \ foundAmbiguous(obj, CAST_AMBIG(obj), obj->kindName()); \ } \ return true; \ } VISIT_W_AMBIG(ASTTypeId) VISIT_W_AMBIG(Declarator) VISIT_W_AMBIG(Condition) VISIT_W_AMBIG(Expression) VISIT_W_AMBIG(ArgExpression) VISIT_W_AMBIG(TemplateArgument) VISIT_W_LOC(TypeSpecifier) VISIT_W_LOC(Enumerator) VISIT_W_LOC(Member) VISIT_W_LOC(IDeclarator) VISIT_W_LOC(Initializer) VISIT_W_LOC_AMBIG(TopForm) VISIT_W_LOC_AMBIG(Statement) VISIT_W_LOC_AMBIG(TemplateParameter) #undef VISIT_W_AMBIG #undef VISIT_W_LOC #undef VISIT_W_LOC_AMBIG #undef CAST_AMBIG // EOF
3d2e52bacf474d8a871fc6f23b88fad28a429b4c
7edb36015a07782245a6d9f84a301a97a3eb668d
/code/userprog/exception.cc
a68c03445cd78ee88d4061f24801114111ac19ec
[ "MIT-Modern-Variant" ]
permissive
NicolasAfonso/NachOS
7a3b951320cbef00113ad3da3459f3af70f9b46a
22f879f25b7415bdae062d5c1c69ae877562b05a
refs/heads/master
2020-04-06T03:43:40.963567
2013-03-28T08:07:59
2013-03-28T08:07:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,470
cc
exception.cc
// exception.cc // Entry point into the Nachos kernel from user programs. // There are two kinds of things that can cause control to // transfer back to here from user code: // // syscall -- The user code explicitly requests to call a procedure // in the Nachos kernel. Right now, the only function we support is // "Halt". // // exceptions -- The user code does something that the CPU can't handle. // For instance, accessing memory that doesn't exist, arithmetic errors, // etc. // // Interrupts (which can also cause control to transfer from user // code into the Nachos kernel) are handled elsewhere. // // For now, this only handles the Halt() system call. // Everything else core dumps. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #include "syscall.h" #ifdef CHANGED #include "synchconsole.h" #include "machine.h" #include "userthread.h" //defini plus bas void putStringHandler(char *s); void copyStringToMachine(char *s,char *to,int size); #endif //CHANGED //---------------------------------------------------------------------- // UpdatePC : Increments the Program Counter register in order to resume // the user program immediately after the "syscall" instruction. //---------------------------------------------------------------------- static void UpdatePC () { int pc = machine->ReadRegister (PCReg); machine->WriteRegister (PrevPCReg, pc); pc = machine->ReadRegister (NextPCReg); machine->WriteRegister (PCReg, pc); pc += 4; machine->WriteRegister (NextPCReg, pc); } //---------------------------------------------------------------------- // ExceptionHandler // Entry point into the Nachos kernel. Called when a user program // is executing, and either does a syscall, or generates an addressing // or arithmetic exception. // // For system calls, the following is the calling convention: // // system call code -- r2 // arg1 -- r4 // arg2 -- r5 // arg3 -- r6 // arg4 -- r7 // // The result of the system call, if any, must be put back into r2. // // And don't forget to increment the pc before returning. (Or else you'll // loop making the same system call forever! // // "which" is the kind of exception. The list of possible exceptions // are in machine.h. //---------------------------------------------------------------------- void ExceptionHandler (ExceptionType which) { int type = machine->ReadRegister (2); #ifdef CHANGED if (which == SyscallException) { switch(type) { case(SC_Halt): { DEBUG ('a', "Shutdown, initiated by user program.\n"); interrupt->Halt (); break; } case(SC_Exit): { DEBUG ('a', "EXIT\n"); currentThread->space->do_Exit(); break; } case(SC_PutChar): { DEBUG ('a', "Putchar\n"); synchconsole->SynchPutChar ((char)machine->ReadRegister(4)); break; } case(SC_PutString): { DEBUG ('a', "PutString\n"); putStringHandler((char *)machine->ReadRegister(4)); break; } case(SC_GetChar): { DEBUG ('a', "GetChar\n"); machine->WriteRegister(2, (int) synchconsole->SynchGetChar()); break; } case(SC_GetString): { DEBUG ('a', "GetString\n"); //adresse du resultat char *to = (char *) machine->ReadRegister(4); int size = (int) machine->ReadRegister(5); char *buffer = new char[MAX_STRING_SIZE]; synchconsole->SynchGetString(buffer,size); copyStringToMachine(buffer,to,size); delete [] buffer; break; } case(SC_UserThreadCreate): { DEBUG ('a', "UserThreadCreate\n"); do_UserThreadCreate((int)machine->ReadRegister(4), (int)machine->ReadRegister(5)); break; } case(SC_UserThreadExit): { DEBUG ('a', "UserThreadExit\n"); do_UserThreadExit(); break; } /*plus tard case(SC_UserThreadJoin): { DEBUG ('a', "UserThreadJoin\n"); int threadID = machine -> ReadRegister(4); int tt = do_UserThreadJoin(threadID); machine->WriteRegister(2,tt); break; } */ default: { printf ("Unexpected user mode exception %d %d\n", which, type); ASSERT (FALSE); } } } #else if ((which == SyscallException && type == SC_Halt)) { DEBUG ('a', "Shutdown, initiated by user program.\n"); interrupt->Halt (); } else { printf ("Unexpected user mode exception %d %d\n", which, type); ASSERT (FALSE); } #endif // LB: Do not forget to increment the pc before returning! UpdatePC (); // End of addition } #ifdef CHANGED void copyStringFromMachine (int from, char *to, unsigned size) { unsigned i; for(i=0;i<size && machine->mainMemory[from+i] !='\0';i++) { to[i] = machine->mainMemory[from+i]; } to[i] = '\0'; } void putStringHandler(char *s) { char *buffer = new char[MAX_STRING_SIZE]; copyStringFromMachine((int)s,buffer,MAX_STRING_SIZE); synchconsole->SynchPutString(buffer); delete [] buffer; } void copyStringToMachine(char *s, char *to, int size) { int i; for(i=0;i<size-1 && s[i] !='\0';i++) { machine->mainMemory[(unsigned)(to+i)] = (char) s[i]; } machine->mainMemory[(unsigned)(to+i)] = '\0'; } #endif //CHANGED
0b8cfc7565c25d1d24dde782311f9bc4a4e6a0b4
4cec78b4ac3eadcb6f4b490e91e690685e49c674
/MarkX_CalGamesOC/TKOClimber.cpp
b06b1d674c4383eee43a989b2ac9b3e70c9a3216
[]
no_license
MittyRobotics/Mark-X
a86aa943fa63a30ee5b8065ee30348a3371aeeb9
03a692dd0adbc05ece01be15db96cefc76a95f4d
refs/heads/master
2021-05-27T02:00:30.750612
2014-01-10T02:14:22
2014-01-10T02:14:22
15,834,840
0
0
null
null
null
null
UTF-8
C++
false
false
23,732
cpp
TKOClimber.cpp
//Last edited by Vadim Korolik //on 09/08/2013 #include "TKOClimber.h" //Constructor for the TKOClimber class /* * SetVoltageRampRate() When in PercentVbus or Voltage output mode, the rate at which the voltage changes can be limited to reduce current spikes. * ConfigFaultTime() * Configure how long the Jaguar waits in the case of a fault before resuming operation. * Faults include over temerature, over current, and bus under voltage. * The default is 3.0 seconds, but can be reduced to as low as 0.5 seconds. */ TKOClimber::TKOClimber(int port1, int port2) : _stick3(3), _stick4(4), sDumperR(PN_S1R_ID), sDumperE(PN_S1E_ID), sClipsR(PN_S3R_ID), sClipsE(PN_S3E_ID), sArmR(PN_S4R_ID), sArmE(PN_S4E_ID), dumpProtect(9), comp(PRESSURE_SWITCH_PORT, COMPRESSOR_ID), rsRatchet(PN_R3_ID), winch1(port1, CANJaguar::kPercentVbus), winch2(port2, CANJaguar::kPercentVbus), winchEncoder(WINCH_ENC_PORT_A, WINCH_ENC_PORT_B), hookLeft(7), hookRight(8), clipLeft(5), clipRight(6), armTop(4), armBottom(3), ratchet(2), winch1PID(WINCH_kP, WINCH_kI, WINCH_kD, &winchEncoder, &winch1), winch2PID(WINCH_kP, WINCH_kI, WINCH_kD, &winchEncoder, &winch2) { printf("Initializing climber \n"); winchEncoder.Start(); ds = DriverStation::GetInstance(); // Pulls driver station information state = INITIAL_STATE; comp.Start(); winch1PID.Enable(); winch2PID.Enable(); winch1.ConfigFaultTime(.5); winch2.ConfigFaultTime(.5); ranCalibration = false; abortTrig = false; climbCount = 0; ClipBack(); ArmBack(); RatchetBack(); log = log->getInstance(); printf("Finished Initializing climber \n"); } void TKOClimber::ArmBack() { sArmE.Set(false); sArmR.Set(true); } void TKOClimber::ArmForward() { ClipForward(); sArmR.Set(false); sArmE.Set(true); } void TKOClimber::ClipBack() { sClipsR.Set(false); sClipsE.Set(true); } void TKOClimber::ClipForward() { sClipsE.Set(false); sClipsR.Set(true); } void TKOClimber::RatchetBack() { rsRatchet.SetOn(1); } void TKOClimber::RatchetForward() { rsRatchet.SetOn(0); } void TKOClimber::RetractDump() { sDumperE.Set(false); sDumperR.Set(true); } void TKOClimber::Dump() { sDumperR.Set(false); sDumperE.Set(true); } void TKOClimber::calibrateWinch() { log->addMessage("CALIB: Starting winch calibration"); winch1PID.Disable(); winch2PID.Disable(); RatchetBack(); while (ds->IsEnabled()) { RatchetBack(); winch1.Set((-1) * MAXSPEED); //go up winch2.Set((-1) * MAXSPEED); if (not armTop.Get()) //NOT ARMTOP MEANS THAT THE WINCH IS AT THE LIMIT SWITCH { winch1.Set(0); winch2.Set(0); winchEncoder.Reset(); SETPOINT_TOP = winchEncoder.PIDGet() + TOLERANCE; break; } } log->addMessage("CALIB: Done going up, at the top."); while (ds->IsEnabled()) { winch1.Set((1) * MAXSPEED); //go down winch2.Set((1) * MAXSPEED); if (not armBottom.Get()) { winch1.Set(0); winch2.Set(0); SETPOINT_BOTTOM = winchEncoder.PIDGet() + (ds->GetAnalogIn(1) * 100); ///USED TO BE 10 break; } } log->addMessage("CALIB: Done going down, at the bottom."); winch1.Set((-1) * MAXSPEED); //go up winch2.Set((-1) * MAXSPEED); Wait(.5); log->addMessage("CALIB: At start point."); winch1.Set(0); winch2.Set(0); Wait(.5); oldSetpoint = winchEncoder.PIDGet(); setpoint = winchEncoder.PIDGet(); SETPOINT_RATCHET_RETRACT = SETPOINT_BOTTOM + 2.0; SETPOINT_LAST = SETPOINT_TOP - 2.0; SETPOINT_CENTER = (SETPOINT_TOP + SETPOINT_BOTTOM) / 2; printf("Top Setpoint: %f", SETPOINT_TOP); printf("Bottom Setpoint: %f", SETPOINT_BOTTOM); deltaSetpoint = LOOPTIME * (SETPOINT_TOP - SETPOINT_BOTTOM) / TIME_BW_SP; ranCalibration = true; } void TKOClimber::print() { printf("HookLeft %d \n", hookLeft.Get()); printf("HookRight %d \n", hookRight.Get()); printf("Clip left %d \n", clipLeft.Get()); printf("Clip Right %d\n", clipRight.Get()); printf("Arm Top %d \n", armTop.Get()); printf("Arm Bottom %d\n", armBottom.Get()); printf("Ratchet %d\n", ratchet.Get()); printf("--------------STATE = %d ------------------- \n\n\n", state); printf("\n"); } void TKOClimber::MoveWinchWithStick() { DSClear(); // dumpProtect.StartLiveWindowMode(); winch1PID.Enable(); winch2PID.Enable(); if (_stick3.GetRawButton(4)) TKOClimber::ArmBack(); if (_stick3.GetRawButton(5)) TKOClimber::ArmForward(); if (_stick3.GetRawButton(2)) TKOClimber::ClipBack(); if (_stick3.GetRawButton(3)) TKOClimber::ClipForward(); if (_stick3.GetRawButton(8)) TKOClimber::RatchetBack(); if (_stick3.GetRawButton(9)) TKOClimber::RatchetForward(); if (_stick3.GetRawButton(11)) TKOClimber::calibrateWinch(); if (_stick4.GetRawButton(10)) { dumpProtect.Set(0.); DSLog(2, "Dump protector set to angle 0\n"); } if (_stick4.GetRawButton(11)) { dumpProtect.Set(0.5); DSLog(2, "Dump protector set to angle 90\n"); } if (_stick3.GetRawButton(10)) { climbStart = ds->GetMatchTime(); log->addCMessage("LVL 1 Climb started at (s)", climbStart); TKOClimber::LevelOneClimb(); climbEnd = ds->GetMatchTime(); climbTime = climbEnd - climbStart; log->addMessage("Done with level one climb"); log->addCMessage("LVL 1 Climb took (s)", climbTime); printf("LVL 1 Climb took (s) %f\n", climbTime); } if (_stick3.GetRawButton(7)) { climbStart = ds->GetMatchTime(); log->addCMessage("LVL 2 Climb started at (s)", climbStart); if (TKOClimber::LevelOneClimb()) TKOClimber::LevelTwoOrMoreClimb(); climbEnd = ds->GetMatchTime(); climbTime = climbEnd - climbStart; log->addMessage("Done with level two climb"); log->addCMessage("LVL 2 Climb took (s)", climbTime); printf("LVL 2 Climb took (s) %f\n", climbTime); } if (_stick3.GetRawButton(6)) { climbStart = ds->GetMatchTime(); log->addCMessage("LVL 3 Climb started at (s)", climbStart); if (TKOClimber::LevelOneClimb()) { TKOClimber::LevelTwoOrMoreClimb(); Wait(.1); TKOClimber::LevelTwoOrMoreClimb(); } climbEnd = ds->GetMatchTime(); climbTime = climbEnd - climbStart; log->addMessage("Done with level three climb"); log->addCMessage("LVL 3 Climb took (s)", climbTime); printf("LVL 3 Climb took (s) %f\n", climbTime); } if (comp.GetPressureSwitchValue() == 0) DSLog(1, "NOT max pressure."); DSLog(3, "SERVO ANGLE %f", dumpProtect.GetAngle()); DSLog(4, "SERVO POS %f", dumpProtect.Get()); // if (not clipLeft.Get()) // DSLog(1, "Left Clip Engaged"); // if (not clipRight.Get()) // DSLog(2, "Right Clip Engaged"); // if (not hookLeft.Get()) // DSLog(3, "Left Hook Engaged"); // if (not hookRight.Get()) // DSLog(4, "Right Hook Engaged"); DSLog(5, "SETP: %f", oldSetpoint); DSLog(6, "Winch L: %f", winchEncoder.PIDGet()); if (_stick3.GetY() < -STICK_DEADZONE and (oldSetpoint - (-_stick3.GetY() * deltaSetpoint)) < SETPOINT_BOTTOM) { oldSetpoint = oldSetpoint - (-_stick3.GetY() * deltaSetpoint); } if (_stick3.GetY() > STICK_DEADZONE and (oldSetpoint - (-_stick3.GetY() * deltaSetpoint)) > SETPOINT_TOP) { oldSetpoint = oldSetpoint - (-_stick3.GetY() * deltaSetpoint); } } //void TKOClimber::TaskRunner(TKOClimber *instance) //{ // instance->checkAbort(); // ////////////////MAY NEED WAIT OF PAUSE OF SOME SORT // Wait(0.05); //} //void TKOClimber::checkAbort() //{ // if (_stick3.GetRawButton(2) and _stick3.GetRawButton(4)) // { // abortTrig = true; // } // if (abortTrig == true) // { // RatchetForward(); // winch1PID.Disable(); // winch2PID.Disable(); // winchStop(); // printf("Testing the abort, shutting down winches. \n"); // } //} void TKOClimber::winchStop() { winch1.Set(0); winch2.Set(0); winch1.StopMotor(); winch2.StopMotor(); winch1PID.Disable(); winch2PID.Disable(); if (winch1.GetOutputVoltage() > 0 or winch2.GetOutputVoltage() > 0) printf("WINCH NOT ACTUALLY STOPPED \n"); } void TKOClimber::Test() //pneumatics test { } void TKOClimber::winchMove(double SP) // { setpoint = SP; printf("-----------------IN WINCH MOVE -----------------------------, %f \n", SP); loopTime.Start(); double deltaSetPoint = LOOPTIME * (SETPOINT_TOP - SETPOINT_BOTTOM) / TIME_BW_SP; bool alreadyRan = false; winch1PID.Enable(); winch2PID.Enable(); printf("Encoder Location: %f \n", winchEncoder.PIDGet()); if (SP < winch1PID.GetSetpoint()) { RatchetBack(); } if ((int) oldSetpoint == (int) SP) { return; } if (oldSetpoint < SP) //MOVING DOWN { printf("CURRENT POSITION IS: %f ", winchEncoder.PIDGet()); printf("SETPOINT IS: %f \n", oldSetpoint); oldSetpoint = oldSetpoint - deltaSetPoint; } if (oldSetpoint > SP and alreadyRan == false) { printf("CURRENT POSITION IS: %f ", winchEncoder.PIDGet()); printf("SETPOINT IS: %f \n", oldSetpoint); oldSetpoint = oldSetpoint + deltaSetPoint; } return; } void TKOClimber::winchMoveSlow(double SP, double factor) // { setpoint = SP; printf("-----------------IN WINCH MOVE -----------------------------, %f \n", SP); loopTime.Start(); double deltaSetPoint = LOOPTIME * (SETPOINT_TOP - SETPOINT_BOTTOM) / TIME_BW_SP; double delta = deltaSetPoint / factor; bool alreadyRan = false; winch1PID.Enable(); winch2PID.Enable(); printf("Encoder Location: %f \n", winchEncoder.PIDGet()); if (SP < winch1PID.GetSetpoint()) { RatchetBack(); } if ((int) oldSetpoint == (int) SP) { return; } if (oldSetpoint < SP) //MOVING DOWN { printf("CURRENT POSITION IS: %f ", winchEncoder.PIDGet()); printf("SETPOINT IS: %f \n", oldSetpoint); oldSetpoint = oldSetpoint - delta; } if (oldSetpoint > SP and alreadyRan == false) { printf("CURRENT POSITION IS: %f ", winchEncoder.PIDGet()); printf("SETPOINT IS: %f \n", oldSetpoint); oldSetpoint = oldSetpoint + delta; } return; } void TKOClimber::testMoveWinch() { setpoint = SETPOINT_CENTER; while (setpoint > oldSetpoint + 10 and ds->IsEnabled()) //moving down { //while where you want it to go is below than its ramping setpoint printf("@@@@@@@@@@@@@@@@@@ NOW IN TESTMOVEWINCH @@@@@@@@@@@@@@@@@@@@@@@ \n"); time2.Reset(); winchMove(SETPOINT_CENTER); //sets setpoint to argument, increments oldsetpoint winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); if (oldSetpoint > setpoint + 3) break; } while (setpoint < oldSetpoint + 10 and ds->IsEnabled()) //moving up { //while where you want it to go is below than its ramping setpoint printf("@@@@@@@@@@@@@@@@@@ NOW IN TESTMOVEWINCH @@@@@@@@@@@@@@@@@@@@@@@ \n"); time2.Reset(); winchMove(SETPOINT_CENTER); //sets setpoint to argument, increments oldsetpoint winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); if (oldSetpoint < setpoint + 3) break; } } void TKOClimber::ohGod() { printf("UH OH"); while (ds->IsEnabled()) { winch1PID.Disable(); winch2PID.Disable(); RatchetForward(); } } bool TKOClimber::LevelOneClimb() { log->addMessage("LVL 1 Starting climb"); climbCount = 0; if (ranCalibration == false) { log->addMessage("LVL 1 Climb called without calibration..."); calibrateWinch(); MoveWinchWithStick(); return false; } winch1PID.Enable(); winch2PID.Enable(); ClipForward(); RatchetBack(); Wait(.5); setpoint = SETPOINT_BEGINNING; while (setpoint > oldSetpoint + 10 and ds->IsEnabled()) { time2.Reset(); winchMoveSlow(SETPOINT_BEGINNING, 1.); //sets setpoint to argument, increments oldsetpoint winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } setpoint = SETPOINT_BEGINNING; while (setpoint < oldSetpoint - 10 and ds->IsEnabled()) ///MAYBE THIS > SIGN NEEDS TO BE < { //while where you want it to go is below than its ramping setpoint printf("@@@@@@@@@@@@@@@@@@@@MOVING WINCH TO SETPOINT \n"); //disableIfOutOfRange() time2.Reset(); winchMoveSlow(SETPOINT_BEGINNING, 1.); //sets setpoint to argument, increments oldsetpoint winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } log->addMessage("LVL 1: Winch should now be at climb start position."); //--------------WINCH SHOULD NOW BE AT STARTING POSITION------------- ArmForward(); Wait(3.); RatchetForward(); Wait(.1); log->addMessage("LVL 1: Arm moved forward towards pyramid."); setpoint = SETPOINT_ARM_BACK; while (setpoint > oldSetpoint + 10 and ds->IsEnabled()) { //while where you want it to go is below than its ramping setpoint printf("TESTING CURRENT ENC POS: %f\n", winchEncoder.PIDGet()); disableIfOutOfRange() if (winchEncoder.PIDGet() >= 1600) { if (hookLeft.Get() or hookRight.Get()) { winch1PID.SetSetpoint(winchEncoder.PIDGet()); winch2PID.SetSetpoint(winchEncoder.PIDGet()); RatchetBack(); log->addMessage(">>>CRITICAL LVL 1: IMPROPERLY ALLIGNED? WHEN STARTING FIRST PULL HOOKS DID NOT ATTACH"); Wait(0.25); log->addMessage(">>>CRITICAL LVL 1: ABORTING LVL 1 CLIMB, RETURNING OUT OF CLIMB FUNCTION."); printf("CRITICAL LVL 1: IMPROPERLY ALLIGNED? WHEN STARTING FIRST PULL HOOKS DID NOT ATTACH\n"); return false; } } time2.Reset(); winchMoveSlow(SETPOINT_ARM_BACK, 1.); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } log->addMessage("LVL 1: Finished pulling up to arm back setpoint"); ArmBack(); Wait(2.); log->addMessage("LVL 1: Arm moved back."); setpoint = SETPOINT_CLIP_BACK; while (setpoint > oldSetpoint + 10 and ds->IsEnabled()) { //while where you want it to go is below than its ramping setpoint disableIfOutOfRange() time2.Reset(); winchMoveSlow(SETPOINT_CLIP_BACK, 1.); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } log->addMessage("LVL 1: Finished pulling up to clip back setpoint"); ClipBack(); Wait(.5); log->addMessage("LVL 1: Clips moved back"); setpoint = SETPOINT_BOTTOM + 500; while (ds->IsEnabled() and armBottom.Get()) { //while where you want it to go is below than its ramping setpoint time2.Reset(); printf("Le going down more than bottom lel\n"); printf("PID writing: %f\n", winch1PID.Get()); if (not armBottom.Get()) break; printf("oldSP = %f%s", oldSetpoint, "\n"); winchMoveSlow(setpoint, 2); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } log->addMessage("LVL 1: Winch now at bottom limit switch"); Wait(.25); setpoint = SETPOINT_BOTTOM - 300; RatchetBack(); ClipForward(); Wait(.5); log->addMessage("LVL 1: Clip is forward, transferring weight"); while (setpoint < oldSetpoint - 10 and ds->IsEnabled()) //UP TO SETPOINT_BOTTOM FROM THE LIMIT SWITCH { //while where you want it to go is below than its ramping setpoint printf("Le going up back to setpoint bottom lel"); DSLog(1, "LAST SETPOINT %f", setpoint); time2.Reset(); if (not clipLeft.Get() and not clipRight.Get()) { log->addMessage("LVL 1: CLIPS ENGAGED"); break; } winchMoveSlow(setpoint, 10); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } Wait(1.); if (clipLeft.Get() or clipRight.Get()) { DSClear(); if (not clipLeft.Get()) { DSLog(1, "Left Clip Engaged"); log->addMessage("LVL 1: Left clip engaged"); } if (not clipRight.Get()) { DSLog(2, "Right Clip Engaged"); log->addMessage("LVL 1: Right clip engaged"); } if (not hookLeft.Get()) { DSLog(3, "Left Hook Engaged"); log->addMessage("LVL 1: Left hook engaged"); } if (not hookRight.Get()) { DSLog(4, "Right Hook Engaged"); log->addMessage("LVL 1: Right hook engaged"); } while ((clipLeft.Get() or clipRight.Get()) and ds->IsEnabled()) { RatchetForward(); winchStop(); DSLog(6, "ERROR NO CLIP"); log->addMessage("LVL 1: CLIPS NOT ENGAGED"); Wait(5.); } } RatchetBack(); Wait(.25); setpoint = SETPOINT_TOP + 30; log->addMessage("LVL 1: Weight transferred, moving hooks back up to top."); while (setpoint < oldSetpoint - 1 and ds->IsEnabled()) { //while where you want it to go is below than its ramping setpoint if (not clipLeft.Get()) DSLog(1, "Left Clip Engaged"); if (not clipRight.Get()) DSLog(2, "Right Clip Engaged"); if (not hookLeft.Get()) DSLog(3, "Left Hook Engaged"); if (not hookRight.Get()) DSLog(4, "Right Hook Engaged"); disableIfOutOfRange() DSLog(1, "LAST SETPOINT %f", setpoint); time2.Reset(); winchMoveSlow(setpoint, 0.5); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } DSLog(3, "Done with autoclimb") log->addMessage("LVL 1: DONE WITH LVL 1 CLIMB"); printf("Done with autoclimb"); climbCount++; return true; } bool TKOClimber::LevelTwoOrMoreClimb() { winch1PID.Enable(); winch2PID.Enable(); ArmForward(); Wait(2); // if (hookLeft.Get() or hookRight.Get()) //MAYBE REMOVE HOOK CHECK // ohGod(); RatchetForward(); setpoint = SETPOINT_ARM_BACK_LVL2; bool dumped = false; int tempCount = 0; while (setpoint > oldSetpoint + 10 and ds->IsEnabled()) { //while where you want it to go is below than its ramping setpoint if ((climbCount == (int) ds->GetAnalogIn(2) - 1) and winchEncoder.PIDGet() > 500 and not dumped) { Dump(); Wait(0.25); RetractDump(); Wait(0.25); Dump(); Wait(0.25); RetractDump(); Wait(0.25); Dump(); dumped = true; } if (tempCount % 10 == 0) { std::ostringstream oss; oss << "LVL2: W1Temp: " << winch1.GetTemperature(); log->addMessage(oss.str()); oss.str(""); oss << "LVL2: W1Curr: " << winch1.GetOutputCurrent(); log->addMessage(oss.str()); oss.str(""); oss << "LVL2: W1BUSV: " << winch1.GetBusVoltage(); log->addMessage(oss.str()); oss.str(""); oss << "LVL2: W1FAULTS: " << winch1.GetFaults(); log->addMessage(oss.str()); } time2.Reset(); winchMoveSlow(SETPOINT_ARM_BACK_LVL2, 1); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); tempCount++; Wait(LOOPTIME - time2.Get()); } comp.Stop(); ArmBack(); Wait(.5); setpoint = SETPOINT_ARM_BACK; tempCount = 0; while (setpoint > oldSetpoint + 10 and ds->IsEnabled()) { //while where you want it to go is below than its ramping setpoint if (tempCount % 10 == 0) { std::ostringstream oss; oss << "LVL2: W1Temp: " << winch1.GetTemperature(); log->addMessage(oss.str()); oss.str(""); oss << "LVL2: W1Curr: " << winch1.GetOutputCurrent(); log->addMessage(oss.str()); oss.str(""); oss << "LVL2: W1BUSV: " << winch1.GetBusVoltage(); log->addMessage(oss.str()); oss.str(""); oss << "LVL2: W1FAULTS: " << winch1.GetFaults(); log->addMessage(oss.str()); } time2.Reset(); winchMoveSlow(SETPOINT_ARM_BACK, 1); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); tempCount++; Wait(LOOPTIME - time2.Get()); } ArmBack(); Wait(.5); setpoint = SETPOINT_CLIP_BACK; tempCount = 0; while (setpoint > oldSetpoint + 10 and ds->IsEnabled()) { //while where you want it to go is below than its ramping setpoint if (tempCount % 10 == 0) { std::ostringstream oss; oss << "LVL2: W1Temp: " << winch1.GetTemperature(); log->addMessage(oss.str()); oss.str(""); oss << "LVL2: W1Curr: " << winch1.GetOutputCurrent(); log->addMessage(oss.str()); oss.str(""); oss << "LVL2: W1BUSV: " << winch1.GetBusVoltage(); log->addMessage(oss.str()); oss.str(""); oss << "LVL2: W1FAULTS: " << winch1.GetFaults(); log->addMessage(oss.str()); } time2.Reset(); winchMoveSlow(SETPOINT_CLIP_BACK, 1); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); tempCount++; Wait(LOOPTIME - time2.Get()); } ClipBack(); Wait(.5); setpoint = SETPOINT_BOTTOM + 500; while (ds->IsEnabled() and armBottom.Get()) { //while where you want it to go is below than its ramping setpoint time2.Reset(); printf("Le going down more than bottom lel\n"); if (not armBottom.Get()) break; printf("oldSP = %f%s", oldSetpoint, "\n"); winchMoveSlow(setpoint, 2); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } Wait(.25); comp.Start(); setpoint = SETPOINT_BOTTOM - 300; RatchetBack(); ClipForward(); Wait(.5); while (setpoint < oldSetpoint - 10 and ds->IsEnabled()) //UP TO SETPOINT_BOTTOM FROM THE LIMIT SWITCH { //while where you want it to go is below than its ramping setpoint printf("Le going up back to setpoint bottom lel"); DSLog(1, "LAST SETPOINT %f", setpoint); time2.Reset(); if (not clipLeft.Get() and not clipRight.Get()) break; winchMoveSlow(setpoint, 10); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } //RatchetForward(); Wait(.25); if (clipLeft.Get() or clipRight.Get()) { DSClear(); if (not clipLeft.Get()) DSLog(1, "Left Clip Engaged"); if (not clipRight.Get()) DSLog(2, "Right Clip Engaged"); if (not hookLeft.Get()) DSLog(3, "Left Hook Engaged"); if (not hookRight.Get()) DSLog(4, "Right Hook Engaged"); while ((clipLeft.Get() or clipRight.Get()) and ds->IsEnabled()) { RatchetForward(); winchStop(); DSLog(6, "ERROR NO CLIP"); } } RatchetBack(); Wait(.25); if (climbCount <= (ds->GetAnalogIn(2) - 2)) //MAKES IT SO IF WE ARE AT LEVEL THREE, WE DONT BRING THE HOOKS TO THE TOP ******** CHANGE TO <= WHEN CLIMBING A 3 LVL PYRAMID { setpoint = SETPOINT_TOP + 30; while (setpoint < oldSetpoint - 1 and ds->IsEnabled()) { //while where you want it to go is below than its ramping setpoint if (not clipLeft.Get()) DSLog(1, "Left Clip Engaged"); if (not clipRight.Get()) DSLog(2, "Right Clip Engaged"); if (not hookLeft.Get()) DSLog(3, "Left Hook Engaged"); if (not hookRight.Get()) DSLog(4, "Right Hook Engaged"); disableIfOutOfRange() DSLog(1, "LAST SETPOINT %f", setpoint); time2.Reset(); winchMoveSlow(setpoint, 1); //sets setpoint to argument, increments oldsetpoint //!!!!!!!!!!!!!!THE SETPOINT SHOULD BE SLIGHTLY BELOW THE BAR LOCATION!!!!! winch1PID.SetSetpoint(oldSetpoint); winch2PID.SetSetpoint(oldSetpoint); Wait(LOOPTIME - time2.Get()); } } DSLog(3, "Done with autoclimb") printf("Done with autoclimb"); climbCount++; return true; } //Destructor for the TKOAutonomous class TKOClimber::~TKOClimber() { }
a71a13b1a380b8ab1a4efbf2280c58dc191aa1c4
0563fa83c4dddc925d241aed6b3a5d372360ea65
/include/Resources.hpp
8298c3c36c2c4790635b2cb3538445f767f59e52
[]
no_license
pinbraerts/Energy-is-over-
c77345e3e614f16c280b7bbd3ee618e6f0dec9d0
5146ed52925bcd908b385f5cbd61eb10cded951a
refs/heads/master
2020-04-21T14:01:21.918343
2019-03-26T05:53:57
2019-03-26T05:53:57
169,620,531
0
1
null
2019-03-05T18:59:51
2019-02-07T18:26:33
C++
UTF-8
C++
false
false
1,919
hpp
Resources.hpp
#ifndef EIO_GAME_HPP #define EIO_GAME_HPP #include "Widget.hpp" struct Resources { std::map<std::wstring, HMODULE> modules; std::map<std::wstring, Factory> factories; void load(std::wstring path, std::vector<IWidget*>& ws) { std::wifstream source(path); while (source) { std::wstring name; source >> name; if (name.empty()) return; else if (name == L"import") { source >> name; HMODULE m = modules[name] = LoadLibrary(name.append(L".dll").c_str()); Info i = (Info)GetProcAddress(m, "info"); if (i == nullptr) throw Error{}; const char* x = i(); while (x != nullptr && *x != '\0') { size_t l = strlen(x); factories[stows(x)] = (Factory)GetProcAddress(m, std::string("factory").append(x).c_str()); x += l + 1; } continue; } Factory f; auto i1 = factories.lower_bound(name); if (i1 == factories.end() || i1->first != name) { HMODULE m; auto iter = modules.lower_bound(name); if (iter == modules.end() || iter->first != name) m = modules.insert(iter, { name, LoadLibrary(name.append(L".dll").c_str()) })->second; else m = iter->second; f = factories.insert(i1, { name, (Factory)GetProcAddress(m, "factory") })->second; if (f == nullptr) throw Error{}; } else f = i1->second; if (IWidget* w = f(source)) ws.push_back(w); } } ~Resources() { for (auto& m : modules) FreeLibrary(m.second); } }; #endif // !EIO_GAME_HPP
0bc5ace0e428c8bb7f0e7e063002c6bfc93d391c
39360906839fb8572f5a348906a501f950fa42bf
/lab_test.cpp
971a07a2bde58d3359b1c11277e5d15a48348c89
[]
no_license
subramanyamdvss/cpp-codes
6a92272dfa8437b67086dedc44bd990ea8a99d72
305fdd12591ed1c69fda7fb089f6ea5c2f824da2
refs/heads/master
2021-01-19T13:56:17.047947
2017-02-24T08:35:59
2017-02-24T08:35:59
82,435,590
0
0
null
null
null
null
UTF-8
C++
false
false
4,702
cpp
lab_test.cpp
// NAME: DVSS SUBRAMANYAM ROLL NO: 15CS10013 MACHINE NUMBER :56 ,,QUESTION PAPER :EVEN #include <bits/stdc++.h> using namespace std; typedef long long lli; typedef vector< long long int > vi; typedef double d; typedef pair<lli,pair<lli,lli> > pipii; #define bg begin() #define rbg rbegin() #define ren rend() #define en end() #define f first #define s second #define For(ii,aa,bb) for(lli ii=aa;ii<=bb;++ii) #define Rof(ii,aa,bb) for(lli ii=aa;ii>=bb;--ii) #define pb push_back #define minf(a,b,c) min(min(a,b),c) #define maxf(a,b,c) max(max(a,b),c) #define mp make_pair #define error(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); } vector<string> split(const string& s, char c) { vector<string> v; stringstream ss(s); string x; while (getline(ss, x, c)) v.emplace_back(x); return move(v); } void err(vector<string>::iterator it) {} template<typename T, typename... Args> void err(vector<string>::iterator it, T a, Args... args) { cerr << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << '\n'; err(++it, args...); } template < typename F, typename S > ostream& operator << ( ostream& os, const pair< F, S > & p ) { return os << "(" << p.first << ", " << p.second << ")"; } template < typename T > ostream &operator << ( ostream & os, const vector< T > &v ) { os << "{"; typename vector< T > :: const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "}"; } template < typename T > ostream &operator << ( ostream & os, const set< T > &v ) { os << "["; typename set< T > :: const_iterator it; for ( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "]"; } template < typename F, typename S > ostream &operator << ( ostream & os, const map< F, S > &v ) { os << "["; typename map< F , S >::const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << it -> first << " = " << it -> second ; } return os << "]"; } #define deb(x) cerr << #x << " = " << x << endl; // NAME: DVSS SUBRAMANYAM ROLL NO: 15CS10013 MACHINE NUMBER :56 ,,QUESTION PAPER :EVEN //if s[i] is sum of elements from 0 to i ,, and p[i] be the value which we want s[i] to be //then s[i]=p[i] only if any of s[i-1]+a[i] or s[i-1]-b[i] is equal to p[i] so we can calculate the value of p[i-1] if we know which //one whether a[i] or -b[i] is the right number lli S(lli i,lli s[],lli *a ,lli *b, lli n , lli p[],lli ck[]){ if(s[i]!=-1000000){ return s[i]; } if(i==0){ return 0; } if(s[i]==-1000000){ if(s[i-1]==-1000000){ p[i-1]=p[i]-a[i]; lli q=S(i-1,s,a,b,n,p,ck); if(q+a[i]==p[i]){ ck[i]=0; s[i]=q+a[i]; } p[i-1]=p[i]+b[i]; q=S(i-1,s,a,b,n,p,ck); if(q-b[i]==p[i]){ p[i-1]=p[i]+b[i]; ck[i]=1; s[i]=q-b[i]; } return s[i]; } /*if(s[i-1]!=-1000000){ error("qq"); lli q=s[i-1]; if(q+a[i]==p[i]){ p[i-1]=p[i]-a[i]; ck[i]=0; s[i]=q+a[i]; } if(q-b[i]==p[i]){ p[i-1]=p[i]+b[i]; ck[i]=1; s[i]=q-b[i]; } return s[i]; }*/ } } bool choiceexists(lli *a,lli *b, lli n,lli * ck){ lli p[n]; memset(p,0,sizeof(p)); lli s[n]; For(i,0,n-1){ s[i]=-1000000; } p[n-1]=0; lli q=S(n-1,s,a,b,n,p,ck); if(q==0){ return true; } else false; } void printchoice(lli *a,lli *b,lli n,lli * ck){ lli suma=0,sumb=0; For(i,1,n-1){ if(ck[i]==0){ cout<<a[i]<<" "; suma+=a[i]; } else{ sumb+=b[i]; cout<<-b[i]<<" "; } } cout<<endl; cout<<"\nsum of elements choosen from X is :"<<suma<<endl; cout<<"\nsum of elements choosen from Y is :"<<sumb<<endl; return; } int main(){ lli n; cin>>n; lli a[n+1],b[n+1]; cout<<"input a:\n"; For(i,1,n){ cin>>a[i]; } a[0]=0; cout<<"input b:\n"; For(i,1,n){ cin>>b[i]; } b[0]=0; lli ck[n+1]; memset(ck,0,sizeof(ck)); if(choiceexists(a,b,n+1,ck)){ cout<<" yes the choice exists"<<endl; printchoice(a,b,n+1,ck); } else cout<<" the choice doesnt exists"<<endl; }
63ed52e073434f15a2c93619931b0806416efeb0
a6a9a18453209ee6787c15482053fb53b4fd1d43
/Classes/Game/AI/AIBrain/States/JumpBrainState.h
a6f80fc4dbe0c7fed6b82d18945e5d300192235e
[]
no_license
derekmpeterson/BouncyHouseCocos
4145fa75d42fe258f9cddab87020883b6877f2d0
51f248e703ddff0f90e05b45f7ef211ca8ec8232
refs/heads/master
2016-09-13T12:59:11.948897
2016-04-26T16:43:34
2016-04-26T16:43:34
57,144,998
0
1
null
null
null
null
UTF-8
C++
false
false
723
h
JumpBrainState.h
// // JumpBrainState.hpp // BouncyHouse // // Created by Derek Peterson on 1/15/16. // // #ifndef JumpBrainState_hpp #define JumpBrainState_hpp #include "RunBrainState.h" class JumpBrainState : public RunBrainState { private: EntityHandle m_munitionHandle; public: JumpBrainState(); virtual ~JumpBrainState() override; virtual void Enter() override; virtual void Exit() override; virtual void OnActivate() override; virtual void OnDeactivate() override; void OnGroundChangedEvent( cocos2d::EventCustom* i_event ); void OnAvatarAction_Jump( cocos2d::EventCustom* i_event ); void OnMunitionContactEvent( cocos2d::EventCustom* i_event ); }; #endif /* JumpBrainState_hpp */
b67439191bd8eff5d5c8d92aefe32521df1403b4
8dfc3bbb741bcd0a716c981ead0cbd48b7773bbf
/omnet/Enlace/fisico.cc
5980ea2d4240019c42bd4e8adcd21c5ca4865fe4
[]
no_license
armando-ferro/TFM
2d0f49324cbd96e722f829fe6ee5129fd2bb5c98
1be812c035b522eafbdd8a18a8d5575d72ad8952
refs/heads/master
2021-06-02T06:46:08.608471
2016-09-19T09:27:48
2016-09-19T09:27:48
114,017,838
0
1
null
2017-12-12T17:11:56
2017-12-12T17:11:56
null
ISO-8859-1
C++
false
false
7,398
cc
fisico.cc
// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // #include <string.h> #include <omnetpp.h> #include <simtime.h> #include "Inter_Layer_m.h" #include "Link_m.h" #include "Types.h" /*Estados*/ const short idle = 0; const short sending = 1; class fisico: public cSimpleModule { private: /*gestiones internas*/ int max_state; int header_tam; short state_machine; cQueue *txQueue; cChannel * txChannel; cMessage *sent; bool b_up,b_down; /*extracción de estadísticas*/ int sndBit; int sndPkt; int rcvBit; int rcvPkt; int lostPkt; int errorPkt; simsignal_t s_sndBit; simsignal_t s_sndPkt; simsignal_t s_rcvPkt; simsignal_t s_rcvBit; simsignal_t s_lostPkt; simsignal_t s_errorPkt; simsignal_t s_queueTam; public: fisico(); virtual ~fisico(); protected: /*Funciones*/ virtual void initialize(); virtual void handleMessage(cMessage *msg); virtual void send_out(cPacket *pk); virtual void send_up(cPacket *pk); }; // The module class needs to be registered with OMNeT++ Define_Module(fisico); fisico::fisico() { /*gestion de funcionamiento*/ header_tam = 0; state_machine = idle; txQueue = NULL; txChannel = NULL; sent = NULL; max_state = -1; /*extracción de estadísticas*/ sndBit = 0; sndPkt = 0; rcvBit = 0; rcvPkt = 0; lostPkt = 0; errorPkt = 0; s_sndBit = 0; s_sndPkt = 0; s_rcvBit = 0; s_rcvPkt = 0; s_lostPkt = 0; s_errorPkt = 0; s_queueTam = 0; b_up = true; b_down = true; WATCH(max_state); } fisico::~fisico() { cancelAndDelete(sent); txQueue->~cQueue(); } void fisico::initialize(){ /*recoger parámetros*/ if(par("Queue_Length").containsValue()){ max_state = par("Queue_Length"); } if(par("Header_Tam").containsValue()){ header_tam = par("Header_Tam"); } /*Enganchar señales*/ s_sndBit = registerSignal("sndBit"); s_sndPkt = registerSignal("sndPkt"); s_rcvBit = registerSignal("rcvBit"); s_rcvPkt = registerSignal("rcvPkt"); s_lostPkt = registerSignal("lostPkt"); s_errorPkt = registerSignal("errorPkt"); s_queueTam = registerSignal("QueueState"); /*Cola de mensajes a enviar*/ txQueue = new cQueue("txQueue"); /*mensaje que indica cuando se ha terminado de enviar un packete*/ sent = new cMessage("sent"); /*Canal de salida*/ if(gate("out")->isConnected()){ txChannel = gate("out")->getTransmissionChannel(); }else{ b_down = false; } if(not(gate("up_out")->isConnected())){ b_up = false; } WATCH(state_machine); WATCH(max_state); WATCH(b_up); } void fisico::handleMessage(cMessage *msg){ if(msg == sent){ /*propio comprobar cola o idle*/ if(txQueue->empty()){ /*No hay mensajen en cola se espera otro*/ state_machine = idle; }else{ /*se debe extraer un mensaje de la cola y enviar*/ cPacket *message = (cPacket *)txQueue->pop(); emit(s_queueTam,txQueue->length()); send_out(message); } } else{ /*comprobar si es de capa superior o exterior*/ if(msg->arrivedOn("up_in")){ /*capa superior, extraer comprobar estado*/ if(not(b_down)){ bubble("Imposible mandar mensajes, no conectado"); delete(msg); return; } inter_layer *rx = check_and_cast<inter_layer *>(msg); cPacket *pk; if(rx->hasEncapsulatedPacket()){ pk = rx->decapsulate(); }else{ delete(rx); return; } if(state_machine == idle){ /*enviar mensaje*/ send_out(pk); }else{ /*enviando otro paquete, meterlo en la cola*/ /*comprobar cola*/ if(max_state >= 0){ /*hay limite*/ if(txQueue->length() >= max_state){ /*se ha superado el limite*/ char msgname[20]; sprintf(msgname,"cola llena-%d",max_state); bubble(msgname); delete(pk); emit(s_lostPkt,++lostPkt); }else{ /*todavía hay sitio*/ txQueue->insert(pk); emit(s_queueTam,txQueue->length()); } }else{ /*no hay limite*/ txQueue->insert(pk); emit(s_queueTam,txQueue->length()); } } delete(rx); }else{ /*externo, comprobar eror y tipo, desencapsular y subir a la capa superior*/ if(not(b_up)){ bubble("Imposible mandar mensajes, no conectado"); delete(msg); return; } Link * rxp = check_and_cast<Link *>(msg); if(rxp->hasBitError()){ bubble("Paquete con error"); emit(s_errorPkt,++errorPkt); delete(rxp); }else{ if(rxp->getType()!=e_msg_t){ bubble("Tipo erróneo"); delete(rxp); } if(rxp->hasEncapsulatedPacket()){ cPacket *data = (cPacket *) rxp->decapsulate(); int tam = data->getBitLength(); rcvBit += tam; emit(s_rcvBit,rcvBit); emit(s_rcvPkt,++rcvPkt); send_up(data); }else{ bubble("Paquete inesperado"); } delete(rxp); } } } } void fisico::send_out(cPacket * pk){ /*empaquetar sacar estadísticas*/ int tam; tam = pk->getBitLength(); sndBit += tam; char msgname[20]; sprintf(msgname,"fisico-%d",++sndPkt); Link *rx = new Link(msgname,0); rx->setBitLength(header_tam); rx->encapsulate(pk); /*llenar cabecera*/ rx->setType(e_msg_t); rx->setSeq(sndPkt); /*enviar por out*/ send(rx,"out"); state_machine = sending; /*programar el auto mensaje para cambair de estado*/ simtime_t txFinishTime = txChannel->getTransmissionFinishTime(); scheduleAt(txFinishTime,sent); emit(s_sndBit,sndBit); emit(s_sndPkt,sndPkt); } void fisico::send_up(cPacket *pk){ /*encapsular con la información*/ inter_layer *il = new inter_layer("fisicoUP",0); il->encapsulate(pk); send(il,"up_out"); }
78e2a756f9711371b223bb57e7075a607e595330
9d90c683c0f8dbdf5a8cb0de46111e0d7c4d67f5
/JSON.h
5ebc7c0fd3b3e135c07cb0928df25e8dac87bccf
[]
no_license
mog422/ImgTL_Windows
485da530cf5dc7cedce7335239b6c8237bd456f4
a608ecafb5b1e84f934f51cc261cd70a2f64a66c
refs/heads/master
2021-01-18T12:30:34.301178
2014-09-23T00:19:35
2014-09-23T00:19:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,241
h
JSON.h
#pragma once #include "Util.h" #include <map> #include <vector> #include <memory> class JSONParseException : public std::exception { public: JSONParseException() : std::exception("Exception while parsing JSON string") {} }; class JSONValueTypeMismatchException : public std::exception { public: JSONValueTypeMismatchException() : std::exception("Exception while retrieving JSON value") {} }; class JSONValue; typedef std::map<std::string, JSONValue> JSONObject; class JSONValue { private: std::shared_ptr<void> m_value; enum JSONValueType { TYPE_INVALID = 0, TYPE_NUMBER, TYPE_STRING, TYPE_OBJECT, TYPE_NULL, TYPE_BOOLEAN, TYPE_ARRAY, }; JSONValueType m_type; public: JSONValue() : m_type(TYPE_INVALID) {} ~JSONValue() {} void setBooleanValue(const bool value) { m_type = TYPE_BOOLEAN; m_value = std::shared_ptr<int>(new int(value)); } void setNull() { m_type = TYPE_NULL; } void setNumberValue(const double value) { m_type = TYPE_NUMBER; m_value = std::shared_ptr<double>(new double(value)); } void setStringValue(const std::string &value) { m_type = TYPE_STRING; m_value = std::shared_ptr<std::string>(new std::string(value)); } void setObjectValue(const JSONObject &value) { m_type = TYPE_OBJECT; m_value = std::shared_ptr<JSONObject>(new JSONObject(value)); } void setArrayValue(const std::vector<JSONValue> &value) { m_type = TYPE_ARRAY; m_value = std::shared_ptr<std::vector<JSONValue> >(new std::vector<JSONValue>(value)); } const double operator =(const double value) { setNumberValue(value); } const std::string &operator =(const std::string &value) { setStringValue(value); } const JSONObject &operator =(const JSONObject &value) { setObjectValue(value); } const std::vector<JSONValue> &operator =(const std::vector<JSONValue> &value) { setArrayValue(value); } operator int() { if(m_type == TYPE_NULL) return 0; if(m_type != TYPE_NUMBER && m_type != TYPE_BOOLEAN) throw JSONValueTypeMismatchException(); if(m_type == TYPE_NUMBER) return (int)*((double *)m_value.get()); else return *((int *)m_value.get()); } JSONValue &operator[](const std::string &key) { if(m_type == TYPE_INVALID) setObjectValue(JSONObject()); if(m_type != TYPE_OBJECT) throw JSONValueTypeMismatchException(); return (*(JSONObject *)m_value.get())[key]; } JSONValue &operator[](const char *key) { return operator [](std::string(key)); } JSONValue &operator[](int index) { if(m_type == TYPE_INVALID) setArrayValue(std::vector<JSONValue>()); if(m_type != TYPE_ARRAY) throw JSONValueTypeMismatchException(); return (*(std::vector<JSONValue> *)m_value.get())[index]; } operator std::string() { if(m_type != TYPE_STRING) throw JSONValueTypeMismatchException(); return *((std::string *)m_value.get()); } int getSize() { if(m_type == TYPE_ARRAY) return ((std::vector<JSONValue> *)m_value.get())->size(); throw JSONValueTypeMismatchException(); } bool hasKey(const std::string &key) { if(m_type == TYPE_OBJECT) return ((JSONObject *)m_value.get())->find(key) != ((JSONObject *)m_value.get())->end(); throw JSONValueTypeMismatchException(); } }; class JSONParser { private: static int getNextDelimiterPos(int pos, const std::string &string) { std::string::const_iterator it = string.begin() + pos; int i = 0; for(; it != string.end(); it ++, i ++) { if(*it == ' ' || *it == '\t' || *it == '\r' || *it == '\n' || *it == ',' || *it == ']' || *it == '}') break; } return pos + i; } static int getNextTokenPos(int pos, const std::string &string) { std::string::const_iterator it = string.begin() + pos; int i = 0; for(; it != string.end(); it ++, i ++) { if(*it == ' ' || *it == '\t' || *it == '\r' || *it == '\n') continue; break; } return pos + i; } static JSONValue getJSONValue(int &pos, const std::string &string) { if(string.size() == 0) return JSONValue(); int data = string.at(pos); JSONValue ret; if(data == '[') { pos ++; //begin of array std::vector<JSONValue> values; while(true) { pos = getNextTokenPos(pos, string); if(string.at(pos) == ']') break; if(string.at(pos) == ',') { pos ++; continue; } values.push_back(getJSONValue(pos, string)); } pos ++; ret.setArrayValue(values); } else if(data == '{') { pos ++; //begin of object JSONObject object; while(true) { pos = getNextTokenPos(pos, string); if(string.at(pos) == '}') break; if(string.at(pos) == ',') { pos ++; continue; } std::string key = getJSONString(pos, string); pos = getNextTokenPos(pos, string); data = string.at(pos); if(data != ':') throw JSONParseException(); pos ++; pos = getNextTokenPos(pos, string); object[key] = getJSONValue(pos, string); } pos ++; ret.setObjectValue(object); } else if(data == '\"') { ret.setStringValue(getJSONString(pos, string)); } else { //integer or keyword int pos1 = getNextDelimiterPos(pos, string); std::string temp = string.substr(pos, pos1 - pos); if(temp == "true") ret.setBooleanValue(true); else if(temp == "false") ret.setBooleanValue(false); else if(temp == "null") ret.setNull(); else ret.setNumberValue(StrToDouble(temp)); pos = pos1; } return ret; } static std::string getJSONString(int &pos, const std::string &string) { int data; data = string.at(pos); if(data != '\"') throw JSONParseException(); pos ++; std::string ret; while(true) { if(string.at(pos) == '\"') break; if(string.at(pos) == '\\' && string.at(pos + 1) == '\"') { ret.push_back('\"'); pos += 2; continue; } if(string.at(pos) == '\\' && string.at(pos + 1) == 'u') { //unicode wchar_t data = hexStrToInt(string.substr(pos + 2, 4)); ret.append(wstringToString(std::wstring(data, 1))); pos += 6; continue; } ret.push_back(string.at(pos)); pos ++; } pos ++; //ending " return ret; } public: static JSONValue parseJSONString(const std::string &string) { int pos = 0; return getJSONValue(pos, string); } };
52b8b6fc309b254e7fcf0dafda439fede4e866ee
a2badfee532cf096e9bd12b0892fdce3b49e54c8
/src/modules/builderc.cpp
4ad6eedfb0ddbd5484100c01fca7ae48c8342099
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
unghee/TorchCraftAI
5e5e9b218990db8042198a12aeef78651b49f67b
e6d596483d2a9a8b796765ed98097fcae39b6ac0
refs/heads/master
2022-04-16T12:12:10.289312
2020-04-20T02:55:22
2020-04-20T02:55:22
257,154,995
0
0
MIT
2020-04-20T02:51:19
2020-04-20T02:51:18
null
UTF-8
C++
false
false
30,624
cpp
builderc.cpp
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "modules/builderc.h" #include "modules/builderhelper.h" #include "commandtrackers.h" #include "movefilters.h" #include "utils.h" #include <glog/logging.h> namespace cherrypi { namespace { auto const kMaxBuildAttempts = 3; /// Computes bounding box distance of given unit from build location int pxDistanceOfUnit(Unit* unit, BuildType const* type, Position const& pos) { return utils::pxDistanceBB( unit->unit.pixel_x - unit->type->dimensionLeft, unit->unit.pixel_y - unit->type->dimensionUp, unit->unit.pixel_x + unit->type->dimensionRight, unit->unit.pixel_y + unit->type->dimensionDown, pos.x * tc::BW::XYPixelsPerWalktile, pos.y * tc::BW::XYPixelsPerWalktile, (pos.x + type->tileWidth * tc::BW::XYWalktilesPerBuildtile) * tc::BW::XYPixelsPerWalktile, (pos.y + type->tileHeight * tc::BW::XYWalktilesPerBuildtile) * tc::BW::XYPixelsPerWalktile); } } // namespace BuilderControllerBase::BuilderControllerBase( Module* module, BuildType const* type, std::unordered_map<Unit*, float> unitProbs, std::shared_ptr<BuilderControllerData> bcdata) : Controller(module), type_(type), unitProbs_(std::move(unitProbs)), bcdata_(std::move(bcdata)) {} void BuilderControllerBase::grabUnit(State* state, Unit* unit) { auto* board = state->board(); auto ctask = std::dynamic_pointer_cast<ControllerTask>(board->taskForId(upcId_)); if (ctask == nullptr) { LOG(WARNING) << "No associated controller task? That's weird."; return; } if (ctask->finished()) { // Prevent spawning new tasks if the task is finished, since // it would keep the build task alive (important when tasks are cancelled). VLOG(1) << "Task " << utils::upcString(upcId_) << " is finished, cowardly refusing to grab another unit"; return; } // We'll want to grab a builder or move a unit out of the way. Take control // of unit by posting and consuming a UPC with it. This way we'll receive a // new UPC Id, which lets us bind the unit to a new (do-nothing) task. auto upc = std::make_shared<UPCTuple>(); upc->unit[unit] = 1; upc->command[Command::Create] = 0.5; upc->command[Command::Move] = 0.5; auto newId = board->postUPC(std::move(upc), upcId_, module_); board->consumeUPC(newId, module_); // Instantiate another controller task so that unit management wrt controller // is unified. board->postTask( std::make_shared<ControllerTask>( newId, std::unordered_set<Unit*>{unit}, state, ctask->controller()), module_, true); Controller::addUnit(state, unit, newId); VLOG(1) << "BuilderControllerBase " << utils::upcString(upcId_) << ": took control of unit " << utils::unitString(unit) << " via " << utils::upcString(newId); } void BuilderControllerBase::releaseUnit(State* state, Unit* unit) { auto task = state->board()->taskWithUnitOfModule(unit, module_); if (task == nullptr) { auto taskData = state->board()->taskDataWithUnit(unit); auto has = units_.find(unit) != units_.end(); VLOG(has ? 0 : 1) << "BuilderControllerBase " << utils::upcString(upcId_) << ": cannot release unit " << utils::unitString(unit) << ": not owned by our tasks but by " << (taskData.owner ? taskData.owner->name() : "nobody") << " and controller thinks we " << (has ? "own it" : "don't own it"); units_.erase(unit); upcs_.erase(unit); return; } Controller::removeUnit(state, unit, task->upcId()); task->removeUnit(unit); state->board()->updateTasksByUnit(task.get()); VLOG(1) << "BuilderControllerBase " << utils::upcString(upcId_) << ": release unit " << utils::unitString(unit) << " from " << utils::upcString(task->upcId()); } /// Returns scoring function for selecting a unit to build another /// (non-building) unit auto BuilderControllerBase::defaultUnitBuilderScore(State* state) { return [this, state](Unit* u) { if (u->type != type_->builder) { return kdInfty; } if (!u->active()) { return kdInfty; } if (type_->isAddon && u->addon) { return kdInfty; } double score = 0.0; if (builder_ == u) { score -= 10.0; } else if (state->board()->taskDataWithUnit(u).owner == module_) { // We're already building something with this one return kdInfty; } score += u->remainingBuildTrainTime + u->remainingUpgradeResearchTime; return score; }; } /// Returns scoring function for selecting a unit to build a Larva-based unit. auto BuilderControllerBase::larvaBuilderScore( State* state, bool preferSaturation) { // Compute hatchery counts of Larvae std::unordered_map<int, int> larvaCount; for (Unit* u : state->unitsInfo().myCompletedUnitsOfType(buildtypes::Zerg_Larva)) { if (u->associatedUnit) { larvaCount[u->associatedUnit->id] += 1; } } return [this, state, preferSaturation, larvaCount = std::move(larvaCount)]( Unit* u) { if (u->type != type_->builder) { return kdInfty; } if (!u->active()) { return kdInfty; } double score = 0.0; if (builder_ == u) { score -= DFOASG(10, 5); } else { auto taskData = state->board()->taskDataWithUnit(u); if (taskData.owner == module_) { // We're already building something with this one return kdInfty; } // Better build at a Hatchery with lots of Larva so that we'll get more if (u->associatedUnit && u->associatedUnit->type->producesLarva) { auto iterator = larvaCount.find(u->associatedUnit->id); if (iterator != larvaCount.end()) { double larva = iterator->second; larva += utils::clamp( double(state->currentFrame() - u->lastLarvaSpawn) / kLarvaFrames, 0.0, 1.0); double bonus = 4 - larva; bonus = bonus * bonus; score += bonus; // (1,16) } } // Build at bases where we have low saturation auto& areaInfo = state->areaInfo(); auto baseIdx = areaInfo.myClosestBaseIdx(u->pos()); if (baseIdx >= 0) { double saturation = areaInfo.myBase(baseIdx)->saturation; // 4, so it will pick a 2-Larva Hatchery over 1 Larva, but not 3 over 2 score += DFOASG(4, 2) * (preferSaturation ? 1.0 - saturation : saturation); // (0, 5) } } score += u->remainingBuildTrainTime + u->remainingUpgradeResearchTime; return score; }; } /// Returns scoring function for selecting a unit to morph a hatchery or lair auto BuilderControllerBase::hatcheryTechBuilderScore(State* state) { return [this, state](Unit* u) { if (u->type != type_->builder) { return kdInfty; } if (!u->active()) { return kdInfty; } double score = 0.0; if (builder_ == u) { score -= 10.0; } else { auto taskData = state->board()->taskDataWithUnit(u); if (taskData.owner == module_) { // We're already building something with this one return kdInfty; } } // Prefer Lair and Hive in early bases score += 10 * state->areaInfo().myClosestBaseIdx(u->pos()); if (u->morphing()) { score += u->remainingBuildTrainTime; } score += u->remainingUpgradeResearchTime; return score; }; } bool BuilderControllerBase::cancelled(State* state) const { // XXX This is a hotfix since step() is currently sometimes called for // cancelled tasks. This should not be the case and somebody should check for // this beforehand (BuilderModule?). For now just do a manual check to avoid // regressions. auto* board = state->board(); auto ctask = std::dynamic_pointer_cast<ControllerTask>(board->taskForId(upcId_)); if (ctask == nullptr) { LOG(WARNING) << "No associated controller task? That's weird."; return false; } return ctask->status() == TaskStatus::Cancelled; } bool BuilderControllerBase::findBuilder(State* state, Position const& pos) { auto board = state->board(); if (type_->isBuilding && type_->builder->isWorker) { if (pos.x != -1 || pos.y != -1) { // Try to find a builder close to the targeted location auto builderScore = [&](Unit* u) { if (u->type != type_->builder) { return kdInfty; } if (!u->active()) { return kdInfty; } double r = 0.0; if (builder_ == u) { r -= DFOASG(10, 5); } else { auto taskData = board->taskDataWithUnit(u); if (taskData.owner == module_) { // We're already building something with this one return kdInfty; } if (taskData.task && taskData.owner && (taskData.owner->name().find("Scouting") != std::string::npos || taskData.owner->name().find("Harass") != std::string::npos)) { return kdInfty; } if (!u->idle() && !u->unit.orders.empty()) { if (u->unit.orders.front().type == tc::BW::Order::MoveToMinerals) { r += 15.0; } else if ( u->unit.orders.front().type == tc::BW::Order::ReturnMinerals) { r += 60.0; } else if ( u->unit.orders.front().type == tc::BW::Order::MoveToGas) { r += 75.0; } else if ( u->unit.orders.front().type == tc::BW::Order::ReturnGas) { r += 90.0; } else { r += 150.0; } } auto i = bcdata_->recentAssignedBuilders.find(u); if (i != bcdata_->recentAssignedBuilders.end()) { if (std::get<1>(i->second) == type_ && utils::distance( std::get<2>(i->second).x, std::get<2>(i->second).y, pos.x, pos.y) <= DFOASG(48, 24)) { r -= DFOASG(1000.0, 500); } } } r += utils::distance(u, pos) / u->topSpeed; return r; }; if (builder_ && builderScore(builder_) == kdInfty) { builder_->busyUntil = 0; builder_ = nullptr; } if (!builder_) { std::vector<Unit*> candidates; for (auto it : unitProbs_) { if (it.second > 0 && it.first->type == type_->builder) { candidates.push_back(it.first); } } if (!candidates.empty()) { builder_ = utils::getBestScoreCopy( std::move(candidates), builderScore, kdInfty); } else { builder_ = utils::getBestScoreCopy( state->unitsInfo().myCompletedUnitsOfType(type_->builder), builderScore, kdInfty); } } } else if (builder_) { builder_ = nullptr; } } else { std::function<double(Unit*)> builderScore; if (type_ == buildtypes::Zerg_Drone) { // Build new drones at unsaturated bases that contain lots of larva. builderScore = larvaBuilderScore(state, false); } else if (type_->builder == buildtypes::Zerg_Larva) { // Build other Zerg units at saturated bases that contain lots of larva. builderScore = larvaBuilderScore(state, true); } else if ( type_ == buildtypes::Zerg_Lair || type_ == buildtypes::Zerg_Hive) { builderScore = hatcheryTechBuilderScore(state); } else { builderScore = defaultUnitBuilderScore(state); } if (builder_ && builderScore(builder_) == kdInfty) { builder_->busyUntil = 0; builder_ = nullptr; } if (!builder_) { std::vector<Unit*> candidates; for (auto it : unitProbs_) { if (it.second > 0 && it.first->type == type_->builder) { candidates.push_back(it.first); } } if (!candidates.empty()) { builder_ = utils::getBestScoreCopy( std::move(candidates), builderScore, kdInfty); } else { builder_ = utils::getBestScoreCopy( state->unitsInfo().myCompletedUnitsOfType(type_->builder), builderScore, kdInfty); } } } return builder_ != nullptr; } WorkerBuilderController::WorkerBuilderController( Module* module, BuildType const* type, std::unordered_map<Unit*, float> unitProbs, std::shared_ptr<BuilderControllerData> bcdata, Position pos) : BuilderControllerBase( module, type, std::move(unitProbs), std::move(bcdata)), pos_(std::move(pos)) { if (!type->isBuilding) { throw std::runtime_error("Building expected, got " + type->name); } if (type->builder == nullptr) { throw std::runtime_error("Don't know how to build " + type->name); } if (!type->builder->isWorker) { throw std::runtime_error("No worker required to build " + type->name); } } void WorkerBuilderController::step(State* state) { auto board = state->board(); auto frame = state->currentFrame(); if (succeeded_ || failed_ || cancelled(state)) { return; } // Regularly check if building location is still valid if (!building_ && frame - lastCheckLocation_ >= 11) { lastCheckLocation_ = frame; // Ignore reserved tiles in this check since reservations for buildings are // not handled by this module. if (!builderhelpers::canBuildAt(state, type_, pos_, true)) { VLOG(1) << logPrefix() << " location is no longer valid; marking task as failed"; failed_ = true; return; } } if (moving_ && tracker_) { // Worker is moving to build location switch (tracker_->status()) { case TrackerStatus::Success: // This task didn't succeed yet, we need to start the building now // (this is done in BuilderModule). VLOG_IF(1, (tracker_->status() != trackerStatus_)) << logPrefix() << " movement tracker reported success, resetting"; lastUpdate_ = 0; moving_ = false; tracker_ = nullptr; break; case TrackerStatus::Cancelled: VLOG_IF(2, (tracker_->status() != trackerStatus_)) << logPrefix() << " tracker cancelled but task not cancelled" << " marking task as failed"; failed_ = true; case TrackerStatus::Timeout: case TrackerStatus::Failure: moving_ = false; tracker_ = nullptr; VLOG(1) << logPrefix() << " movement tracker reported timeout/failure"; break; case TrackerStatus::Pending: case TrackerStatus::Ongoing: VLOG_IF(2, (tracker_->status() != trackerStatus_)) << logPrefix() << " movement tracker reported pending/ongoing, " "status->ongoing"; break; default: break; } } else if (!moving_ && tracker_) { switch (tracker_->status()) { case TrackerStatus::Pending: VLOG_IF(2, (tracker_->status() != trackerStatus_)) << logPrefix() << " tracker reported pending, status->ongoing"; break; case TrackerStatus::Ongoing: VLOG_IF(2, (tracker_->status() != trackerStatus_)) << logPrefix() << " tracker reported ongoing, status->ongoing"; constructionStarted_ = true; break; case TrackerStatus::Success: VLOG(1) << logPrefix() << " success, finished task"; building_ = false; succeeded_ = true; break; case TrackerStatus::Timeout: case TrackerStatus::Failure: if (buildAttempts_ < kMaxBuildAttempts) { VLOG(1) << logPrefix() << " building tracker " << (tracker_->status() == TrackerStatus::Timeout ? "timed out" : "failed") << ", scheduling retry"; lastUpdate_ = 0; } else { VLOG(1) << logPrefix() << " building tracker " << (tracker_->status() == TrackerStatus::Timeout ? "timed out" : "failed") << ", giving up"; failed_ = true; } tracker_ = nullptr; building_ = false; break; case TrackerStatus::Cancelled: LOG(ERROR) << logPrefix() << " canceled tracker without canceled task "; failed_ = true; break; default: break; } } if (tracker_) { trackerStatus_ = tracker_->status(); } if (succeeded_ || failed_) { return; } std::vector<uint8_t> visited; uint8_t visitedN = 0; auto findMoveAwayPos = [&](Unit* u, Position source, float distance) { if (visited.empty()) { visited.resize(TilesInfo::tilesWidth * TilesInfo::tilesHeight); } const int mapWidth = state->mapWidth(); const int mapHeight = state->mapHeight(); bool flying = u->flying(); uint8_t visitedValue = ++visitedN; auto* tilesData = state->tilesInfo().tiles.data(); Position startPos(u->x, u->y); std::deque<const Tile*> open; open.push_back(&state->tilesInfo().getTile(u->x, u->y)); while (!open.empty()) { const Tile* tile = open.front(); open.pop_front(); if (utils::distance(tile->x, tile->y, source.x, source.y) >= distance) { return Position(tile->x, tile->y); } auto add = [&](const Tile* ntile) { if (!flying && (!tile->entirelyWalkable || tile->building)) { return; } auto& v = visited[ntile - tilesData]; if (v == visitedValue) { return; } v = visitedValue; if (utils::distance(ntile->x, ntile->y, startPos.x, startPos.y) <= 4 * 20) { open.push_back(ntile); } }; if (tile->x > 0) { add(tile - 1); } if (tile->y > 0) { add(tile - TilesInfo::tilesWidth); } if (tile->x < mapWidth - tc::BW::XYWalktilesPerBuildtile) { add(tile + 1); } if (tile->y < mapHeight - tc::BW::XYWalktilesPerBuildtile) { add(tile + TilesInfo::tilesHeight); } } return Position(); }; if (builder_ && VLOG_IS_ON(2)) { utils::drawLine(state, builder_, pos_); utils::drawText(state, pos_, type_->name); } if (lastMoveUnitsInTheWay_ && frame - lastMoveUnitsInTheWay_ >= 30) { lastMoveUnitsInTheWay_ = 0; for (auto* u : movedUnits_) { releaseUnit(state, u); } movedUnits_.clear(); } if (!constructionStarted_) { bcdata_->res.ore -= type_->mineralCost; bcdata_->res.gas -= type_->gasCost; } // Update required? if (lastUpdate_ > 0 && frame - lastUpdate_ < 4) { return; } lastUpdate_ = frame; bool moveOnly = false; if (!constructionStarted_) { if (type_->mineralCost && bcdata_->res.ore < 0) { moveOnly = true; } if (type_->gasCost && bcdata_->res.gas < 0) { moveOnly = true; } if (type_->supplyRequired && bcdata_->res.used_psi + type_->supplyRequired > bcdata_->res.total_psi) { moveOnly = true; } if (!moveOnly) { if (!utils::prerequisitesReady(state, type_)) { moveOnly = true; } } } if (builder_ && (pos_.x != -1 || pos_.y != -1)) { bcdata_->recentAssignedBuilders[builder_] = std::make_tuple(frame, type_, pos_); } // Find a builder if (!builder_ && !building_) { findBuilder(state, pos_); if (builder_) { if (moveOnly && (pos_.x != -1 || pos_.y != -1)) { double t = 0.0; if (type_->mineralCost) { t = std::max(t, -bcdata_->res.ore / bcdata_->currentMineralsPerFrame); } if (type_->gasCost) { t = std::max(t, -bcdata_->res.gas / bcdata_->currentGasPerFrame); } if (t > utils::distance(builder_, pos_) / builder_->topSpeed) { builder_ = nullptr; } } if (builder_) { VLOG(1) << logPrefix() << " found builder: " << utils::unitString(builder_); grabUnit(state, builder_); } } if (builder_ == nullptr) { VLOG(1) << logPrefix() << " could not determine builder right now"; } } if (type_->isBuilding) { if (builder_ && (pos_.x != -1 || pos_.y != -1)) { if (!detector_) { detector_ = utils::getBestScoreCopy( state->unitsInfo().myUnits(), [&](Unit* u) { if (!u->type->isDetector || u->type->isBuilding || !u->active() || board->taskWithUnit(u)) { return kdInfty; } return (double)utils::distance(u, pos_); }, kdInfty); if (detector_) { grabUnit(state, detector_); } } else { auto tgt = movefilters::safeMoveTo(state, detector_, pos_); if (tgt.x < 0 || tgt.y < 0) { VLOG(1) << "detector stuck"; tgt = pos_; } else if (tgt.distanceTo(detector_->getMovingTarget()) > 4) { // condition made to avoid sending too many commands addUpc(detector_, tgt, Command::Move); } } // hack: we should not rely on movement tracker // re-send move every now and then if not close to destination float distFromBuilderToDestThreshold = 4.0f * 2; if (type_->isRefinery) { distFromBuilderToDestThreshold = 4.0f * 6; } Position targetPosition( std::min( pos_.x + type_->tileWidth * tc::BW::XYWalktilesPerBuildtile / 2, state->mapWidth() - 1), std::min( pos_.y + type_->tileHeight * tc::BW::XYWalktilesPerBuildtile / 2, state->mapHeight() - 1)); auto distFromBuilderToDest = utils::distance(builder_, targetPosition); if (tracker_ == nullptr || distFromBuilderToDest >= distFromBuilderToDestThreshold) { if (distFromBuilderToDest >= distFromBuilderToDestThreshold) { auto tgt = movefilters::safeMoveTo(state, builder_, targetPosition); if (tgt.x < 0 || tgt.y < 0) { VLOG(1) << "builder stuck"; tgt = targetPosition; // well, that won't do anything } if (tgt.distanceTo(builder_->getMovingTarget()) > 4) { addUpc(builder_, tgt, Command::Move); if (!tracker_) { tracker_ = state->addTracker<MovementTracker>( std::initializer_list<Unit*>{builder_}, targetPosition.x, targetPosition.y, distFromBuilderToDestThreshold); trackerStatus_ = tracker_->status(); moving_ = true; VLOG(3) << logPrefix() << " using MovementTracker, distance=" << distFromBuilderToDest << ", threshold=" << distFromBuilderToDestThreshold; } } } else if (!moveOnly) { // and tracker_ == nullptr // Any units we need to get out of the way to build here? Unit* killUnit = nullptr; int movedUnits = 0; for (Unit* e : state->unitsInfo().visibleUnits()) { if (!e->flying() && !e->invincible() && e != builder_ && e->detected() && !e->type->isBuilding) { auto d = pxDistanceOfUnit(e, type_, pos_); if (e->isMine && !e->type->isNonUsable && d <= 16) { Position target = findMoveAwayPos(e, Position(builder_), 16); lastMoveUnitsInTheWay_ = frame; // Grab that unit and move it away movedUnits_.insert(e); grabUnit(state, e); if (e->burrowed()) { state->board()->postCommand( tc::Client::Command( tc::BW::Command::CommandUnit, e->id, tc::BW::UnitCommandType::Unburrow), upcId_); } addUpc(e, target, Command::Move); VLOG(1) << logPrefix() << " moving " << utils::unitString(e) << " out of the way"; ++movedUnits; continue; } if (d <= 0) { VLOG(1) << logPrefix() << " going to kill blocking unit " << utils::unitString(e); killUnit = e; break; } } } if (killUnit) { for (auto* u : movedUnits_) { releaseUnit(state, u); } movedUnits_.clear(); addUpc(builder_, killUnit, Command::Delete); } else { if (movedUnits) { ++moveAttempts_; } if (!movedUnits || moveAttempts_ >= 12) { ++buildAttempts_; } if (buildAttempts_ > kMaxBuildAttempts) { // Block tiles at build location for some time, maybe it will // work then. buildAttempts_ = 0; for (int y = pos_.y; y != pos_.y + tc::BW::XYWalktilesPerBuildtile * type_->tileHeight; ++y) { for (int x = pos_.x; x != pos_.x + tc::BW::XYWalktilesPerBuildtile * type_->tileWidth; ++x) { Tile* t = state->tilesInfo().tryGetTile(x, y); if (t) { t->blockedUntil = std::max( t->blockedUntil, state->currentFrame() + 15 * 30); } } } } tracker_ = state->addTracker<BuildTracker>(builder_, type_, 15); trackerStatus_ = tracker_->status(); building_ = true; addUpc(builder_, pos_, Command::Create, type_); } VLOG(3) << logPrefix() << " using BuildTracker, distance = " << utils::distance(builder_, pos_); } } } } postUpcs(state); } void WorkerBuilderController::removeUnit(State* state, Unit* unit, UpcId id) { if (unit == builder_) { builder_ = nullptr; } if (unit == detector_) { detector_ = nullptr; } BuilderControllerBase::removeUnit(state, unit, id); } std::string WorkerBuilderController::logPrefix() const { std::ostringstream oss; oss << "WorkerBuilderController for task " << utils::upcString(upcId_) << " (" << utils::buildTypeString(type_) << "):"; return oss.str(); } BuilderController::BuilderController( Module* module, BuildType const* type, std::unordered_map<Unit*, float> unitProbs, std::shared_ptr<BuilderControllerData> bcdata) : BuilderControllerBase( module, type, std::move(unitProbs), std::move(bcdata)) {} void BuilderController::step(State* state) { auto frame = state->currentFrame(); if (succeeded_ || failed_ || cancelled(state)) { return; } if (tracker_) { switch (tracker_->status()) { case TrackerStatus::Pending: VLOG_IF(2, (tracker_->status() != trackerStatus_)) << logPrefix() << " tracker reported pending, status->ongoing"; break; case TrackerStatus::Ongoing: VLOG_IF(2, (tracker_->status() != trackerStatus_)) << logPrefix() << " tracker reported ongoing, status->ongoing"; constructionStarted_ = true; break; case TrackerStatus::Success: VLOG(1) << logPrefix() << " success, finished task"; succeeded_ = true; break; case TrackerStatus::Timeout: case TrackerStatus::Failure: VLOG(1) << logPrefix() << " building tracker " << (tracker_->status() == TrackerStatus::Timeout ? "timed out" : "failed") << ", scheduling retry"; lastUpdate_ = 0; tracker_ = nullptr; break; case TrackerStatus::Cancelled: LOG(ERROR) << logPrefix() << " canceled tracker without canceled task "; failed_ = true; break; default: break; } } if (tracker_) { trackerStatus_ = tracker_->status(); } if (succeeded_ || failed_) { return; } if (!constructionStarted_) { bcdata_->res.ore -= type_->mineralCost; bcdata_->res.gas -= type_->gasCost; } // Update required? if (lastUpdate_ > 0 && frame - lastUpdate_ < 4) { return; } lastUpdate_ = frame; bool canBuild = true; if (!constructionStarted_) { if (type_->mineralCost && bcdata_->res.ore < 0) { canBuild = false; } if (type_->gasCost && bcdata_->res.gas < 0) { canBuild = false; } if (type_->supplyRequired && bcdata_->res.used_psi + type_->supplyRequired > bcdata_->res.total_psi) { canBuild = false; } if (canBuild) { if (!utils::prerequisitesReady(state, type_)) { canBuild = false; } } } if (!canBuild) { return; } if (builder_ == nullptr && tracker_ == nullptr) { findBuilder(state); if (builder_) { VLOG(1) << logPrefix() << " found builder: " << utils::unitString(builder_); grabUnit(state, builder_); } else { VLOG(1) << logPrefix() << " could not determine builder right now"; } } if (builder_ && tracker_ == nullptr) { addUpc(builder_, builder_->pos(), Command::Create, type_); if (type_->isUpgrade()) { tracker_ = state->addTracker<UpgradeTracker>(builder_, type_, 15); } else if (type_->isTech()) { tracker_ = state->addTracker<ResearchTracker>(builder_, type_, 15); } else { tracker_ = state->addTracker<BuildTracker>(builder_, type_, 15); } trackerStatus_ = tracker_->status(); } postUpcs(state); } void BuilderController::removeUnit(State* state, Unit* unit, UpcId id) { if (unit == builder_) { builder_ = nullptr; } BuilderControllerBase::removeUnit(state, unit, id); } std::string BuilderController::logPrefix() const { std::ostringstream oss; oss << "BuilderController for task " << utils::upcString(upcId_) << " (" << utils::buildTypeString(type_) << "):"; return oss.str(); } } // namespace cherrypi
f43796662f34b064b0ebef6f53d6e1860e2abd96
19d41c4ae325277636383885388c83dd1555f8cf
/TIOJ/1224.cpp
55d0b3767407ad0a870beb77a6b12902d69465c6
[]
no_license
henrytsui000/online-judge
5fd0f7b5c747fb5bfd5f84fb616b9f7346e8abaf
337aa1d52d587fb653ceeb8b3ee64668804f5b13
refs/heads/master
2022-05-28T13:56:04.705485
2022-05-19T13:33:43
2022-05-19T13:33:43
226,999,858
3
0
null
2022-02-02T03:22:06
2019-12-10T01:10:15
C++
UTF-8
C++
false
false
2,780
cpp
1224.cpp
#include <bits/stdc++.h> #pragma GCC optimize("unroll-loops,no-stack-protector") using namespace std; using ll = long long; using ld = long double; using pii = pair<int,int>; using pll = pair<ll,ll>; using pdd = pair<ld,ld>; #define IOS ios_base::sync_with_stdio(0); cin.tie(0) #define endl '\n' #define all(a) a.begin(),a.end() #define sz(a) ((int)a.size()) #define F first #define S second #define rep(i,n) for(int i=0,_a,_b;i<(int)n;i++) #define rep1(i,n) for(int i=1;i<=(int)n;i++) #define pb push_back #define eb emplace_back #define mp(a,b) make_pair(a,b) #define cans cout<<ans<<endl #define in cout<<"in lar"<<endl #define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end())))) #define GET_POS(c,x) (lower_bound(c.begin(),c.end(),x)-c.begin()) template<typename T1,typename T2> ostream& operator<<(ostream& out,pair<T1,T2> P){ out<<'('<<P.F<<','<<P.S<<')'; return out; } //}}} const ll INF64=8000000000000000000LL; const int INF=0x3f3f3f3f; const ll MOD=ll(1e9+7); const ld PI=acos(-1); const ld eps=1e-9; //const ll p=880301; //const ll P=31; ll mypow(ll a,ll b){ ll res=1LL; while(b){ if(b&1) res=res*a%MOD; a=a*a%MOD; b>>=1; } return res; } const int maxn = 1e5+5; struct st{ int a[4]; }; st arr[maxn]; int ans=0; struct node{ node *lc,*rc; int l,r; int val; int lz_tag; void push(){ lc->val+=val,rc->val+=val; val=0; } }; node *build(int l,int r){ if(l==r-1){ return new node{0,0,l,r,0}; }else{ int mid=(l+r)>>1; node *ret=new node{build(l,mid),build(mid,r),l,r,0}; } } void add(int l,int r,node *nd){ if(l==nd->l&&r==nd->r){ nd->val++; }else{ int mid = (nd->l+nd->r)>>1; if(l>=mid){ add(l,r,nd->rc); }else if(r<=mid){ add(l,r,nd->lc); }else { add(l,mid,nd->lc); add(mid,r,nd->rc); } } } void qry(int l,int r,node* nd){ if(nd->l==l&&nd->r==r){ if(nd->val) ans +=(l-r); }else{ nd->push(); int mid=(l+r)>>1; if(l>=mid){ qry(l,r,nd->rc); }else if(r<=mid){ qry(l,r,nd->lc); }else{ qry(l,mid,nd->lc); qry(mid,r,nd->rc); } } } bool tmp(st x,st y){ if(x.a[3]>y.a[3]) return true; else if(x.a[3]==y.a[3]) return x.a[2]>y.a[2]; else return false; } int32_t main(){ int n; cin>>n; rep(i,n) rep(j,4) cin>>arr[i].a[j]; sort(arr,arr+n,tmp); rep(i,n){ rep(j,4) cout<<arr[i].a[j]<<' '; cout<<endl; } rep(i,n){ if() } return 0; }
bae495d96d53c7eec5b41fbcfe672c60ede2ccc3
56237e6b716a82ef3728d48ec28899a203e28216
/week6/ex1.cpp
eb40d058f04aed8176009afcb3d431a1697b5e23
[]
no_license
ramanqul/pp1-2019
a07cb481aad9c61f274e4b6b78758e945e6a8746
a05e4a843de593330f4549ea200da3a72340e072
refs/heads/master
2020-04-21T11:21:34.141580
2019-05-04T11:13:21
2019-05-04T11:13:21
169,522,171
0
0
null
null
null
null
UTF-8
C++
false
false
217
cpp
ex1.cpp
#include <iostream> using namespace std; string hello(string name) { return "Hello, " + name; //must } int main() { string name; cin >> name; string res = hello(name); cout << res << endl; return 0; }
4a74e900b8bdc5b4c3783c3c716a9cf8dd11a3d1
9c0f172c0098449bd7a571c36c7b9e91286b7dec
/helloword/helloword/main.cpp
77b6e76858f8385852258a6fe06ea2a76d131afb
[]
no_license
kenesbao/cplusplus
0a40d5dbdfe0fa4372af5c6900820af63df29fc3
fb8461cc1df0eb3225fe3b237900c75364cf2f66
refs/heads/master
2021-01-25T08:38:06.502621
2015-03-30T06:08:44
2015-03-30T06:08:44
33,101,955
0
0
null
null
null
null
UTF-8
C++
false
false
274
cpp
main.cpp
// // main.cpp // helloword // // Created by 包立明 on H27/03/30. // Copyright (c) 平成27年 bao. All rights reserved. // #include <iostream> int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; }
dfa26acf150beaef8af99c35e600a08f4112b681
1175638e96c27290074f0e0c0bcf131103d64883
/main.cpp
e3697da20f6fc179362ef5d98128130beae1bfd9
[]
no_license
Ryochan7/weiss-deck-builder-qtquick
25dfae485dd5b97683bb7e0a4f8a2f812a2dfe1e
138defe30903cf4001ac7a3c7ff49527bf183589
refs/heads/master
2021-05-04T06:20:13.002082
2016-10-18T21:24:44
2016-10-18T21:24:44
71,068,104
1
0
null
null
null
null
UTF-8
C++
false
false
816
cpp
main.cpp
#include <QApplication> #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "weisscard.h" #include "weisscardmodel.h" #include "weisscardfullmodel.h" #include "util.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); WeissCardModel deckModel; WeissCardFullModel collectionModel; Util utilObj; QQmlApplicationEngine engine; WeissCard::registerQmlType(); engine.rootContext()->setContextProperty("deckModel", &deckModel); engine.rootContext()->setContextProperty("collectionModel", &collectionModel); engine.rootContext()->setContextProperty("realDeck", deckModel.getDeck()); engine.rootContext()->setContextProperty("util", &utilObj); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
13702e4f11dd7821bce4a203f743d5176feb62ca
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1595491_1/C++/Bogdan/ProblemB.cpp
d15ef05418eaee15e51b3fc0b4e7efe814c2770e
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
969
cpp
ProblemB.cpp
#include <iostream> #include <cstring> using namespace std; void mainB() { unsigned int T,N,S,p; int minNormal, minSurprise; unsigned int countNormal, countSurprise; unsigned int score; cin >> T; for (unsigned int i=0;i<T;++i) { cin >> N >> S >> p; if (p == 0) { minNormal = 0; minSurprise = 0; } else if (p == 1) { minNormal = 1; minSurprise = 1; } else { minNormal = 3*p-2; minSurprise = 3*p-4; } countNormal = 0; countSurprise = 0; for (unsigned int j=0;j<N;++j) { cin >> score; if ((int)score >= minNormal) ++countNormal; else if ((int)score >= minSurprise) ++countSurprise; } if (countSurprise > S) countSurprise = S; cout << "Case #" << (i+1) << ": " << countNormal+countSurprise << endl; } }
7549d3ccd8eed484dd1e6b8ca64e7d3776c3d47e
1dd67be315c6c8241a9815a12d335e6bb6a7c8a8
/software/PeaPod-Arduino/FloatSensor.h
e2d4f0b76ea9c11396b54e3019083b44798b425c
[ "MIT" ]
permissive
nataliiaaaa/PeaPod
7ec0c252d1456b2cfe96597484da0d590aa1f459
7b3a3fe21ecdc11c024d94ce51e3612b7c8ccaae
refs/heads/master
2023-08-17T11:25:24.075713
2021-03-13T19:20:28
2021-03-13T19:20:28
416,932,564
0
0
null
null
null
null
UTF-8
C++
false
false
331
h
FloatSensor.h
#ifndef FloatSensor_H #define FloatSensor_H #include "Arduino.h" #include "Sensor.h" class FloatSensor : public Sensor { public: FloatSensor(uint8_t pin); private: float read() override; bool init() override; /** * Digital input pin. * */ uint8_t pin; }; #endif
07667c182543c9f315485e1da7d0f46fea2ae793
10a57a1756eef8e7ae5db5ef0dfe4857d8176181
/MeasureSensityResponse/AcousticTest/AcousticTest/TurnTable.cpp
8bbec0571d0ca50f37e172690747f33638f10498
[]
no_license
Janie91/GitAcoustic
a44cf3ac30e943450cb6f1a63ccc5a2f67164372
ae1d19d07b0dd83dda3aa9e514365de059646d75
refs/heads/master
2021-09-09T11:08:59.107432
2018-03-15T10:19:56
2018-03-15T10:19:56
114,206,016
0
0
null
null
null
null
GB18030
C++
false
false
19,807
cpp
TurnTable.cpp
// TurnTable.cpp : 实现文件 // #include "stdafx.h" #include "AcousticTest.h" #include "TurnTable.h" #include "afxdialogex.h" #include "MyFunction.h" // CTurnTable 对话框 IMPLEMENT_DYNAMIC(CTurnTable, CDialog) CTurnTable::CTurnTable(CWnd* pParent /*=NULL*/) : CDialog(CTurnTable::IDD, pParent) { m_CurrentAngle = _T(""); m_Speed = Speed; m_TargetAngle=0; m_StartAngle=StartAngle; m_EndAngle=EndAngle; } CTurnTable::~CTurnTable() { } void CTurnTable::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_MSCOMM, m_mscom); DDX_Text(pDX, IDC_CurrentAngle, m_CurrentAngle); DDX_Text(pDX, IDC_Speed, m_Speed); DDX_Text(pDX, IDC_TargetAngle, m_TargetAngle); DDX_Text(pDX, IDC_StartAngle, m_StartAngle); DDX_Text(pDX, IDC_EndAngle, m_EndAngle); } BEGIN_MESSAGE_MAP(CTurnTable, CDialog) ON_BN_CLICKED(IDC_quit, &CTurnTable::OnBnClickedquit) ON_BN_CLICKED(IDC_RotateRight, &CTurnTable::OnBnClickedRotateright) ON_BN_CLICKED(IDC_RotateLeft, &CTurnTable::OnBnClickedRotateleft) ON_BN_CLICKED(IDC_SetZero, &CTurnTable::OnBnClickedSetzero) ON_BN_CLICKED(IDC_ReturnZero, &CTurnTable::OnBnClickedReturnzero) ON_BN_CLICKED(IDC_RotateSetAngle, &CTurnTable::OnBnClickedRotatesetangle) ON_BN_CLICKED(IDC_StopRotate, &CTurnTable::OnBnClickedStoprotate) ON_WM_TIMER() ON_WM_PAINT() END_MESSAGE_MAP() BOOL CTurnTable::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here SetWindowPos(NULL,50,80,0,0,SWP_NOZORDER | SWP_NOSIZE); if(m_mscom.get_PortOpen()) m_mscom.put_PortOpen(false); //直接在串口控件的属性中设置了以下这些参数 //m_mscom.put_CommPort(2); //选择串口 //m_mscom.put_InBufferSize(1024); //m_mscom.put_OutBufferSize(512); //m_mscom.put_InputLen(0); //设置当前接收区数据长度为0,表示全部读取 // m_mscom.put_InputMode(0); //设置输入方式为文本方式 // m_mscom.put_RTSEnable(1); //设置RT允许 //m_mscom.put_Settings("9600,e,7,2"); //comb2选择的波特率,偶校验,7数据位,2个停止位 if(!m_mscom.get_PortOpen()) { m_mscom.put_PortOpen(true); //打开串口 } else { m_mscom.put_OutBufferCount(0); MessageBox("串口2打开失败"); } SetManual(); SetTimer(1,200,NULL); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } // CTurnTable 消息处理程序 void CTurnTable::SetManual() { // TODO: 在此添加控件通知处理程序代码 BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19); databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,82); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,49); databuf.SetAt(14,48); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal;//因为串口返回的是字符串类型的,retVal的vt是VT_BSTR if(str.Mid(5,2)!="00") { AfxMessageBox("设置手动模式操作出错!"); } } void CTurnTable::SetSpeed(int speed) { BYTE commanddata; CByteArray databuf; char crc[3]; char strspeed[9]; databuf.SetSize(21);//设速度为speed databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,87); databuf.SetAt(4,68); databuf.SetAt(5,48); databuf.SetAt(6,50); databuf.SetAt(7,49); databuf.SetAt(8,48); sprintf_s(strspeed,"%08X",speed);//左边补零,共有八位 databuf.SetAt(9,strspeed[4]);//回转命令数据是先低后高 databuf.SetAt(10,strspeed[5]); databuf.SetAt(11,strspeed[6]); databuf.SetAt(12,strspeed[7]); databuf.SetAt(13,strspeed[0]); databuf.SetAt(14,strspeed[1]); databuf.SetAt(15,strspeed[2]); databuf.SetAt(16,strspeed[3]); commanddata=databuf[0]; for(int i=1;i<=16;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(17,crc[0]); databuf.SetAt(18,crc[1]); databuf.SetAt(19,42); databuf.SetAt(20,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("设置速度操作出错!"); } } float CTurnTable::ReadCurrentAngle() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(17); databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,82); databuf.SetAt(4,68); databuf.SetAt(5,48); databuf.SetAt(6,50); databuf.SetAt(7,55); databuf.SetAt(8,54); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,48); databuf.SetAt(12,50); commanddata=databuf[0]; for(int i=1;i<=12;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(13,crc[0]); databuf.SetAt(14,crc[1]); databuf.SetAt(15,42); databuf.SetAt(16,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); //angle为接收回来的第8位开始的4位 VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal;//因为串口返回的是字符串类型的,retVal的vt是VT_BSTR //if(str.Mid(5,2)!="00") //{ // AfxMessageBox("读取角度操作出错!"); //} int temp; CString anglestring; anglestring.Append(str.Mid(7,1)); anglestring.Append(str.Mid(7,1)); anglestring.Append(str.Mid(7,1)); anglestring.Append(str.Mid(7,1)); anglestring+=str.Mid(7,4); sscanf_s(anglestring,"%X",&temp); //是字符串,要化为数值,然后除以10才是角度 float angle=temp/10.0f; m_CurrentAngle.Format("%.1f°",angle); SetDlgItemText(IDC_CurrentAngle,m_CurrentAngle); Sleep(200); return angle; } void CTurnTable::RotateRight() { SetSpeed(m_Speed); BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//顺时针转 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,83); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,55); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("顺时针转动操作出错!"); } } void CTurnTable::StopRotateRight() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//顺时针停 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,82); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,55); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("顺时针停操作出错!"); } } void CTurnTable::RotateLeft() { SetSpeed(m_Speed); BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//逆时针转 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,83); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,56); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("逆时针转动操作出错!"); } } void CTurnTable::StopRotateLeft() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//逆时针停 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,82); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,56); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("逆时针停操作出错!"); } } void CTurnTable::StopRotate() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//停止转动 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,82); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,57); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("停止转动操作出错!"); } } void CTurnTable::CancelCurrentZero() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//取消当前零点 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,82); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,51); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("取消当前零点操作出错!"); } } void CTurnTable::SetCurrentPosZero() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//设当前位置为零点 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,83); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,51); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("设置当前位置为零点操作出错!"); } } void CTurnTable::StopRotateBacktoZero() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//停止回零点 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,82); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,54); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("停止回零点操作出错!"); } } void CTurnTable::RotateBacktoZero() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//回到参考零点 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,83); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,54); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("回到参考零点操作出错!"); } } void CTurnTable::SetAuto() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//设为自动 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,83); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,49); databuf.SetAt(14,48); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("设为自动操作出错!"); } } void CTurnTable::SetTargetAngle(int targetangle) { BYTE commanddata; CByteArray databuf; char crc[3]; char strangle[9]; databuf.SetSize(21);//设置目标角度 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,87); databuf.SetAt(4,68); databuf.SetAt(5,48); databuf.SetAt(6,50); databuf.SetAt(7,55); databuf.SetAt(8,52); sprintf_s(strangle,"%08X",targetangle*10);//转换角度时有个10倍关系 databuf.SetAt(9,strangle[4]); databuf.SetAt(10,strangle[5]); databuf.SetAt(11,strangle[6]); databuf.SetAt(12,strangle[7]); databuf.SetAt(13,strangle[0]); databuf.SetAt(14,strangle[1]); databuf.SetAt(15,strangle[2]); databuf.SetAt(16,strangle[3]); commanddata=databuf[0]; for(int i=1;i<=16;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(17,crc[0]); databuf.SetAt(18,crc[1]); databuf.SetAt(19,42); databuf.SetAt(20,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("设置目标角度操作出错!"); } } void CTurnTable::PositionStart() { BYTE commanddata; CByteArray databuf; char crc[3]; databuf.SetSize(19);//定位启动 databuf.SetAt(0,64); databuf.SetAt(1,48); databuf.SetAt(2,49); databuf.SetAt(3,75); databuf.SetAt(4,83); databuf.SetAt(5,67); databuf.SetAt(6,73); databuf.SetAt(7,79); databuf.SetAt(8,32); databuf.SetAt(9,48); databuf.SetAt(10,48); databuf.SetAt(11,53); databuf.SetAt(12,48); databuf.SetAt(13,48); databuf.SetAt(14,57); commanddata=databuf[0]; for(int i=1;i<=14;i++) { commanddata^=databuf[i]; } sprintf_s(crc,"%02X",commanddata); databuf.SetAt(15,crc[0]); databuf.SetAt(16,crc[1]); databuf.SetAt(17,42); databuf.SetAt(18,13); m_mscom.put_Output(COleVariant(databuf)); Sleep(200); VARIANT retVal=m_mscom.get_Input(); CString str; str=retVal.bstrVal; if(str.Mid(5,2)!="00") { AfxMessageBox("定位启动操作出错!"); } } void CTurnTable::ReturnZero() { StopRotateBacktoZero(); RotateBacktoZero(); } void CTurnTable::SetZero() { CancelCurrentZero(); SetCurrentPosZero(); } void CTurnTable::RotateTargetAngle(int targetangle) { SetAuto(); Sleep(200); StopRotate(); Sleep(100); m_Speed=GetDlgItemInt(IDC_Speed); SetSpeed(m_Speed); SetTargetAngle(targetangle); PositionStart(); } void CTurnTable::OnBnClickedRotateright() { // TODO: Add your control notification handler code here CString str; SetManual(); m_Speed=GetDlgItemInt(IDC_Speed); GetDlgItemTextA(IDC_RotateRight,str); if(str=="顺时针转") { RotateRight(); GetDlgItem(IDC_RotateRight)->SetWindowTextA("顺时针停"); } else if(str=="顺时针停") { StopRotateRight(); GetDlgItem(IDC_RotateRight)->SetWindowTextA("顺时针转"); } } void CTurnTable::OnBnClickedRotateleft() { // TODO: Add your control notification handler code here CString str; SetManual(); m_Speed=GetDlgItemInt(IDC_Speed); GetDlgItemTextA(IDC_RotateLeft,str); if(str=="逆时针转") { RotateLeft(); GetDlgItem(IDC_RotateLeft)->SetWindowTextA("逆时针停"); } else if(str=="逆时针停") { StopRotateLeft(); GetDlgItem(IDC_RotateLeft)->SetWindowTextA("逆时针转"); } } void CTurnTable::OnBnClickedSetzero() { // TODO: Add your control notification handler code here SetZero(); } void CTurnTable::OnBnClickedReturnzero() { // TODO: Add your control notification handler code here ReturnZero(); } void CTurnTable::OnBnClickedRotatesetangle() { // TODO: Add your control notification handler code here m_TargetAngle=GetDlgItemInt(IDC_TargetAngle); RotateTargetAngle(m_TargetAngle); } void CTurnTable::OnBnClickedStoprotate() { // TODO: Add your control notification handler code here StopRotate(); } void CTurnTable::OnTimer(UINT_PTR nIDEvent) { // TODO: Add your message handler code here and/or call default ReadCurrentAngle(); CDialog::OnTimer(nIDEvent); } void CTurnTable::OnBnClickedquit() { // TODO: Add your control notification handler code here Speed=GetDlgItemInt(IDC_Speed); StartAngle=GetDlgItemInt(IDC_StartAngle); EndAngle=GetDlgItemInt(IDC_EndAngle); } void CTurnTable::OnPaint()//在turntable的重绘函数中添加了显示角度的函数,不知道测量的时候能不能一直看到变化 { CPaintDC dc(this); // device context for painting // TODO: Add your message handler code here // Do not call CDialog::OnPaint() for painting messages SetDlgItemText(IDC_CurrentAngle,m_CurrentAngle); } void CTurnTable::OnCancel() { // TODO: Add your specialized code here and/or call the base class KillTimer(1); if(m_mscom.get_PortOpen()) m_mscom.put_PortOpen(false); DestroyWindow(); } void CTurnTable::PostNcDestroy() { // TODO: Add your specialized code here and/or call the base class CDialog::PostNcDestroy(); //delete this; }
a66332a29a34179f7a89c1150186c24bd01c45fe
9bf952de762c04c84ba1fc7f1499aa711d338364
/hw8/hw8.cpp
f933e22a39cd996d1d3ea8e76fee026332d17fd0
[]
no_license
Computational-Physics-Research/Computational-Physics-3
50447fc0c7c2d38915906fec538d7fa90a57714f
a2aba8b60d21ab3934986c1201aa4e688c07014f
refs/heads/master
2021-12-11T06:45:39.236755
2016-10-31T04:12:24
2016-10-31T04:12:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,812
cpp
hw8.cpp
/* AEP 4380 HW #8 Dan Girshovich 4/12/13 Least Squares Curve Fitting Compile with: g++ -std=c++0x -O2 -o gen_data hw8.cpp Tested on Mac OSX 10.8.2 with a Intel Core 2 Duo */ #include <cstdio> #include <cstdlib> #include <cmath> #include <algorithm> #include <functional> #include "nr3.h" using namespace std; typedef function<double(double)> math_func; const int N = 607; // max number of data points const double sigma_perc = 0.2; vector<int> ts = vector<int>(N); vector<double> ys = vector<double>(N); vector<double> sigmas = vector<double>(N); // slightly modified given code to read from the data file void load_arrays() { const int NCMAX = 200; // max number of characters per line char cline[N]; double co2; FILE *fp; fp = fopen("maunaloa.co2", "r"); if (NULL == fp) { printf("Can't open file."); exit(0); } for (int i = 0; i < 15; i++) fgets(cline, NCMAX, fp); // read a whole line int t = 0, npts = 0; int year; do { fscanf(fp, "%d", &year); for (int j = 0; j < 12; j++) { fscanf(fp, "%lf", &co2); if (co2 > 0.0) { ts[npts] = t; ys[npts++] = co2; } t++; } if (npts >= N) break; fscanf(fp, "%lf", &co2); // skipping average value } while (year < 2008); } // returns an array of fit functions vector<math_func> get_fit_funcs(bool first_harmonic) { const double pi = 4.0 * atan(1.0); double k = 2 * pi / 12; vector<math_func> fs { [ = ](double t){return 1;}, [ = ](double t){return t;}, [ = ](double t){return t * t;}, [ = ](double t){return sin(k * t);}, [ = ](double t){return cos(k * t);}, }; vector<math_func> half_year_terms { [ = ](double t) {return sin((k * t) / 2);}, [ = ](double t) {return cos((k * t) / 2);}, }; if (first_harmonic) { fs.insert(fs.end(), half_year_terms.begin(), half_year_terms.end()); } return fs; } // returns the F matrix given fit functions MatDoub_IO get_F(vector<math_func> fs) { int m = fs.size(); MatDoub_IO F(m, m); for (int l = 0; l < m; l++) { for (int k = 0; k < m; k++) { double sum = 0.0; for (int i = 0; i < N; i++) { double y = ys[i]; sum += fs[l](ts[i]) * fs[k](ts[i]) / (sigmas[i] * sigmas[i]); } F[l][k] = sum; } } return F; } // returns the b vector given fit functions MatDoub_IO get_b(vector<math_func> fs) { int m = fs.size(); MatDoub_IO b(m, 1); for (int l = 0; l < m; l++) { double sum = 0.0; for (int i = 0; i < N; i++) { double y = ys[i]; sum += y * fs[l](ts[i]) / (sigmas[i] * sigmas[i]); } b[l][0] = sum; } return b; } // From Numerical Recipes Ch 2 void gaussj(MatDoub_IO &a, MatDoub_IO &b) { Int i, icol, irow, j, k, l, ll, n = a.nrows(), m = b.ncols(); Doub big, dum, pivinv; VecInt indxc(n), indxr(n), ipiv(n); for (j = 0; j < n; j++) ipiv[j] = 0; for (i = 0; i < n; i++) { big = 0.0; for (j = 0; j < n; j++) if (ipiv[j] != 1) for (k = 0; k < n; k++) { if (ipiv[k] == 0) { if (abs(a[j][k]) >= big) { big = abs(a[j][k]); irow = j; icol = k; } } } ++(ipiv[icol]); if (irow != icol) { for (l = 0; l < n; l++) SWAP(a[irow][l], a[icol][l]); for (l = 0; l < m; l++) SWAP(b[irow][l], b[icol][l]); } indxr[i] = irow; indxc[i] = icol; if (a[icol][icol] == 0.0) throw("gaussj: Singular Matrix"); pivinv = 1.0 / a[icol][icol]; a[icol][icol] = 1.0; for (l = 0; l < n; l++) a[icol][l] *= pivinv; for (l = 0; l < m; l++) b[icol][l] *= pivinv; for (ll = 0; ll < n; ll++) if (ll != icol) { dum = a[ll][icol]; a[ll][icol] = 0.0; for (l = 0; l < n; l++) a[ll][l] -= a[icol][l] * dum; for (l = 0; l < m; l++) b[ll][l] -= b[icol][l] * dum; } } for (l = n - 1; l >= 0; l--) { if (indxr[l] != indxc[l]) for (k = 0; k < n; k++) SWAP(a[k][indxr[l]], a[k][indxc[l]]); } } // From Numerical Recipes Ch 2 void gaussj(MatDoub_IO &a) { MatDoub b(a.nrows(), 0); gaussj(a, b); } void write1(string name, int suffix, function<double(int)> g, int max) { stringstream fname; fname << name << suffix << ".dat"; ofstream of; of.open(fname.str().c_str()); for (int i = 0; i < max; i++) { of << g(i) << endl; } of.close(); } void write2(string name, int suffix, function<double(int)> g, int max) { stringstream fname; fname << name << suffix << ".dat"; ofstream of; of.open(fname.str().c_str()); for (int i = 0; i < max; i++) { of << ts[i] << " " << g(i) << endl; } of.close(); } void write_all_fit_data(vector<math_func> fs, bool seasonal_var) { MatDoub_IO F = get_F(fs); MatDoub_IO b = get_b(fs); gaussj(F, b); // now b contains the solution vector (a), and F is (old F)^-1 MatDoub &F_inv = F; MatDoub &a = b; int m = seasonal_var ? fs.size() : 3; math_func f = [ = , &a](double t) { double sum = 0.0; for (int k = 0; k < m; k++) { sum += a[k][0] * fs[k](t); } return sum; }; auto get_params = [&a](int i) { return a[i][0]; }; write1("params", m, get_params, m); auto get_fit = [f](int i) { return f(ts[i]); }; write2("fit", m, get_fit, N); auto get_error = [F_inv](int i) { return F_inv[i][i]; }; write1("error", m, get_error, m); auto get_chi_sq = [f, m](int j) { double sum = 0.0; for (int i = 0; i < N; i++) { double tmp = (ys[i] - f(ts[i])) / sigmas[i]; sum += tmp * tmp; } return sum / (N - m); }; write1("chi_sq", m, get_chi_sq, 1); } int main() { load_arrays(); transform(ys.begin(), ys.end(), sigmas.begin(), [](double y) { return y * sigma_perc; }); auto get_orig_data = [](int i) { return ys[i]; }; write2("orig", 0, get_orig_data, N); // with first harmonic vector<math_func> fs = get_fit_funcs(true); write_all_fit_data(fs, true); // no first harmonic vector<math_func> fs2 = get_fit_funcs(false); write_all_fit_data(fs2, true); // with seasonal variations removed after fit calculation write_all_fit_data(fs, false); }
5421a1c1284c29eb179d343d97eb97c525e99584
fe3727a2a91858de4f813dedb027ac63601acc52
/tester/gcd/gen.cpp
d06593a257397198448e49db026fb36989d14a32
[]
no_license
fabik/cpspc2017
3f0edf5da364941606ea726f8d7aa2cec7f8ca80
39e780bd37a9ec35f88ee02a69209d246a774104
refs/heads/master
2021-03-27T16:29:45.850866
2017-06-30T17:15:55
2017-06-30T17:15:55
90,709,123
1
0
null
null
null
null
UTF-8
C++
false
false
3,711
cpp
gen.cpp
/* ingen for NWD Autor: Piotr Smulewicz */ #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <cassert> #include <algorithm> #include "oi.h" using namespace std; const int MAXC = 10 * 1000 * 1000; const long long MAXZAK =1000LL*1000LL*1000LL*1000LL; typedef long long LL; const int N[] = { 7 , 15, 100, 2000, 2000, 500*1000, 500*1000}; const long long Z[] = { 30, 30, 500, 2000, MAXZAK, MAXZAK , MAXZAK }; int number = 1; char letter = 'a'; int uni; oi::Random generator(1); vector<int> l, r; void nastepna_grupa() { number++; letter = 'a'; } vector<long long> data; void save(int n, int e) { if (uni) { sort(data.begin(),data.end()); std::vector<long long>::iterator it; it = std::unique(data.begin(), data.end()); data.resize(std::distance(data.begin(), it)); } stringstream name; name << "test/0" << number << "." << letter << ".in"; letter++; cout << "Generate file " << name.str() << endl; ofstream file(name.str().c_str()); file << data.size() << endl; for (int i = 0; i < n; i++) { file << data[i] << ((i + 1 != int(data.size())) ? " " : "\n"); } } // random number from interval [l, r] long long from_interval(long long l, long long r) { //if( l>r ) // swap(l,r); assert(l <= r); long long d = r - l + 1; return l + generator.randULL() % d; } void random_test(int n, int e, long long min, long long max) { data.clear(); for (int i = 0; i < n; i++) { data.push_back(from_interval(min, max)); } save(n, e); } void random_a(long long n, long long k) { data.clear(); for (int i = 0; i < n; i++) { if (i < n / 2) data.push_back(k * (i + 1)); else if (i != n - 1) data.push_back((n / 2) * k + 1); else data.push_back((n / 2) * k * 2); } save(n, 1); } void random_uniq(int n, long long min, long long max) { data.clear(); for (int i = 0; i < n; i++) { data.push_back(from_interval(min, max)); } save(n, 1); } void long_work(int n){ data.clear(); long long sum=0; for(int i=0;i<n;i++){ if(i<19){ sum+=(1<<(20-i)); data.emplace_back(sum); }else{ if(i==19) sum+=2; sum++; data.emplace_back(sum); } } save(n, 1); } int main() { for (int subtask = 0; subtask < 7; subtask++) { if ((subtask == 3) || (subtask == 5)){ uni = 1; } else { uni = 0; } for(int i=0;i<3;i++){ random_test(N[subtask], N[subtask] / 2, 1, Z[subtask]); random_test(N[subtask], 2, 1, Z[subtask]); random_test(N[subtask], N[subtask] - 3, 1, Z[subtask]); random_test(N[subtask], N[subtask] / 2, Z[subtask] - 20, Z[subtask]); random_a(N[subtask], Z[subtask] / N[subtask]); } if ((subtask >= 2) && (subtask <= 4)){ int _subtask = 1; random_test(N[_subtask], N[_subtask] / 2, 1, Z[_subtask]); random_test(N[_subtask], 2, 1, Z[_subtask]); random_test(N[_subtask], N[_subtask] - 3, 1, Z[_subtask]); random_test(N[_subtask], N[_subtask] / 2, Z[_subtask] - 20, Z[_subtask]); random_a(N[_subtask], Z[_subtask] / N[_subtask]); } if(subtask>=3) long_work(N[subtask]); nastepna_grupa(); } return 0; }
306f24bf30b669c164565e7a0d6a1b5482542445
d7bbe2e1161bda20183df745332e73d344822d1c
/admin.cpp
03728293e0a97e455698be75c890903d73f2e8fa
[]
no_license
prabhavagrawal7/School-Management-System
a9168fc01ececa9a2bbb3f7f977a1c726e66dadb
8a8b73651b0c21056df3b8458ac1eacb0c71c454
refs/heads/master
2023-06-14T17:40:21.264877
2021-07-11T05:41:40
2021-07-11T05:41:40
381,802,260
1
3
null
2021-06-30T19:13:34
2021-06-30T18:46:23
C++
UTF-8
C++
false
false
76,294
cpp
admin.cpp
#include<bits/stdc++.h> using namespace std; #include "admin.h" //#include"common.h" //#include "exam_marks.h" // struct exam_marks{ // int maths_marks; // int english_marks; // int hindi_marks; // int science_marks; // int social_marks; // int computer_marks; // }; void admin:: lib_add_book(){ string book_name; cout<<"Enter the name of the book "<<endl; cin>>book_name; int choice; cout<<"1 for student book"<<endl; cout<<"2 for teacher book"<<endl; cin>>choice; obj_library.add_book(book_name,choice); } void admin:: get_id_book() { string book_name; cout<<"Enter the name of the book "<<endl; cin>>book_name; int choice; cout<<"1 for student book"<<endl; cout<<"2 for teacher book"<<endl; cin>>choice; if (choice==1) { int ans=obj_library.get_id_student(book_name); } else if (choice==2) { int ans=obj_library.get_id_teacher(book_name); } } // void admin:: default_call() { // } // void admin:: set_school_balance(){ // obj_bank.set_school_balance(1000000); // } int admin:: get_school_balance(){ int balance=obj_bank.get_school_balance(); return balance; } int admin:: student_id=1000; int admin:: staff_id=2000; // int admin:: batch_id=3000; // later void admin:: admin_functions(){ // cout<<"Please first set school account details"; // // take it bydefault // set_school_balance(); // first set the school amount cout<<"Welcome Admin here!! How can I help you "<<endl; cout<<"MENU"<<endl; cout<<"-----------------------"<<endl; int choice; cout <<"Press 1 to add student "<<endl; cout <<"Press 2 to add teacher "<<endl; cout <<"Press 3 to add staff "<<endl; cout <<"Press 4 to remove student "<<endl; cout <<"Press 5 to remove teacher "<<endl; cout <<"Press 6 to remove staff "<<endl; cout <<"Press 7 to add class monitor (student) "<<endl; cout <<"Press 8 to add class teacher (teacher) "<<endl; cout <<"Press 9 to add leader (student) "<<endl; cout <<"Press 10 to remove class monitor (student) "<<endl; cout <<"Press 11 to remove class teacher (teacher) "<<endl; cout <<"Press 12 to remove leader (student) "<<endl; // new with bank cout<<"Press 13 to pay the staff"<<endl; // new to check school balance cout<<"Press 14 to get the school balance"<<endl; // cout<<"Press 15 to exit"<<endl; // lib cout<<"Press 15 to add book"<<endl; cout<<"Press 16 to check id of book"<<endl; cout<<"Press 17 to display student list "<<endl; cout<<"Press 18 to display class monitor list "<<endl; cout<<"Press 19 to display leader list"<<endl; cout<<"Press 20 to display staff list "<<endl; cout<<"Press 21 to display teacher list "<<endl; cout<<"Press 22 to display class teacher list "<<endl; cout<<"Press 23 to display library contents "<<endl; cout<<"Press 24 to exit"<<endl; cout<<"Enter your choice "<<endl; cin>>choice; if (choice==1) { add_student(); } else if (choice==2){ add_teacher(); } else if (choice==3){ add_staff(); } else if (choice==4){ remove_student(); } else if (choice==5){ remove_teacher(); } else if (choice==6){ remove_staff(); } else if (choice==7){ add_class_monitor(); } else if (choice==8){ add_class_teacher(); } else if (choice==9){ add_leader(); } else if (choice==10){ remove_class_monitor(); } else if (choice==11){ remove_class_teacher(); } else if (choice==12){ remove_leader(); } else if (choice==13) { pay_staff(); } else if (choice==14) { int x=obj_bank.get_school_balance(); cout<<x<<endl; } else if (choice==15 ) { lib_add_book(); } // else if (choice==15){ // return; // } else if (choice==16) { get_id_book(); } else if (choice==17) { int size=student_list.size(); // if (size==0) { // cout<<"List is empty!"<<endl; // } cout<<"List size :- "<<size<<endl; for(int i=0;i<size;i++){ cout<<"Student number "<<i+1<<endl; student_list[i].display(); } } else if (choice==18) { int size=class_monitor_list.size(); // if (size==0) { // cout<<"List is empty!"<<endl; // } cout<<"List size :- "<<size<<endl; for(int i=0;i<size;i++){ cout<<"Class monitor number "<<i+1<<endl; class_monitor_list[i].display(); } } else if (choice==19) { int size=leader_list.size(); // if (size==0) { // cout<<"List is empty!"<<endl; // } cout<<"List size :- "<<size<<endl; for(int i=0;i<size;i++){ cout<<"Leader number "<<i+1<<endl; leader_list[i].display(); } } else if (choice==20) { int size=staff_list.size(); // if (size==0) { // cout<<"List is empty!"<<endl; // } cout<<"List size :- "<<size<<endl; for(int i=0;i<size;i++){ cout<<"Staff number "<<i+1<<endl; staff_list[i].display(); } } else if (choice==21) { int size=teacher_list.size(); // if (size==0) { // cout<<"List is empty!"<<endl; // } cout<<"List size :- "<<size<<endl; for(int i=0;i<size;i++){ cout<<"teacher number "<<i+1<<endl; teacher_list[i].display(); } } else if (choice==22) { int size=class_teacher_list.size(); // if (size==0) { // cout<<"List is empty!"<<endl; // } cout<<"List size :- "<<size<<endl; for(int i=0;i<size;i++){ cout<<"class_teacher number "<<i+1<<endl; class_teacher_list[i].display(); } } else if (choice==23) { obj_library.display(); } else if (choice==24) { return; } cout<<"Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin>>ch; if (ch=='y' || ch=='Y') { admin_functions(); } else { return; } } void admin:: pay_staff(){ int id; cout<<"Enter the id of the staff(staff/teacher/class-teacher) you want to make the payment"<<endl; cin>>id; int check1=0; // staff int check2=0; // teacher int check3=0; // class-teacher int size=staff_list.size(); auto it=staff_list.begin(); staff *ptr; for(int i=0;i<size;i++){ if (staff_list[i].get_staff_id()==id) { // staff_list.erase(it); ptr=&staff_list[i]; check1=1; break; } it++; } int size2=teacher_list.size(); auto it2=teacher_list.begin(); teacher *ptr2; for(int i=0;i<size2;i++){ if (teacher_list[i].get_staff_id()==id) { // staff_list.erase(it); ptr2=&teacher_list[i]; check2=1; break; } it2++; } int size3=class_teacher_list.size(); auto it3=class_teacher_list.begin(); class_teacher *ptr3; for(int i=0;i<size3;i++){ if (class_teacher_list[i].get_staff_id()==id) { // staff_list.erase(it); ptr3=&class_teacher_list[i]; check3=1; break; } it3++; } if (check1==1){ // cout<<"The staff with id "<<id<<" has been delted successfully "<<endl; int amount=ptr->get_salary(); // if already paid then do not pay if (ptr->get_payment_done()==1) { cout<<"Payment is already done!!"<<endl; } else { obj_bank.pay_payment_staff(id,amount); ptr->set_payment_done(1); } } else if (check2==1) { int amount=ptr2->get_salary(); // if already paid then do not pay if (ptr2->get_payment_done()==1) { cout<<"Payment is already done!!"<<endl; } else { obj_bank.pay_payment_staff(id,amount); ptr2->set_payment_done(1); } } else if (check3==1) { int amount=ptr3->get_salary(); // if already paid then do not pay if (ptr3->get_payment_done()==1) { cout<<"Payment is already done!!"<<endl; } else { obj_bank.pay_payment_staff(id,amount); ptr3->set_payment_done(1); } } else { cout <<"No such staff exist "<<endl; } } void admin:: add_class_monitor(){ class_monitor obj1; obj1.set_fee_paid(0); string str; cout << "Enter Student name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all // roll number or id we will give you this // int roll_no; // cout << "Enter Roll no :- "; // cin >> roll_no; student_id++; obj1.set_roll_no(student_id); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int standard; cout << "Enter Standard :-"; cin >> standard; obj1.set_standard(standard); // int status; // cout << "Enter Status :-"; // cin >> status; // obj1.update_standard(status); // 1 for pass 0 for fail // string date; int present; // cout << "Enter date :-"; // cin >> date; // cout << "Enter Present :-"; // cin >> present; // obj1.add_date_for_attandence(date, present); // date, 1 or 0 1 for present 0 for absent // unique here // int x; // cout<<"Enter the standard you are monitor of "<<endl; // cin>>x; // obj1.set_standard(x); class_monitor_list.push_back(obj1); } void admin :: add_leader(){ leader obj1; obj1.set_fee_paid(0); string str; cout << "Enter Student name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all // roll number or id we will give you this // int roll_no; // cout << "Enter Roll no :- "; // cin >> roll_no; student_id++; obj1.set_roll_no(student_id); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int standard; cout << "Enter Standard :-"; cin >> standard; obj1.set_standard(standard); // int status; // cout << "Enter Status :-"; // cin >> status; // obj1.update_standard(status); // 1 for pass 0 for fail // string date; int present; // cout << "Enter date :-"; // cin >> date; // cout << "Enter Present :-"; // cin >> present; // obj1.add_date_for_attandence(date, present); // date, 1 or 0 1 for present 0 for absent // unique // high school leader or middle school leader // can add this if you want leader_list.push_back(obj1); } void admin:: add_class_teacher() { class_teacher obj1; obj1.set_payment_done(0); // as soon as the object is created --> set the payment done to 0 string str; cout << "Enter name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all staff_id++; obj1.set_staff_id(staff_id); // string designation; // cout<<"Enter designation "<<endl; // cin>>designation; // we have a teacher here obj1.set_designation("Class Teacher"); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string address; cout << "Enter address :-"; cin >> address; obj1.set_address(address); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int salary; cout << "Enter salary :-"; cin >> salary; obj1.set_salary(salary); // unique s int x; cout<<"Enter the standard you are the class teacher of "<<endl; cin>>x; obj1.set_batch_no(x); class_teacher_list.push_back(obj1); } // no menu required here // you want to have these things // like they are mandatory void admin:: add_student(){ student obj1; // obj1.set_percentage(0); // done via setting name only obj1.set_fee_paid(0); // initalization string str; cout << "Enter Student name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all // roll number or id we will give you this // int roll_no; // cout << "Enter Roll no :- "; // cin >> roll_no; student_id++; obj1.set_roll_no(student_id); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int standard; cout << "Enter Standard :-"; cin >> standard; obj1.set_standard(standard); // int status; // cout << "Enter Status :-"; // cin >> status; // obj1.update_standard(status); // 1 for pass 0 for fail // string date; int present; // cout << "Enter date :-"; // cin >> date; // cout << "Enter Present :-"; // cin >> present; // obj1.add_date_for_attandence(date, present); // date, 1 or 0 1 for present 0 for absent student_list.push_back(obj1); cout<<"Student has been added successfully!" <<endl; } void admin:: add_staff(){ staff obj1; obj1.set_payment_done(0); // as soon as the object is created --> set the payment done to 0 string str; cout << "Enter name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all staff_id++; obj1.set_staff_id(staff_id); string designation; cout<<"Enter designation "<<endl; cin>>designation; obj1.set_designation(designation); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string address; cout << "Enter address :-"; cin >> address; obj1.set_address(address); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int salary; cout << "Enter salary :-"; cin >> salary; obj1.set_salary(salary); staff_list.push_back(obj1); } void admin:: add_teacher(){ teacher obj1; obj1.set_payment_done(0); // as soon as the object is created --> set the payment done to 0 string str; cout << "Enter name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all staff_id++; obj1.set_staff_id(staff_id); // string designation; // cout<<"Enter designation "<<endl; // cin>>designation; // we have a teacher here obj1.set_designation("Teacher"); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string address; cout << "Enter address :-"; cin >> address; obj1.set_address(address); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int salary; cout << "Enter salary :-"; cin >> salary; obj1.set_salary(salary); teacher_list.push_back(obj1); } void admin:: remove_student(){ int id; cout<<"Enter the roll number (student id) to be removed "; cin>>id; int check=0; int size=student_list.size(); auto it=student_list.begin(); for(int i=0;i<size;i++){ if (student_list[i].get_roll_no()==id) { student_list.erase(it); check=1; break; } it++; } if (check){ cout<<"The student with id "<<id<<" has been delted successfully "<<endl; } else { cout <<"No such student exist "<<endl; } } void admin:: remove_staff(){ int id; cout<<"Enter the staff id to be removed "; cin>>id; int check=0; int size=staff_list.size(); auto it=staff_list.begin(); for(int i=0;i<size;i++){ if (staff_list[i].get_staff_id()==id) { staff_list.erase(it); check=1; break; } it++; } if (check){ cout<<"The staff with id "<<id<<" has been delted successfully "<<endl; } else { cout <<"No such staff exist "<<endl; } } void admin:: remove_teacher(){ int id; cout<<"Enter the teacher id to be removed "; // staff id cin>>id; int check=0; int size=teacher_list.size(); auto it=teacher_list.begin(); for(int i=0;i<size;i++){ if (teacher_list[i].get_staff_id()==id) { teacher_list.erase(it); check=1; break; } it++; } if (check){ cout<<"The teacher with id "<<id<<" has been delted successfully "<<endl; } else { cout <<"No such teacher exist "<<endl; } } void admin:: remove_class_teacher(){ int id; cout<<"Enter the class teacher id to be removed "; // staff id cin>>id; int check=0; int size=class_teacher_list.size(); auto it=class_teacher_list.begin(); for(int i=0;i<size;i++){ if (class_teacher_list[i].get_staff_id()==id) { class_teacher_list.erase(it); check=1; break; } it++; } if (check){ cout<<"The class teacher with id "<<id<<" has been delted successfully "<<endl; } else { cout <<"No such class teacher exist "<<endl; } } void admin:: remove_class_monitor(){ int id; cout<<"Enter the roll number (student id monitor ) to be removed "; cin>>id; int check=0; int size=class_monitor_list.size(); auto it=class_monitor_list.begin(); for(int i=0;i<size;i++){ if (class_monitor_list[i].get_roll_no()==id) { class_monitor_list.erase(it); check=1; break; } it++; } if (check){ cout<<"The class monitor student with id "<<id<<" has been delted successfully "<<endl; } else { cout <<"No such student exist "<<endl; } } void admin:: remove_leader(){ int id; cout<<"Enter the roll number ( leade ) to be removed "; cin>>id; int check=0; int size=leader_list.size(); auto it=leader_list.begin(); for(int i=0;i<size;i++){ if (leader_list[i].get_roll_no()==id) { leader_list.erase(it); check=1; break; } it++; } if (check){ cout<<"The leader student with id "<<id<<" has been delted successfully "<<endl; } else { cout <<"No such student exist "<<endl; } } void admin:: staff_functions(){ int id; cout<<"Enter your staff id "; cin>>id; int check=0; int size=staff_list.size(); staff *ptr; auto it=staff_list.begin(); for(int i=0;i<size;i++){ if (staff_list[i].get_staff_id()==id) { ptr=&staff_list[i]; check=1; break; } it++; } if (check==0) { cout<<"The staff with this id do not exist "<<endl; } else { // designation change // address change // salary change while(1){ cout<<"The staff with this "<<id<<" here "<<endl; cout<<"MENU "<<endl; cout<<"---------------------------------"<<endl; cout<<"Press 1 for change username "<<endl; cout<<"Press 2 for change name "<<endl; cout<<"Press 3 for change email "<<endl; cout<<"Press 4 for change phone_no "<<endl; cout<<"Press 5 for change date_of_birth "<<endl; cout<<"Press 6 for change designation "<<endl; cout<<"Press 7 for get username "<<endl; cout<<"Press 8 for get name "<<endl; cout<<"Press 9 for get email "<<endl; cout<<"Press 10 for get phone_no "<<endl; cout<<"Press 11 for get date_of_birth "<<endl; cout<<"Press 12 for get designation "<<endl; cout<<"Press 13 for get staff id "<<endl; cout<<"Press 14 for add date for attendance "<<endl; cout<<"Press 15 for marking todays attendance "<<endl; cout<<"Press 16 to set address"<<endl; cout<<"Press 17 to get address"<<endl; cout<<"Press 18 to set salary"<<endl; cout<<"Press 19 to get salary "<<endl; cout<<"Press 20 to get the attendance list "<<endl; // cout<<"Press 19 to get the report-card "<<endl; // new cout<<"Press 21 to check payment is done or not "<<endl; cout<<"Press 22 to display "<<endl; cout<<"Press 23 to exit "<<endl; int choice; cout<<"Enter your choice "<<endl; cin>>choice; if (choice==1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice==2) { string str; cout << "Enter Staff name :- "; cin >> str; ptr->set_name(str); } else if (choice==3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice==4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice==5){ string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice==6) { string designation; cout << "Enter designation :-"; cin >> designation; ptr->set_designation(designation); } else if (choice==7){ string str=ptr->get_username(); cout<<"Username -"<<str<<endl; } else if (choice==8){ string str=ptr->get_name(); cout<<"Name -"<<str<<endl; } else if (choice==9){ string str=ptr->get_email(); cout<<"Email -"<<str<<endl; } else if (choice==10){ string str=ptr->get_phone_no(); cout<<"Phone number -"<<str<<endl; } else if (choice==11){ string str=ptr->get_date_of_birth(); cout<<"Date of birth -"<<str<<endl; } else if (choice==12){ string str=ptr->get_designation(); cout<<"Designation -"<<str<<endl; } else if (choice==13){ int x=ptr->get_staff_id(); cout<<"Staff id -"<<x<<endl; } else if (choice==14){ string str; int x; cout<<"Enter the date "<<endl; cin>>str; cout<<"Enter <1,0> ( 1 for present and 0 for absent ) "<<endl; cin>>x; ptr->add_date_for_attandence(str,x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice==16){ string str; cout<<"Enter Address "<<endl; cin>>str; ptr->set_address(str); } else if (choice==17){ string str =ptr->get_address(); cout<<str<<endl; } else if (choice==18){ int x; cout<<"Enter salary"<<endl; cin>>x; ptr->set_salary(x); } else if (choice==19){ int x=ptr->get_salary(); cout<<"salary "<<x<<endl; } else if (choice==20){ vector <pair <string ,int >> v; v=ptr->get_attendance_list(); cout<<"Date"<<" "<<"Status"<<endl; for(auto x: v){ cout<<x.first<<" "<<x.second<<endl; } } // else if (choice==19) { // ptr->show_report(); // } else if (choice==21) { int x=ptr->get_payment_done(); cout<<x<<endl; } else if (choice==22) { ptr->display(); } else if (choice==23) { return; } cout<<"Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin>>ch; if (ch=='y' || ch=='Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function void admin:: teacher_functions(){ int id; cout<<"Enter your staff id "; cin>>id; int check=0; int size=teacher_list.size(); teacher *ptr; auto it=teacher_list.begin(); for(int i=0;i<size;i++){ if (teacher_list[i].get_staff_id()==id) { ptr=&teacher_list[i]; check=1; break; } it++; } if (check==0) { cout<<"The staff with this id do not exist "<<endl; } else { // designation change // address change // salary change while(1){ cout<<"The teacher with this id "<<id<<" here !!"<<endl; cout<<"MENU "<<endl; cout<<"---------------------------------"<<endl; cout<<"Press 1 for change username "<<endl; cout<<"Press 2 for change name "<<endl; cout<<"Press 3 for change email "<<endl; cout<<"Press 4 for change phone_no "<<endl; cout<<"Press 5 for change date_of_birth "<<endl; cout<<"Press 6 for change designation "<<endl; cout<<"Press 7 for get username "<<endl; cout<<"Press 8 for get name "<<endl; cout<<"Press 9 for get email "<<endl; cout<<"Press 10 for get phone_no "<<endl; cout<<"Press 11 for get date_of_birth "<<endl; cout<<"Press 12 for get designation "<<endl; cout<<"Press 13 for get staff id "<<endl; cout<<"Press 14 for add date for attendance "<<endl; cout<<"Press 15 for marking todays attendance "<<endl; cout<<"Press 16 to set address"<<endl; cout<<"Press 17 to get address"<<endl; cout<<"Press 18 to set salary"<<endl; cout<<"Press 19 to get salary "<<endl; cout<<"Press 20 to get the attendance list "<<endl; // cout<<"Press 19 to get the report-card "<<endl; // unique cout<<"Press 21 to add subject "<<endl; cout<<"Press 22 to get the subject list"<<endl; cout<<"Press 23 to conduct exam "<<endl; cout<<"Press 24 to check payment is done or not "<<endl; cout<<"Press 25 to display "<<endl; cout<<"Press 26 to exit "<<endl; // // giving marks to student // cout<<"Press 25 to give marks to student "<<endl; int choice; cout<<"Enter your choice "<<endl; cin>>choice; if (choice==1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice==2) { string str; cout << "Enter Staff name :- "; cin >> str; ptr->set_name(str); } else if (choice==3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice==4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice==5){ string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice==6) { string designation; cout << "Enter designation :-"; cin >> designation; ptr->set_designation(designation); } else if (choice==7){ string str=ptr->get_username(); cout<<"Username -"<<str<<endl; } else if (choice==8){ string str=ptr->get_name(); cout<<"Name -"<<str<<endl; } else if (choice==9){ string str=ptr->get_email(); cout<<"Email -"<<str<<endl; } else if (choice==10){ string str=ptr->get_phone_no(); cout<<"Phone number -"<<str<<endl; } else if (choice==11){ string str=ptr->get_date_of_birth(); cout<<"Date of birth -"<<str<<endl; } else if (choice==12){ string str=ptr->get_designation(); cout<<"Designation -"<<str<<endl; } else if (choice==13){ int x=ptr->get_staff_id(); cout<<"Staff id -"<<x<<endl; } else if (choice==14){ string str; int x; cout<<"Enter the date "<<endl; cin>>str; cout<<"Enter <1,0> ( 1 for present and 0 for absent ) "<<endl; cin>>x; ptr->add_date_for_attandence(str,x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice==16){ string str; cout<<"Enter Address "<<endl; cin>>str; ptr->set_address(str); } else if (choice==17){ string str =ptr->get_address(); cout<<str<<endl; } else if (choice==18){ int x; cout<<"Enter salary"<<endl; cin>>x; ptr->set_salary(x); } else if (choice==19){ int x=ptr->get_salary(); cout<<"salary "<<x<<endl; } else if (choice==20){ vector <pair <string ,int >> v; v=ptr->get_attendance_list(); cout<<"Date"<<" "<<"Status"<<endl; for(auto x: v){ cout<<x.first<<" "<<x.second<<endl; } } else if (choice==21) { int x; string str; cout<<"Enter the subject "; cin>>str; cout<<"Enter the batch "; cin>>x; ptr->add_subject(x,str); } else if (choice==22) { cout<<"Subject list is as follows " <<endl; ptr->get_subject(); } else if (choice==23) { ptr->conduct_exam(); } // else if (choice==19) { // ptr->show_report(); // } else if (choice==24) { int x=ptr->get_payment_done(); cout<<x<<endl; } else if (choice==25) { ptr->display(); } else if (choice==26) { return; } cout<<"Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin>>ch; if (ch=='y' || ch=='Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function void admin:: class_teacher_functions(){ int id; cout<<"Enter your staff id "; cin>>id; int check=0; int size=class_teacher_list.size(); class_teacher *ptr; auto it=class_teacher_list.begin(); for(int i=0;i<size;i++){ if (class_teacher_list[i].get_staff_id()==id) { ptr=&class_teacher_list[i]; check=1; break; } it++; } if (check==0) { cout<<"The staff with this id do not exist "<<endl; return; } else { // designation change // address change // salary change while (1){ cout<<"MENU "<<endl; cout<<"class Teacher here id -> "<<id<<endl; cout<<"---------------------------------"<<endl; cout<<"Press 1 for change username "<<endl; cout<<"Press 2 for change name "<<endl; cout<<"Press 3 for change email "<<endl; cout<<"Press 4 for change phone_no "<<endl; cout<<"Press 5 for change date_of_birth "<<endl; cout<<"Press 6 for change designation "<<endl; cout<<"Press 7 for get username "<<endl; cout<<"Press 8 for get name "<<endl; cout<<"Press 9 for get email "<<endl; cout<<"Press 10 for get phone_no "<<endl; cout<<"Press 11 for get date_of_birth "<<endl; cout<<"Press 12 for get designation "<<endl; cout<<"Press 13 for get staff id "<<endl; cout<<"Press 14 for add date for attendance "<<endl; cout<<"Press 15 for marking todays attendance "<<endl; cout<<"Press 16 to set address"<<endl; cout<<"Press 17 to get address"<<endl; cout<<"Press 18 to set salary"<<endl; cout<<"Press 19 to get salary "<<endl; cout<<"Press 20 to get the attendance list "<<endl; // cout<<"Press 19 to get the report-card "<<endl; // unique cout<<"Press 21 to add subject "<<endl; cout<<"Press 22 to get the subject list"<<endl; cout<<"Press 23 to conduct exam "<<endl; cout<<"Press 24 to change the branch "<<endl; cout<<"Press 25 to get the branch "<<endl; cout<<"Press 26 to check payment is done or not "<<endl; // new // lib // check if you like want the lib infro in student class as well or not cout<<"Press 27 to issue a book " <<endl; cout<<"Press 28 to submit a book"<<endl; // giving marks to student --> check later cout<<"Press 29 to give marks to student "<<endl; // all the teachers gives the marks to the class teacher and class teacher gives them to student cout<<"Press 30 to change student entries "<<endl; // being the class teacher --> it can cout<<"Press 31 to display "<<endl; cout<<"Press 32 to exit "<<endl; int choice; cout<<"Enter your choice "<<endl; cin>>choice; if (choice==1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice==2) { string str; cout << "Enter Staff name :- "; cin >> str; ptr->set_name(str); } else if (choice==3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice==4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice==5){ string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice==6) { string designation; cout << "Enter designation :-"; cin >> designation; ptr->set_designation(designation); } else if (choice==7){ string str=ptr->get_username(); cout<<"Username -"<<str<<endl; } else if (choice==8){ string str=ptr->get_name(); cout<<"Name -"<<str<<endl; } else if (choice==9){ string str=ptr->get_email(); cout<<"Email -"<<str<<endl; } else if (choice==10){ string str=ptr->get_phone_no(); cout<<"Phone number -"<<str<<endl; } else if (choice==11){ string str=ptr->get_date_of_birth(); cout<<"Date of birth -"<<str<<endl; } else if (choice==12){ string str=ptr->get_designation(); cout<<"Designation -"<<str<<endl; } else if (choice==13){ int x=ptr->get_staff_id(); cout<<"Staff id -"<<x<<endl; } else if (choice==14){ string str; int x; cout<<"Enter the date "<<endl; cin>>str; cout<<"Enter <1,0> ( 1 for present and 0 for absent ) "<<endl; cin>>x; ptr->add_date_for_attandence(str,x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice==16){ string str; cout<<"Enter Address "<<endl; cin>>str; ptr->set_address(str); } else if (choice==17){ string str =ptr->get_address(); cout<<str<<endl; } else if (choice==18){ int x; cout<<"Enter salary"<<endl; cin>>x; ptr->set_salary(x); } else if (choice==19){ int x=ptr->get_salary(); cout<<"salary "<<x<<endl; } else if (choice==20){ vector <pair <string ,int >> v; v=ptr->get_attendance_list(); cout<<"Date"<<" "<<"Status"<<endl; for(auto x: v){ cout<<x.first<<" "<<x.second<<endl; } } else if (choice==21) { int x; string str; cout<<"Enter the subject "; cin>>str; cout<<"Enter the batch "; cin>>x; ptr->add_subject(x,str); } else if (choice==22) { cout<<"Subject list is as follows " <<endl; ptr->get_subject(); } else if (choice==23) { ptr->conduct_exam(); } else if (choice==24) { int x; cout<<"Enter the branch "; cin>>x; ptr->set_batch_no(x); } else if (choice==25) { int x=ptr->get_batch_no(); cout<<"Branch "<<x<<endl; } // else if (choice==19) { // ptr->show_report(); // } else if (choice==26) { int x=ptr->get_payment_done(); cout<<x<<endl; } else if (choice==27) { string book; cout<<"Enter book name you want "<<endl; cin>>book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout<<"Enter the todays date "<<endl; cin>>date; obj_library.issue_teacher(book,date,id); } else if (choice==28) { string book; cout<<"Enter book name you want to return "<<endl; cin>>book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout<<"Enter the todays date ( return date ) "<<endl; cin>>date; obj_library.submit_teacher(id,book,date); } else if (choice==29) { int id; cout<<"Enter the roll no of the student you want "<<endl; cin>>id; int check=0; int size=student_list.size(); student *pointer; auto it=student_list.begin(); for(int i=0;i<size;i++){ if (student_list[i].get_roll_no()==id) { pointer=&student_list[i]; check=1; break; } it++; } if (check==0) { cout<<"The student with this id do not exist "<<endl; } else { exam_marks m=ptr->give_marks(); // pointer->exam.push_back(m); // direct cannot give the marks // so make a function in student pointer->add_exam_marks(m); } } else if (choice==31) { ptr->display(); } else if (choice==32) { return; } else if (choice==30) { int id; cout<<"Enter your student id "; cin>>id; int check=0; int size=student_list.size(); student *pointer; auto it=student_list.begin(); for(int i=0;i<size;i++){ if (student_list[i].get_roll_no()==id) { pointer=&student_list[i]; check=1; break; } it++; } if (check==0) { cout<<"The student with this id do not exist "<<endl; } // check if the class teacher and student are of the same batch else if (pointer->get_standard()!=ptr->get_batch_no()) { cout<<"You are not the class teacher of this batch (student belongs) --> so you cannot .... "<<endl; } else if (pointer->get_standard()==ptr->get_batch_no()) { // can change while(1) { cout<<"MENU "<<endl; cout<<"---------------------------------"<<endl; cout<<"Press 1 for change username "<<endl; cout<<"Press 2 for change name "<<endl; cout<<"Press 3 for change email "<<endl; cout<<"Press 4 for change phone_no "<<endl; cout<<"Press 5 for change date_of_birth "<<endl; // cout<<"Press 6 for change standard "<<endl; --> check you can update the standard from here cout<<"Press 6 for get username "<<endl; cout<<"Press 7 for get name "<<endl; cout<<"Press 8 for get email "<<endl; cout<<"Press 9 for get phone_no "<<endl; cout<<"Press 10 for get date_of_birth "<<endl; cout<<"Press 11 for get standard "<<endl; cout<<"Press 12 for get roll no "<<endl; // cout<<"Press 14 for add date for attendance "<<endl; // cout<<"Press 15 for marking todays attendance "<<endl; // cout<<"Press 16 to give exam"<<endl; cout<<"Press 13 to get the percentage "<<endl; cout<<"Press 14 to get the attendance list "<<endl; cout<<"Press 15 to get the report-card "<<endl; // new // bank // cout<<"Press 20 to pay the fees"<<endl; // cout<<"Press 21 to get fee paid or not"<<endl; // new // lib // check if you like want the lib infro in student class as well or not // cout<<"Press 22 to issue a book " <<endl; // cout<<"Press 23 to submit a book"<<endl; int choice1; cout<<"Enter your choice "<<endl; cin>>choice1; if (choice1==1) { string username; cout << "Enter Username :- "; cin >> username; pointer->set_username(username); } else if (choice1==2) { string str; cout << "Enter Student name :- "; cin >> str; pointer->set_name(str); } else if (choice1==3) { string email; cout << "Enter Email :-"; cin >> email; pointer->set_email(email); } else if (choice1==4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; pointer->set_phone_no(phone_no); } else if (choice1==5){ string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; pointer->set_date_of_birth(date_of_birth); } // else if (choice==6) { // int standard; // cout << "Enter Standard :-"; // cin >> standard; // ptr->set_standard(standard); // } else if (choice1==6){ string str=pointer->get_username(); cout<<"Username -"<<str<<endl; } else if (choice1==7){ string str=pointer->get_name(); cout<<"Name -"<<str<<endl; } else if (choice1==8){ string str=pointer->get_email(); cout<<"Email -"<<str<<endl; } else if (choice1==9){ string str=pointer->get_phone_no(); cout<<"Phone number -"<<str<<endl; } else if (choice1==10){ string str=pointer->get_date_of_birth(); cout<<"Date of birth -"<<str<<endl; } else if (choice1==11){ int str=pointer->get_standard(); cout<<"Standard -"<<str<<endl; } else if (choice1==12){ int str=pointer->get_roll_no(); cout<<"Roll no -"<<str<<endl; } // else if (choice==13){ // string str; // int x; // cout<<"Enter the date "<<endl; // cin>>str; // cout<<"Enter <1,0> ( 1 for present and 0 for absent ) "<<endl; // cin>>x; // ptr->add_date_for_attandence(str,x); // } // else if (choice==15){ // ptr->mark_todays_attandence(); // } // else if (choice==16){ // ptr->give_exam(); // } else if (choice1==13){ float x=pointer->get_percentage(); cout<<"Percentage - "<<x<<endl; } else if (choice1==14){ vector <pair <string ,int >> v; v=pointer->get_attendance_list(); cout<<"Date"<<" "<<"Status"<<endl; for(auto x: v){ cout<<x.first<<" "<<x.second<<endl; } } else if (choice1==15) { pointer->show_report(); } // else if (choice==20) { // // fix this fees somehow say 1000 store it somewhere // obj_bank.perform_student_transaction(ptr->get_roll_no(),1000); // ptr->set_fee_paid(1); // } // else if (choice==21) { // int x=ptr->get_fee_paid(); // cout<<x<<endl; // } // else if (choice==22) { // string book; // cout<<"Enter book name you want "<<endl; // cin>>book; // string date; // // input or use prabhav function to fetch todays date // // now we are inputing // cout<<"Enter the todays date "<<endl; // cin>>date; // obj_library.issue_student(book,date,id); // } // else if (choice==23) { // string book; // cout<<"Enter book name you want to return "<<endl; // cin>>book; // string date; // // input or use prabhav function to fetch todays date // // now we are inputing // cout<<"Enter the todays date ( return date ) "<<endl; // cin>>date; // obj_library.issue_student(book,date,id); // /pointer cout<<"Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin>>ch; if (ch=='y' || ch=='Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } } cout<<"Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin>>ch; if (ch=='y' || ch=='Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function // update status // check where to add --> while assigning percentage // teacher will assign marks --> then set percentage --> if percentage is greater than sth then // update status // choice 16 // give exam --> check // change to go via the teacher // int number_of_exams; --> use this void admin:: student_functions(){ int id; cout<<"Enter your student id "; cin>>id; int check=0; int size=student_list.size(); student *ptr; auto it=student_list.begin(); for(int i=0;i<size;i++){ if (student_list[i].get_roll_no()==id) { ptr=&student_list[i]; check=1; break; } it++; } if (check==0) { cout<<"The student with this id do not exist "<<endl; } else { while(1){ cout<<"Student with this id "<<id<<" here !!"<<endl; cout<<"MENU "<<endl; cout<<"---------------------------------"<<endl; cout<<"Press 1 for change username "<<endl; cout<<"Press 2 for change name "<<endl; cout<<"Press 3 for change email "<<endl; cout<<"Press 4 for change phone_no "<<endl; cout<<"Press 5 for change date_of_birth "<<endl; cout<<"Press 6 for change standard "<<endl; cout<<"Press 7 for get username "<<endl; cout<<"Press 8 for get name "<<endl; cout<<"Press 9 for get email "<<endl; cout<<"Press 10 for get phone_no "<<endl; cout<<"Press 11 for get date_of_birth "<<endl; cout<<"Press 12 for get standard "<<endl; cout<<"Press 13 for get roll no "<<endl; cout<<"Press 14 for add date for attendance "<<endl; cout<<"Press 15 for marking todays attendance "<<endl; cout<<"Press 16 to give exam"<<endl; cout<<"Press 17 to get the percentage "<<endl; cout<<"Press 18 to get the attendance list "<<endl; cout<<"Press 19 to get the report-card "<<endl; // new // bank cout<<"Press 20 to pay the fees"<<endl; cout<<"Press 21 to get fee paid or not"<<endl; // new // lib // check if you like want the lib infro in student class as well or not cout<<"Press 22 to issue a book " <<endl; cout<<"Press 23 to submit a book"<<endl; cout<<"Press 24 to display"<<endl; cout<<"Press 25 to give maths exam"<<endl; cout<<"Press 26 to exit"<<endl; int choice; cout<<"Enter your choice "<<endl; cin>>choice; if (choice==1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice==2) { string str; cout << "Enter Student name :- "; cin >> str; ptr->set_name(str); } else if (choice==3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice==4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice==5){ string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice==6) { int standard; cout << "Enter Standard :-"; cin >> standard; ptr->set_standard(standard); } else if (choice==7){ string str=ptr->get_username(); cout<<"Username -"<<str<<endl; } else if (choice==8){ string str=ptr->get_name(); cout<<"Name -"<<str<<endl; } else if (choice==9){ string str=ptr->get_email(); cout<<"Email -"<<str<<endl; } else if (choice==10){ string str=ptr->get_phone_no(); cout<<"Phone number -"<<str<<endl; } else if (choice==11){ string str=ptr->get_date_of_birth(); cout<<"Date of birth -"<<str<<endl; } else if (choice==12){ int str=ptr->get_standard(); cout<<"Standard -"<<str<<endl; } else if (choice==13){ int str=ptr->get_roll_no(); cout<<"Roll no -"<<str<<endl; } else if (choice==14){ string str; int x; cout<<"Enter the date "<<endl; cin>>str; cout<<"Enter <1,0> ( 1 for present and 0 for absent ) "<<endl; cin>>x; ptr->add_date_for_attandence(str,x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice==16){ ptr->give_exam(); } else if (choice==17){ float x=ptr->get_percentage(); cout<<"Percentage - "<<x<<endl; } else if (choice==18){ vector <pair <string ,int >> v; v=ptr->get_attendance_list(); cout<<"Date"<<" "<<"Status"<<endl; for(auto x: v){ cout<<x.first<<" "<<x.second<<endl; } } else if (choice==19) { ptr->show_report(); } else if (choice==20) { // fix this fees somehow say 1000 store it somewhere obj_bank.perform_student_transaction(ptr->get_roll_no(),1000); ptr->set_fee_paid(1); } else if (choice==21) { int x=ptr->get_fee_paid(); cout<<x<<endl; } else if (choice==22) { string book; cout<<"Enter book name you want "<<endl; cin>>book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout<<"Enter the todays date "<<endl; cin>>date; obj_library.issue_student(book,date,id); } else if (choice==23) { string book; cout<<"Enter book name you want to return "<<endl; cin>>book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout<<"Enter the todays date ( return date ) "<<endl; cin>>date; obj_library.submit_student(id,book,date); } else if (choice==24) { ptr->display(); } else if (choice==25){ ptr->give_maths_exam(); } else if (choice==26) { return ; } cout<<"Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin>>ch; if (ch=='y' || ch=='Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function void admin:: class_monitor_functions(){ int id; cout<<"Enter your student id "; cin>>id; int check=0; int size=class_monitor_list.size(); class_monitor *ptr; auto it=class_monitor_list.begin(); for(int i=0;i<size;i++){ if (class_monitor_list[i].get_roll_no()==id) { ptr=&class_monitor_list[i]; check=1; break; } it++; } if (check==0) { cout<<"The student with this id do not exist "<<endl; } else { while(1){ cout<<"The class monitor (student) with this id"<<id<< " here"<<endl; cout<<"MENU "<<endl; cout<<"---------------------------------"<<endl; cout<<"Press 1 for change username "<<endl; cout<<"Press 2 for change name "<<endl; cout<<"Press 3 for change email "<<endl; cout<<"Press 4 for change phone_no "<<endl; cout<<"Press 5 for change date_of_birth "<<endl; cout<<"Press 6 for change standard "<<endl; cout<<"Press 7 for get username "<<endl; cout<<"Press 8 for get name "<<endl; cout<<"Press 9 for get email "<<endl; cout<<"Press 10 for get phone_no "<<endl; cout<<"Press 11 for get date_of_birth "<<endl; cout<<"Press 12 for get standard "<<endl; cout<<"Press 13 for get roll no "<<endl; cout<<"Press 14 for add date for attendance "<<endl; cout<<"Press 15 for marking todays attendance "<<endl; cout<<"Press 16 to give exam"<<endl; cout<<"Press 17 to get the percentage "<<endl; cout<<"Press 18 to get the attendance list "<<endl; cout<<"Press 19 to get the report-card "<<endl; // unique here // cout<<"Press 20 to change standard you are monitoring"<<endl; // cout<<"Press 21 to get the standard you are monitoring"<<endl; cout<<"Press 22 to maintain the class"<<endl; // new cout<<"Press 23 to pay the fees"<<endl; cout<<"Press 24 to get fee paid or not"<<endl; // new // lib // check if you like want the lib infro in student class as well or not cout<<"Press 25 to issue a book " <<endl; cout<<"Press 26 to submit a book"<<endl; cout<<"Press 27 to display"<<endl; cout<<"Press 28 to exit"<<endl; int choice; cout<<"Enter your choice "<<endl; cin>>choice; if (choice==1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice==2) { string str; cout << "Enter Student name :- "; cin >> str; ptr->set_name(str); } else if (choice==3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice==4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice==5){ string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice==6) { int standard; cout << "Enter Standard :-"; cin >> standard; ptr->set_standard(standard); } else if (choice==7){ string str=ptr->get_username(); cout<<"Username -"<<str<<endl; } else if (choice==8){ string str=ptr->get_name(); cout<<"Name -"<<str<<endl; } else if (choice==9){ string str=ptr->get_email(); cout<<"Email -"<<str<<endl; } else if (choice==10){ string str=ptr->get_phone_no(); cout<<"Phone number -"<<str<<endl; } else if (choice==11){ string str=ptr->get_date_of_birth(); cout<<"Date of birth -"<<str<<endl; } else if (choice==12){ int str=ptr->get_standard(); cout<<"Standard -"<<str<<endl; } else if (choice==13){ int str=ptr->get_roll_no(); cout<<"Roll no -"<<str<<endl; } else if (choice==14){ string str; int x; cout<<"Enter the date "<<endl; cin>>str; cout<<"Enter <1,0> ( 1 for present and 0 for absent ) "<<endl; cin>>x; ptr->add_date_for_attandence(str,x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice==16){ ptr->give_exam(); } else if (choice==17){ float x=ptr->get_percentage(); cout<<"Percentage - "<<x<<endl; } else if (choice==18){ vector <pair <string ,int >> v; v=ptr->get_attendance_list(); cout<<"Date"<<" "<<"Status"<<endl; for(auto x: v){ cout<<x.first<<" "<<x.second<<endl; } } else if (choice==19) { ptr->show_report(); } // else if (choice==20) { // int x; // cout<<"Enter the standard you are monitoring"<<endl; // cin>>x; // ptr->set_standard(x); // } // else if (choice==21) { // int x=ptr->get_standard(); // cout<<"Standard you are monitoring "<<x<<endl; // } else if (choice==22) { ptr->maintain_the_class(); } else if (choice==23) { // fix this fees somehow say 1000 store it somewhere obj_bank.perform_student_transaction(ptr->get_roll_no(),1000); ptr->set_fee_paid(1); } else if (choice==24) { int x=ptr->get_fee_paid(); cout<<x<<endl; } else if (choice==25) { string book; cout<<"Enter book name you want "<<endl; cin>>book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout<<"Enter the todays date "<<endl; cin>>date; obj_library.issue_student(book,date,id); } else if (choice==26) { string book; cout<<"Enter book name you want to return "<<endl; cin>>book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout<<"Enter the todays date ( return date ) "<<endl; cin>>date; obj_library.issue_student(book,date,id); } else if (choice==27) { ptr->display(); } else if (choice==28) { return ; } cout<<"Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin>>ch; if (ch=='y' || ch=='Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function void admin::leader_functions(){ int id; cout<<"Enter your student id "; cin>>id; int check=0; int size=leader_list.size(); leader *ptr; auto it=leader_list.begin(); for(int i=0;i<size;i++){ if (leader_list[i].get_roll_no()==id) { ptr=&leader_list[i]; check=1; break; } it++; } if (check==0) { cout<<"The student with this id do not exist "<<endl; } else { while(1) { cout<<"The leader student with this id "<<id<<" here"<<endl; cout<<"MENU "<<endl; cout<<"---------------------------------"<<endl; cout<<"Press 1 for change username "<<endl; cout<<"Press 2 for change name "<<endl; cout<<"Press 3 for change email "<<endl; cout<<"Press 4 for change phone_no "<<endl; cout<<"Press 5 for change date_of_birth "<<endl; cout<<"Press 6 for change standard "<<endl; cout<<"Press 7 for get username "<<endl; cout<<"Press 8 for get name "<<endl; cout<<"Press 9 for get email "<<endl; cout<<"Press 10 for get phone_no "<<endl; cout<<"Press 11 for get date_of_birth "<<endl; cout<<"Press 12 for get standard "<<endl; cout<<"Press 13 for get roll no "<<endl; cout<<"Press 14 for add date for attendance "<<endl; cout<<"Press 15 for marking todays attendance "<<endl; cout<<"Press 16 to give exam"<<endl; cout<<"Press 17 to get the percentage "<<endl; cout<<"Press 18 to get the attendance list "<<endl; cout<<"Press 19 to get the report-card "<<endl; // unique here cout<<"Press 20 to change standard you are monitoring"<<endl; cout<<"Press 21 to get the standard you are monitoring"<<endl; cout<<"Press 22 to maintain the class"<<endl; cout<<"Press 23 to maintain the monitors "<<endl; // new cout<<"Press 24 to pay the fees"<<endl; cout<<"Press 25 to get fee paid or not"<<endl; // new // lib // check if you like want the lib infro in student class as well or not cout<<"Press 26 to issue a book " <<endl; cout<<"Press 27 to submit a book"<<endl; cout<<"Press 28 to display"<<endl; cout<<"Press 29 to exit"<<endl; int choice; cout<<"Enter your choice "<<endl; cin>>choice; if (choice==1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice==2) { string str; cout << "Enter Student name :- "; cin >> str; ptr->set_name(str); } else if (choice==3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice==4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice==5){ string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice==6) { int standard; cout << "Enter Standard :-"; cin >> standard; ptr->set_standard(standard); } else if (choice==7){ string str=ptr->get_username(); cout<<"Username -"<<str<<endl; } else if (choice==8){ string str=ptr->get_name(); cout<<"Name -"<<str<<endl; } else if (choice==9){ string str=ptr->get_email(); cout<<"Email -"<<str<<endl; } else if (choice==10){ string str=ptr->get_phone_no(); cout<<"Phone number -"<<str<<endl; } else if (choice==11){ string str=ptr->get_date_of_birth(); cout<<"Date of birth -"<<str<<endl; } else if (choice==12){ int str=ptr->get_standard(); cout<<"Standard -"<<str<<endl; } else if (choice==13){ int str=ptr->get_roll_no(); cout<<"Roll no -"<<str<<endl; } else if (choice==14){ string str; int x; cout<<"Enter the date "<<endl; cin>>str; cout<<"Enter <1,0> ( 1 for present and 0 for absent ) "<<endl; cin>>x; ptr->add_date_for_attandence(str,x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice==16){ ptr->give_exam(); } else if (choice==17){ float x=ptr->get_percentage(); cout<<"Percentage - "<<x<<endl; } else if (choice==18){ vector <pair <string ,int >> v; v=ptr->get_attendance_list(); cout<<"Date"<<" "<<"Status"<<endl; for(auto x: v){ cout<<x.first<<" "<<x.second<<endl; } } else if (choice==19) { ptr->show_report(); } else if (choice==20) { int x; cout<<"Enter the standard you are monitoring"<<endl; cin>>x; ptr->set_standard(x); } else if (choice==21) { int x=ptr->get_standard(); cout<<"Standard you are monitoring "<<x<<endl; } else if (choice==22) { ptr->maintain_the_class(); } // unique else if (choice==23) { ptr->maintain_the_monitor(); } else if (choice==24) { // fix this fees somehow say 1000 store it somewhere obj_bank.perform_student_transaction(ptr->get_roll_no(),1000); ptr->set_fee_paid(1); } else if (choice==25) { int x=ptr->get_fee_paid(); cout<<x<<endl; } else if (choice==26) { string book; cout<<"Enter book name you want "<<endl; cin>>book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout<<"Enter the todays date "<<endl; cin>>date; obj_library.issue_student(book,date,id); } else if (choice==27) { string book; cout<<"Enter book name you want to return "<<endl; cin>>book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout<<"Enter the todays date ( return date ) "<<endl; cin>>date; obj_library.issue_student(book,date,id); } else if (choice==28) { ptr->display(); } else if (choice==29) { return ; } cout<<"Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin>>ch; if (ch=='y' || ch=='Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function
52adab6d34cf1d6da48e03cb5ac7b7f69a47bfbc
2c97e06cb0031b47baf889c79f9558ec1c1d8f24
/week-02/day-2/practicegg/main.cpp
727d3b401b9c010ad1c7f15a0ca3f98510c887ce
[]
no_license
green-fox-academy/KisG93
c88d70721671ac3f5b6d4a94b240ca84cb859d98
133262e00fd7a82a7269a8f1adfec094114373ba
refs/heads/master
2020-04-02T17:22:10.749501
2019-02-21T13:17:27
2019-02-21T13:17:27
154,655,065
0
0
null
null
null
null
UTF-8
C++
false
false
611
cpp
main.cpp
#include <iostream> #include <vector> #include <map> #include <string> int main() { std::vector<int> myFavoriteNumbers2 = {8, 6 , 2, 0}; std::cout << myFavoriteNumbers2[3] << std::endl; std::cout << myFavoriteNumbers2.size() << std::endl; myFavoriteNumbers2.push_back(27); std::map<std::string, int> students = {{"Jozsi", 8}, {"Tibi",9}, {"Peti", 7}}; std::cout << "Tibi ennyi éves: " << students["Tibi"] << std::endl; std::string mentorName = "Tojas"; mentorName.push_back('k'); mentorName.push_back('a'); std::cout << mentorName << std::endl; return 0; }
e1341870513dcc0cd3e950345027b2ed96e914bf
52d97c724054fe880e8bb22e9ab5185227ed14f6
/Strings2.cpp
c90b5c2008ab43efdb3c0809694ed4842859d101
[]
no_license
mkwok94/School
9c66d5c6cc93d4257b4a9891eb970f43d40f04b3
bb1448629de4156243584a3e2e4ff05f208aafa1
refs/heads/master
2020-04-12T05:43:20.326900
2017-02-10T06:11:57
2017-02-10T06:11:57
62,365,085
0
1
null
null
null
null
UTF-8
C++
false
false
5,978
cpp
Strings2.cpp
// Lab 7 (Part 2), Arrays and Vectors in C++ // Programmer: Melinda (Mel) Kwok // Editor(s) used: Notepad++ // Compiler(s) used: Visual Studio //This library is for the buffer #include <cstdlib> //This library is for getting inputs and outputting #include <iostream> using std::cin; using std::cout; using std::endl; //This library is so the compiler can read strings #include <string> #include <algorithm> using std::swap; //Prototype for Copy String Function void myStrCpy(char*, const char*); //Prototype for String Comparison Function int myStrCmp(const char*, const char*); //Prototype for String Swap Function void myStrSwap(char*, char*); //Prototype for Uppercase Conversion Function void myStrUpr(char*); //Prototype for Lowercase Conversion Function void myStrLwr(char*); //Start of Main Function int main() { //Print my name and this assignment's title cout << "Lab 7 (Part 2), Arrays and Vectors in C++ \n"; cout << "Programmer: Melinda Kwok \n"; cout << "Editor(s) used: Notepad++ \n"; cout << "Compiler(s) used: Visual Studio \n"; cout << "File: " << __FILE__ << endl; cout << "Compiled: " << __DATE__ << " at " << __TIME__ << endl << endl; //Decalred varaibles! //All of them are just premade strings that we will be using for the whole function char a[100] = {"Hello World"}; char b[100]; char c[100] = {"Hello World"}; char d[100] = {"Suhhh dude"}; //This is calling the Copy Function into the Main Function //It is coping the string in array a and copying it into array b which is blank //It then outputs the results showing the original string and then it's copied version myStrCpy(b, a); cout << "Source string: " << a << endl; cout << "String copy: " << b << endl; cout << endl; cout << endl; //These are the Comparison Functions called back into the Main Function. I have 2 to show that it works on both equal and not equal strings //I know it's suppose to return 1 or 0 but I thought it would be neater to have it the outcome statements in the Function and then just pull whichever one is correct here myStrCmp(a, c); myStrCmp(a, d); cout << endl; //This is for the String Swap Function //It shows the two strings that I chose to swap as they are and then afterwards shows them swapped cout << "String 1: " << c << endl; cout << "String 2: " << d << endl; cout << "SWAP!" << endl; myStrSwap(c, d); cout << "String 1: " << c << endl; cout << "String 2: " << d << endl; cout << endl; //This is for the Uppercase Function //It shows the original string and then the new version as it is made in all uppercase letters cout << "Original String: " << a << endl; myStrUpr(a); cout << "Uppercase Version: " << a << endl; cout << endl; //This is for the Lowercase Function //It shows the original string and then the new version as it is made in all lowercase letters cout << "Original String: " << b << endl; myStrLwr(b); cout << "Lowercase Version: " << b << endl; return 0; }//End of Main Function //Copy String Function void myStrCpy (char b[], const char a[]) { //Variable i declared at 0 int i = 0; //While loop is reading through the constant array a, which is given from the main function //If an element in array a isn't a null character, it will put that element into array b and increment i while (a[i] != '\0') { b[i] = a[i]; i++; } //After everything has been put from array a into array b, it will have array equal a null character to end it //It is then sent back to the main function b[i] = '\0'; }//End of Copy String Function //String Comparison Function int myStrCmp(const char* a, const char* b) { //Declaring variables all as 0 int i = 0; int check = 0; int compare = 0; //While loop - while both array and a by don't have a null character, run this //If array a doesn't equal array b, check = 1 and will end this loop and increment so that strings will be output while (a[i] != '\0' && b[i] != '\0') { if (a[i] != b[i]) { check = 1; break; } i++; } //If check is still 0 and array and b have null characters; compare will = 1 if not, compare will = 2 //These numbers will be used to determine if the strings are equal or not if (check == 0 && a[i] == '\0' && b[i] == '\0') { compare = 1; } else { compare = 2; } //These use the number received from compare. If comapare = 1, it will give an output statement saying the strings are the same //If it doesn't equal 1, then it will say that the strings aren't equal //The resulting cout statement from compare will be sent back to the Main Function and be outputted there. if (compare == 1) { cout << a << " and " << b << " are both equal strings." << endl; } else { cout << a << " and " << b << " are not equal strings." << endl; } }//End of String Comparison Function //String Swap Function void myStrSwap(char* a, char* b) { /*Write a C function to swap the contents of two C strings, using this function prototype: void myStrSwap(char*, char*); Swap each char value in the parameter C strings until the null terminator of the longer string is swapped. Do not use <cstring>'s strlen(), strcmp(), or strcpy() functions in your program -- you are to write your function using loops to process the char arrays. Do not use pointers -- use array syntax instead. Do not use more than one loop in the function.*/ int i = 0; while (true) { if ( i != '\0') { swap(a[i], b[i]); } i++; } }//End of String Swap Function //Uppercase Conversion Function void myStrUpr(char* a) { int i = 0; while(a[i] != '\0') { a[i] = toupper(a[i]); i++; } }//End of Uppercase Conversion Function //Lowercase Conversion Function void myStrLwr(char* a) { int i = 0; while(a[i] != '\0') { a[i] = tolower(a[i]); i++; } }//End of Lowercase Conversion Function
4fb4747ae8d6171ce8c1cf54fdfafcb9213975f2
2c7cc09b17b78deb1491efeb219f9320191cf442
/src/utils/Event.h
b9d20ad53d2f45219c506c2707a02b4b10f6b39f
[ "MIT" ]
permissive
awwit/httpserverapp
221e146ea787ef9e8193e445dc708201d7aee92e
e269cde1d46c5e5c790fbed008c370251f391d4c
refs/heads/master
2022-04-29T16:27:09.815606
2022-03-29T21:13:42
2022-03-29T21:13:42
19,515,460
26
23
null
null
null
null
UTF-8
C++
false
false
635
h
Event.h
#pragma once #include <mutex> #include <condition_variable> #include <atomic> namespace Utils { class Event { private: std::mutex mtx; std::condition_variable cv; std::atomic<bool> signaled; bool manually; public: Event(const bool signaled = false, const bool manualy = false) noexcept; ~Event() noexcept = default; public: void wait(); bool wait_for(const std::chrono::milliseconds &ms); bool wait_until(const std::chrono::high_resolution_clock::time_point &tp); void notify() noexcept; void notify(const size_t threadsCount) noexcept; void reset() noexcept; bool notifed() const noexcept; }; }
3e20e7426012885641a6abfb3438bc9422478445
319cc56c41d4b167ba4b967a0989848837f0784e
/group_project_code/source/main.cpp
590b1c824bc62fa408acdb1cb4255a0532ee2a34
[ "MIT" ]
permissive
architsangal/Modifying-.ply-files
75944c7ddf66aab0cf8815b7ecfbf873c27aebfd
62b83c2df76eeecb1a317aa073c88035ce95577b
refs/heads/main
2023-01-28T17:13:20.380911
2020-12-08T14:14:11
2020-12-08T14:14:11
319,653,463
0
0
null
null
null
null
UTF-8
C++
false
false
5,761
cpp
main.cpp
#include "../include/Task8.h" #include "../include/Ply.h" #include "../include/FileHandler.h" #include "../include/TxtFileHandler.h" #include "../include/IMT2019020_Task_3.h" #include "../include/Task7PPMfile.h" #include <iostream> #include <string> #include <bits/stdc++.h> using namespace std; void showMenu() //Display Menu { cout << "\t\t\t1. Read a .csv file and transpose the data" << endl << "\t\t\t2. Read a .txt file and generate the document statistics (as provided in gedit text editor)" << endl << "\t\t\t3. Read a .ply file and compute the area of each face and sort the faces by area" << endl << "\t\t\t4. Read a .ppm file and convert the image to grayscale" << endl << "\t\t\t5. Read a .csv file and sort the data on the basis of two columns" << endl << "\t\t\t6. Exit " << endl << endl; } bool Run() { string operation; cout << "\t\t\t\e[3m\u001b[33m Please choose the operation that you wish to perform: \e[0m\u001b[0m"; //Input the operation number cin >> operation; if(operation != "1" && operation != "2" && operation != "3" && operation != "4" && operation != "5" && operation != "6") //If the operation is invalid { cout << endl << "\t\t\t\t\t \u001b[31mPLEASE CHOOSE A VALID OPERATION!\u001b[0m" << endl << endl; return true; } else if(operation == "6") //Exit { return false; } else { string filename; cout << "\n\t\t\t\t\t Enter file name: "; //Input file name cin >> filename; if(filename.length() < 5) //If file name is not valid { cout << "\n\u001b[31m\t\t\t\t\t FILE TYPE NOT RECOGNIZED\u001b[0m\n" << endl; return true; } else { if(operation == "5") //Read a .csv file and sort data on the basis of two columns { if(filename.substr(filename.length() - 4).compare(".csv") == 0) { string col1, col2; cout << "\t\t\t\t\t Enter two Column names to sort: "; cin >> col1 >> col2; Task8 file(filename, col1, col2); if(file.fileExists()) { if(file.isColumnValid(col1) && file.isColumnValid(col2)) { file.read(); if(file.isColWithinLimits()) { file.modify(); file.write(); } else { cout << "\u001b[31m\n\t\t\t\t\t\t INVALID COLUMNS\u001b[0m\n" << endl; } } else { cout << "\u001b[31m\n\t\t\t\t\t THE COLUMN NAME IS INCORRECT\u001b[0m\n" << endl; } } else { cout << "\u001b[31m\n\t\t\t\t\t\tUNABLE TO OPEN FILE\u001b[0m\n" << endl; } } else { cout << "\u001b[31m\n\t\t\t\t\t\tNOT A .csv FILE!\u001b[0m\n" << endl; } return true; } else if(operation == "2") //Read a .txt file and generate statistics { if(filename.substr(filename.length() - 4).compare(".txt") == 0) { TxtFileHandler f(filename); f.read(); // Reads the txt file // Modify and write only if input file is valid if(f.isValidFile()) { f.modify(); f.write(); cout << "\n\t\t\u001b[32mNEW FILE \e[3m'Stats_" << filename << "' \u001b[0m\u001b[32mWITH DOCUMENT STATS HAS BEEN ADDED TO \e[3m'files' \u001b[0m\u001b[32mFOLDER\u001b[0m\n" << endl; } } else { cout << "\u001b[31m\n\t\t\t\t\t\tNOT A .txt FILE!\u001b[0m\n" << endl; } return true; } else if(operation == "3") //Read a .ply file and compute and sort area { if(filename.substr(filename.length() - 4).compare(".ply") == 0) { Ply p; p.setFileName(filename); p.read(); if(p.isValidFile()) { p.modify(); p.write(); } } else { cout << "\u001b[31m\n\t\t\t\t\t\tNOT A .ply FILE!\u001b[0m\n" << endl; } return true; } else if(operation == "1") //Read a .csv file and transpose it { if(filename.substr(filename.length() - 4).compare(".csv") == 0) { ifstream infile("../files/" + filename); if(infile.good()) { FileHandler* data = new Task3(filename,filename); data->read(); //read data->modify(); //modify data->write(); //write delete data; } else { cout << "\u001b[31m\n\t\t\t\t\t\tUNABLE TO OPEN FILE\u001b[0m\n" << endl; } } else { cout << "\u001b[31m\n\t\t\t\t\t\tNOT A .csv FILE!\u001b[0m\n" << endl; } return true; } else if(operation == "4") { if(filename.substr(filename.length() - 4).compare(".ppm") == 0) { ifstream infile("../files/" + filename); if(infile.good()) { Task7PPMfile t; ifstream inStream; ofstream outStream; inStream.open("../files/" + filename, ifstream::binary); inStream >> t; inStream.close(); string OutputFileName = "Grey_" + filename.substr(0, filename.length() - 3) + "pgm"; t.grayscale(); outStream.open("../files/" + OutputFileName, ifstream::binary); outStream << t; outStream.close(); cout << "\n\t\t\u001b[32mTHE FILE HAS BEEN CONVERTED TO GREYSCALE AND SAVED AS \e[3m'" << OutputFileName << "'\u001b[0m\u001b[32m IN \e[3m'files'\u001b[0m \u001b[32mFOLDER\u001b[0m\n" << endl; } else { cout << "\u001b[31m\n\t\t\t\t\t\tUNABLE TO OPEN FILE\u001b[0m\n" << endl; } } else { cout << "\u001b[31m\n\t\t\t\t\t\tNOT A .ppm FILE!\u001b[0m\n" << endl; } return true; } } } return true; } int main() { cout << endl << "\t\t\t\t\t\u001b[36m\u001b[1m\u001b[4mWELCOME TO FILE MANAGEMENT SYSTEM\u001b[0m" << endl << endl; showMenu(); while(Run()) { showMenu(); } cout << "\n\e[3m\e[1m\u001b[36m\t\t\t\t\t\t THANK YOU!\e[0m\u001b[0m" << endl << endl; return 0; }
f9fcb400728588a81aae895edd384d3fd265ba1a
bb6f118d3bc1ea938ab5ee13f6c1b9d04d1f5a5c
/sketching/algorithm/elastic_sketch.h
eea05dea64cd941bd19238f48ea347fa9741bffd
[]
no_license
h2bit/PR-Sketch
c0f2b644901703a7f88ee62ed9c22e5949bb3c00
e0f3324474856f1abba448e1ce0a853817102670
refs/heads/master
2023-05-29T12:01:06.557967
2021-06-04T12:26:19
2021-06-04T12:26:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
975
h
elastic_sketch.h
#ifndef ELASTIC_SKETCH_H #define ELASTIC_SKETCH_H #include <stdint.h> #include <vector> #include <set> #include "../tuple/tuple.h" #include "./base_sketch.h" using namespace std; class ElasticSketchHeavyCounter{ public: vector<uint32_t> pvotes; vector<tuple_key_t> tuplekeys; vector<bool> flags; uint32_t nvote; ElasticSketchHeavyCounter(uint32_t len); }; class ElasticSketch: public BaseSketch { public: ElasticSketch(uint32_t filter_space, uint32_t measure_space, uint32_t counter_len, uint32_t height); void update(tuple_key_t cur_key); uint32_t estimate(tuple_key_t cur_key); set<tuple_key_t> get_tuplekeys(); uint32_t get_transmission_pkts(); uint32_t get_transmission_bytes(); private: uint32_t counter_len; uint32_t heavy_bucketnum; uint32_t height; uint32_t width; vector<ElasticSketchHeavyCounter> heavy_counter_vector; vector<uint32_t> light_vector; uint32_t* get_light_count(uint32_t row, uint32_t col); }; #endif
8d7d658221580374e5f13b4e488733a5e9fd4415
f99c0194278639456604ebf76443b65bf1c6ed04
/common/include/common/P2PKHAddress.hpp
9a910d8b2158c4008f9882d95f7393dbda3f8f9c
[]
no_license
RdeWilde/JoyStream
e4ed42ff61af1f348cb49469caa8e30ccf3f8a52
95c2b6fc50251fbe4730b19d47c18bec86e18bf4
refs/heads/master
2021-06-11T20:26:46.682624
2016-05-10T08:27:05
2016-05-10T08:27:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,164
hpp
P2PKHAddress.hpp
/** * Copyright (C) JoyStream - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Bedeho Mender <bedeho.mender@gmail.com>, August 9 2015 */ #ifndef COIN_P2PKH_ADDRESS_HPP #define COIN_P2PKH_ADDRESS_HPP #include <common/PubKeyHash.hpp> namespace Coin { enum class Network; class P2PKHAddress { public: // Default constructor P2PKHAddress(); // Constructor from public keys P2PKHAddress(Network network, const PubKeyHash & pubKeyHash); // Factory from Base58CheckEncoding static P2PKHAddress fromBase58CheckEncoding(const QString & encoded); // Equality operator bool operator==(const P2PKHAddress & o); // Base58CheckEncode QString toBase58CheckEncoding() const; // Getters and setters Network network() const; void setNetwork(Network network); PubKeyHash pubKeyHash() const; void setPubKeyHash(const PubKeyHash & pubKeyHash); private: // Network to which this address corresponds Network _network; // Pub key hash PubKeyHash _pubKeyHash; }; } #endif // COIN_P2PKH_ADDRESS_HPP
f1473597c8e99cee2cd716260921503e10b4ee0d
6d34fa23c708320b2e42d120d107f187106302e3
/orca/gporca/libgpopt/include/gpopt/xforms/CXformUtils.h
fe8cee18a46286bfc8c324ed280e4737b7240169
[ "Apache-2.0" ]
permissive
joe2hpimn/dg16.oss
a38ca233ba5c9f803f9caa99016a4c7560da9f08
2c4275c832b3e4b715b7475726db6757b127030c
refs/heads/master
2021-08-23T19:11:49.831210
2017-12-06T05:23:22
2017-12-06T05:23:22
113,322,478
2
1
null
2017-12-06T13:50:44
2017-12-06T13:50:44
null
UTF-8
C++
false
false
30,682
h
CXformUtils.h
//--------------------------------------------------------------------------- // Greenplum Database // Copyright 2012 EMC Corp. // // @filename: // CXformUtils.h // // @doc: // Utility functions for xforms // // @owner: // // // @test: // // //--------------------------------------------------------------------------- #ifndef GPOPT_CXformUtils_H #define GPOPT_CXformUtils_H #include "gpos/base.h" #include "gpopt/base/CUtils.h" #include "gpopt/base/CColRef.h" #include "gpopt/operators/ops.h" #include "gpopt/xforms/CXform.h" namespace gpopt { using namespace gpos; // forward declarations class CGroupExpression; class CColRefSet; class CExpression; class CLogical; class CLogicalDynamicGet; class CPartConstraint; class CTableDescriptor; // structure describing a candidate for a partial dynamic index scan struct SPartDynamicIndexGetInfo { // md index const IMDIndex *m_pmdindex; // part constraint CPartConstraint *m_ppartcnstr; // index predicate expressions DrgPexpr *m_pdrgpexprIndex; // residual expressions DrgPexpr *m_pdrgpexprResidual; // ctor SPartDynamicIndexGetInfo ( const IMDIndex *pmdindex, CPartConstraint *ppartcnstr, DrgPexpr *pdrgpexprIndex, DrgPexpr *pdrgpexprResidual ) : m_pmdindex(pmdindex), m_ppartcnstr(ppartcnstr), m_pdrgpexprIndex(pdrgpexprIndex), m_pdrgpexprResidual(pdrgpexprResidual) { GPOS_ASSERT(NULL != ppartcnstr); } // dtor ~SPartDynamicIndexGetInfo() { m_ppartcnstr->Release(); CRefCount::SafeRelease(m_pdrgpexprIndex); CRefCount::SafeRelease(m_pdrgpexprResidual); } }; // arrays over partial dynamic index get candidates typedef CDynamicPtrArray<SPartDynamicIndexGetInfo, CleanupDelete> DrgPpartdig; typedef CDynamicPtrArray<DrgPpartdig, CleanupRelease> DrgPdrgPpartdig; // map of expression to array of expressions typedef CHashMap<CExpression, DrgPexpr, CExpression::UlHash, CUtils::FEqual, CleanupRelease<CExpression>, CleanupRelease<DrgPexpr> > HMExprDrgPexpr; // iterator of map of expression to array of expressions typedef CHashMapIter<CExpression, DrgPexpr, CExpression::UlHash, CUtils::FEqual, CleanupRelease<CExpression>, CleanupRelease<DrgPexpr> > HMExprDrgPexprIter; // array of array of expressions typedef CDynamicPtrArray<DrgPexpr, CleanupRelease> DrgPdrgPexpr; //--------------------------------------------------------------------------- // @class: // CXformUtils // // @doc: // Utility functions for xforms // //--------------------------------------------------------------------------- class CXformUtils { private: // enum marking the index column types enum EIndexCols { EicKey, EicIncluded }; typedef CLogical *(*PDynamicIndexOpConstructor) ( IMemoryPool *pmp, const IMDIndex *pmdindex, CTableDescriptor *ptabdesc, ULONG ulOriginOpId, CName *pname, ULONG ulPartIndex, DrgPcr *pdrgpcrOutput, DrgDrgPcr *pdrgpdrgpcrPart, ULONG ulSecondaryPartIndexId, CPartConstraint *ppartcnstr, CPartConstraint *ppartcnstrRel ); typedef CLogical *(*PStaticIndexOpConstructor) ( IMemoryPool *pmp, const IMDIndex *pmdindex, CTableDescriptor *ptabdesc, ULONG ulOriginOpId, CName *pname, DrgPcr *pdrgpcrOutput ); typedef CExpression *(PRewrittenIndexPath) ( IMemoryPool *pmp, CExpression *pexprIndexCond, CExpression *pexprResidualCond, const IMDIndex *pmdindex, CTableDescriptor *ptabdesc, COperator *popLogical ); // private copy ctor CXformUtils(const CXformUtils &); // create a logical assert for the not nullable columns of the given table // on top of the given child expression static CExpression *PexprAssertNotNull ( IMemoryPool *pmp, CExpression *pexprChild, CTableDescriptor *ptabdesc, DrgPcr *pdrgpcr ); // create a logical assert for the check constraints on the given table static CExpression *PexprAssertCheckConstraints ( IMemoryPool *pmp, CExpression *pexprChild, CTableDescriptor *ptabdesc, DrgPcr *pdrgpcr ); // add a min(col) project element to the given expression list for // each column in the given column array static void AddMinAggs ( IMemoryPool *pmp, CMDAccessor *pmda, CColumnFactory *pcf, DrgPcr *pdrgpcr, HMCrCr *phmcrcr, DrgPexpr *pdrgpexpr, DrgPcr **ppdrgpcrNew ); // check if all columns support MIN aggregate static BOOL FSupportsMinAgg(DrgPcr *pdrgpcr); // helper for extracting foreign key static CColRefSet *PcrsFKey ( IMemoryPool *pmp, DrgPexpr *pdrgpexpr, CColRefSet *prcsOutput, CColRefSet *pcrsKey ); // return the set of columns from the given array of columns which appear // in the index included / key columns static CColRefSet *PcrsIndexColumns ( IMemoryPool *pmp, DrgPcr *pdrgpcr, const IMDIndex *pmdindex, const IMDRelation *pmdrel, EIndexCols eic ); // return the ordered array of columns from the given array of columns which appear // in the index included / key columns static DrgPcr *PdrgpcrIndexColumns ( IMemoryPool *pmp, DrgPcr *pdrgpcr, const IMDIndex *pmdindex, const IMDRelation *pmdrel, EIndexCols eic ); // lookup hash join keys in scalar child group static void LookupHashJoinKeys(IMemoryPool *pmp, CExpression *pexpr, DrgPexpr **ppdrgpexprOuter, DrgPexpr **ppdrgpexprInner); // cache hash join keys on scalar child group static void CacheHashJoinKeys(CExpression *pexpr, DrgPexpr *pdrgpexprOuter, DrgPexpr *pdrgpexprInner); // helper to extract equality from a given expression static BOOL FExtractEquality ( CExpression *pexpr, CExpression **ppexprEquality, // output: extracted equality expression, set to NULL if extraction failed CExpression **ppexprOther // output: sibling of equality expression, set to NULL if extraction failed ); // check if given xform id is in the given array of xforms static BOOL FXformInArray(CXform::EXformId exfid, CXform::EXformId rgXforms[], ULONG ulXforms); #ifdef GPOS_DEBUG // check whether the given join type is swapable static BOOL FSwapableJoinType(COperator::EOperatorId eopid); #endif // GPOS_DEBUG // helper function for adding hash join alternative template <class T> static void AddHashJoinAlternative ( IMemoryPool *pmp, CExpression *pexprJoin, DrgPexpr *pdrgpexprOuter, DrgPexpr *pdrgpexprInner, CXformResult *pxfres ); // helper for transforming SubqueryAll into aggregate subquery static void SubqueryAllToAgg ( IMemoryPool *pmp, CExpression *pexprSubquery, CExpression **ppexprNewSubquery, // output argument for new scalar subquery CExpression **ppexprNewScalar // output argument for new scalar expression ); // helper for transforming SubqueryAny into aggregate subquery static void SubqueryAnyToAgg ( IMemoryPool *pmp, CExpression *pexprSubquery, CExpression **ppexprNewSubquery, // output argument for new scalar subquery CExpression **ppexprNewScalar // output argument for new scalar expression ); // create the Gb operator to be pushed below a join static CLogicalGbAgg *PopGbAggPushableBelowJoin ( IMemoryPool *pmp, CLogicalGbAgg *popGbAggOld, CColRefSet *prcsOutput, CColRefSet *pcrsGrpCols ); // check if the preconditions for pushing down Group by through join are satisfied static BOOL FCanPushGbAggBelowJoin ( CColRefSet *pcrsGrpCols, CColRefSet *pcrsJoinOuterChildOutput, CColRefSet *pcrsJoinScalarUsedFromOuter, CColRefSet *pcrsGrpByOutput, CColRefSet *pcrsGrpByUsed, CColRefSet *pcrsFKey ); // construct an expression representing a new access path using the given functors for // operator constructors and rewritten access path static CExpression *PexprBuildIndexPlan ( IMemoryPool *pmp, CMDAccessor *pmda, CExpression *pexprGet, ULONG ulOriginOpId, DrgPexpr *pdrgpexprConds, CColRefSet *pcrsReqd, CColRefSet *pcrsScalarExpr, CColRefSet *pcrsOuterRefs, const IMDIndex *pmdindex, const IMDRelation *pmdrel, BOOL fAllowPartialIndex, CPartConstraint *ppcForPartialIndexes, IMDIndex::EmdindexType emdindtype, PDynamicIndexOpConstructor pdiopc, PStaticIndexOpConstructor psiopc, PRewrittenIndexPath prip ); // create a dynamic operator for a btree index plan static CLogical * PopDynamicBtreeIndexOpConstructor ( IMemoryPool *pmp, const IMDIndex *pmdindex, CTableDescriptor *ptabdesc, ULONG ulOriginOpId, CName *pname, ULONG ulPartIndex, DrgPcr *pdrgpcrOutput, DrgDrgPcr *pdrgpdrgpcrPart, ULONG ulSecondaryPartIndexId, CPartConstraint *ppartcnstr, CPartConstraint *ppartcnstrRel ) { return GPOS_NEW(pmp) CLogicalDynamicIndexGet ( pmp, pmdindex, ptabdesc, ulOriginOpId, pname, ulPartIndex, pdrgpcrOutput, pdrgpdrgpcrPart, ulSecondaryPartIndexId, ppartcnstr, ppartcnstrRel ); } // create a static operator for a btree index plan static CLogical * PopStaticBtreeIndexOpConstructor ( IMemoryPool *pmp, const IMDIndex *pmdindex, CTableDescriptor *ptabdesc, ULONG ulOriginOpId, CName *pname, DrgPcr *pdrgpcrOutput ) { return GPOS_NEW(pmp) CLogicalIndexGet ( pmp, pmdindex, ptabdesc, ulOriginOpId, pname, pdrgpcrOutput ); } // produce an expression representing a new btree index path static CExpression * PexprRewrittenBtreeIndexPath ( IMemoryPool *pmp, CExpression *pexprIndexCond, CExpression *pexprResidualCond, const IMDIndex *, // pmdindex CTableDescriptor *, // ptabdesc COperator *popLogical ) { // create the expression containing the logical index get operator return CUtils::PexprSafeSelect(pmp, GPOS_NEW(pmp) CExpression(pmp, popLogical, pexprIndexCond), pexprResidualCond); } // create a candidate dynamic get scan to suplement the partial index scans static SPartDynamicIndexGetInfo *PpartdigDynamicGet ( IMemoryPool *pmp, DrgPexpr *pdrgpexprScalar, CPartConstraint *ppartcnstrCovered, CPartConstraint *ppartcnstrRel ); // returns true iff the given expression is a Not operator whose child is a // scalar identifier static BOOL FNotIdent(CExpression *pexpr); // creates a condition of the form col = fVal, where col is the given column static CExpression *PexprEqualityOnBoolColumn ( IMemoryPool *pmp, CMDAccessor *pmda, BOOL fNegated, CColRef *pcr ); // construct a bitmap index path expression for the given predicate // out of the children of the given expression static CExpression *PexprBitmapFromChildren ( IMemoryPool *pmp, CMDAccessor *pmda, CExpression *pexprOriginalPred, CExpression *pexprPred, CTableDescriptor *ptabdesc, const IMDRelation *pmdrel, DrgPcr *pdrgpcrOutput, CColRefSet *pcrsOuterRefs, CColRefSet *pcrsReqd, BOOL fConjunction, CExpression **ppexprRecheck, CExpression **ppexprResidual ); // returns the recheck condition to use in a bitmap // index scan computed out of the expression 'pexprPred' that // uses the bitmap index // fBoolColumn (and fNegatedColumn) say whether the predicate is a // (negated) boolean scalar identifier // caller takes ownership of the returned expression static CExpression *PexprBitmapCondToUse ( IMemoryPool *pmp, CMDAccessor *pmda, CExpression *pexprPred, BOOL fBoolColumn, BOOL fNegatedBoolColumn, CColRefSet *pcrsScalar ); // compute the residual predicate for a bitmap table scan static void ComputeBitmapTableScanResidualPredicate ( IMemoryPool *pmp, BOOL fConjunction, CExpression *pexprOriginalPred, CExpression **ppexprResidual, DrgPexpr *pdrgpexprResidualNew ); // compute a disjunction of two part constraints static CPartConstraint *PpartcnstrDisjunction ( IMemoryPool *pmp, CPartConstraint *ppartcnstrOld, CPartConstraint *ppartcnstrNew ); // construct a bitmap index path expression for the given predicate coming // from a condition without outer references static CExpression *PexprBitmapForSelectCondition ( IMemoryPool *pmp, CMDAccessor *pmda, CExpression *pexprPred, CTableDescriptor *ptabdesc, const IMDRelation *pmdrel, DrgPcr *pdrgpcrOutput, CColRefSet *pcrsReqd, CExpression **ppexprRecheck, BOOL fBoolColumn, BOOL fNegatedBoolColumn ); // construct a bitmap index path expression for the given predicate coming // from a condition with outer references that could potentially become // an index lookup static CExpression *PexprBitmapForIndexLookup ( IMemoryPool *pmp, CMDAccessor *pmda, CExpression *pexprPred, CTableDescriptor *ptabdesc, const IMDRelation *pmdrel, DrgPcr *pdrgpcrOutput, CColRefSet *pcrsOuterRefs, CColRefSet *pcrsReqd, CExpression **ppexprRecheck ); // if there is already an index probe in pdrgpexprBitmap on the same // index as the given pexprBitmap, modify the existing index probe and // the corresponding recheck conditions to subsume pexprBitmap and // pexprRecheck respectively static BOOL FMergeWithPreviousBitmapIndexProbe ( IMemoryPool *pmp, CExpression *pexprBitmap, CExpression *pexprRecheck, DrgPexpr *pdrgpexprBitmap, DrgPexpr *pdrgpexprRecheck ); // iterate over given hash map and return array of arrays of project elements sorted by the column id of the first entries static DrgPdrgPexpr *PdrgpdrgpexprSortedPrjElemsArray(IMemoryPool *pmp, HMExprDrgPexpr *phmexprdrgpexpr); // comparator used in sorting arrays of project elements based on the column id of the first entry static INT ICmpPrjElemsArr(const void *pvFst, const void *pvSnd); public: // helper function for implementation xforms on binary operators // with predicates (e.g. joins) template<class T> static void TransformImplementBinaryOp ( CXformContext *pxfctxt, CXformResult *pxfres, CExpression *pexpr ); // helper function for implementation of hash joins template <class T> static void ImplementHashJoin ( CXformContext *pxfctxt, CXformResult *pxfres, CExpression *pexpr, BOOL fAntiSemiJoin = false ); // helper function for implementation of nested loops joins template <class T> static void ImplementNLJoin ( CXformContext *pxfctxt, CXformResult *pxfres, CExpression *pexpr ); // helper for removing IsNotFalse join predicate for GPDB anti-semi hash join static BOOL FProcessGPDBAntiSemiHashJoin(IMemoryPool *pmp, CExpression *pexpr, CExpression **ppexprResult); // check the applicability of logical join to physical join xform static CXform::EXformPromise ExfpLogicalJoin2PhysicalJoin(CExpressionHandle &exprhdl); // check the applicability of semi join to cross product static CXform::EXformPromise ExfpSemiJoin2CrossProduct(CExpressionHandle &exprhdl); // check the applicability of N-ary join expansion static CXform::EXformPromise ExfpExpandJoinOrder(CExpressionHandle &exprhdl); // extract foreign key static CColRefSet *PcrsFKey ( IMemoryPool *pmp, CExpression *pexprOuter, CExpression *pexprInner, CExpression *pexprScalar ); // compute a swap of the two given joins static CExpression *PexprSwapJoins ( IMemoryPool *pmp, CExpression *pexprTopJoin, CExpression *pexprBottomJoin ); // push a Gb, optionally with a having clause below the child join static CExpression *PexprPushGbBelowJoin ( IMemoryPool *pmp, CExpression *pexpr ); // check if the the array of aligned input columns are of the same type static BOOL FSameDatatype(DrgDrgPcr *pdrgpdrgpcrInput); // helper function to separate subquery predicates in a top Select node static CExpression *PexprSeparateSubqueryPreds(IMemoryPool *pmp, CExpression *pexpr); // helper for creating inverse predicate for unnesting subquery ALL static CExpression *PexprInversePred(IMemoryPool *pmp, CExpression *pexprSubquery); // helper for creating a null indicator expression static CExpression *PexprNullIndicator(IMemoryPool *pmp, CExpression *pexpr); // helper for creating a logical DML on top of a project static CExpression *PexprLogicalDMLOverProject ( IMemoryPool *pmp, CExpression *pexprChild, CLogicalDML::EDMLOperator edmlop, CTableDescriptor *ptabdesc, DrgPcr *pdrgpcr, CColRef *pcrCtid, CColRef *pcrSegmentId ); // check whether there are any BEFORE or AFTER triggers on the // given table that match the given DML operation static BOOL FTriggersExist ( CLogicalDML::EDMLOperator edmlop, CTableDescriptor *ptabdesc, BOOL fBefore ); // does the given trigger type match the given logical DML type static BOOL FTriggerApplies ( CLogicalDML::EDMLOperator edmlop, const IMDTrigger *pmdtrigger ); // construct a trigger expression on top of the given expression static CExpression *PexprRowTrigger ( IMemoryPool *pmp, CExpression *pexprChild, CLogicalDML::EDMLOperator edmlop, IMDId *pmdidRel, BOOL fBefore, DrgPcr *pdrgpcr ); // construct a trigger expression on top of the given expression static CExpression *PexprRowTrigger ( IMemoryPool *pmp, CExpression *pexprChild, CLogicalDML::EDMLOperator edmlop, IMDId *pmdidRel, BOOL fBefore, DrgPcr *pdrgpcrOld, DrgPcr *pdrgpcrNew ); // construct a logical partition selector for the given table descriptor on top // of the given child expression. The partition selection filters use columns // from the given column array static CExpression *PexprLogicalPartitionSelector ( IMemoryPool *pmp, CTableDescriptor *ptabdesc, DrgPcr *pdrgpcr, CExpression *pexprChild ); // return partition filter expressions given a table // descriptor and the given column references static DrgPexpr *PdrgpexprPartEqFilters(IMemoryPool *pmp, CTableDescriptor *ptabdesc, DrgPcr *pdrgpcrSource); // helper for creating Agg expression equivalent to quantified subquery static void QuantifiedToAgg ( IMemoryPool *pmp, CExpression *pexprSubquery, CExpression **ppexprNewSubquery, CExpression **ppexprNewScalar ); // helper for creating Agg expression equivalent to existential subquery static void ExistentialToAgg ( IMemoryPool *pmp, CExpression *pexprSubquery, CExpression **ppexprNewSubquery, CExpression **ppexprNewScalar ); // create a logical assert for the check constraints on the given table static CExpression *PexprAssertConstraints ( IMemoryPool *pmp, CExpression *pexprChild, CTableDescriptor *ptabdesc, DrgPcr *pdrgpcr ); // create a logical assert for checking cardinality of update values static CExpression *PexprAssertUpdateCardinality ( IMemoryPool *pmp, CExpression *pexprDMLChild, CExpression *pexprDML, CColRef *pcrCtid, CColRef *pcrSegmentId ); // return true if stats derivation is needed for this xform static BOOL FDeriveStatsBeforeXform(CXform *pxform); // return true if xform is a subquery decorrelation xform static BOOL FSubqueryDecorrelation(CXform *pxform); // return true if xform is a subquery unnesting xform static BOOL FSubqueryUnnesting(CXform *pxform); // return true if xform should be applied to the next binding static BOOL FApplyToNextBinding(CXform *pxform, CExpression *pexprLastBinding); // return true if xform should be applied only once static BOOL FApplyOnce(CXform::EXformId exfid); // return a formatted error message for the given exception static CWStringConst *PstrErrorMessage(IMemoryPool *pmp, ULONG ulMajor, ULONG ulMinor, ...); // return the array of key columns from the given array of columns which appear // in the index key columns static DrgPcr *PdrgpcrIndexKeys ( IMemoryPool *pmp, DrgPcr *pdrgpcr, const IMDIndex *pmdindex, const IMDRelation *pmdrel ); // return the set of key columns from the given array of columns which appear // in the index key columns static CColRefSet *PcrsIndexKeys ( IMemoryPool *pmp, DrgPcr *pdrgpcr, const IMDIndex *pmdindex, const IMDRelation *pmdrel ); // return the set of key columns from the given array of columns which appear // in the index included columns static CColRefSet *PcrsIndexIncludedCols ( IMemoryPool *pmp, DrgPcr *pdrgpcr, const IMDIndex *pmdindex, const IMDRelation *pmdrel ); // check if an index is applicable given the required, output and scalar // expression columns static BOOL FIndexApplicable ( IMemoryPool *pmp, const IMDIndex *pmdindex, const IMDRelation *pmdrel, DrgPcr *pdrgpcrOutput, CColRefSet *pcrsReqd, CColRefSet *pcrsScalar, IMDIndex::EmdindexType emdindtype ); // check whether a CTE should be inlined static BOOL FInlinableCTE(ULONG ulCTEId); // return the column reference of the n-th project element static CColRef *PcrProjectElement(CExpression *pexpr, ULONG ulIdxProjElement); // create an expression with "row_number" window function static CExpression *PexprRowNumber(IMemoryPool *pmp); // create a logical sequence project with a "row_number" window function static CExpression *PexprWindowWithRowNumber ( IMemoryPool *pmp, CExpression *pexprWindowChild, DrgPcr *pdrgpcrInput ); // generate a logical Assert expression that errors out when more than one row is generated static CExpression *PexprAssertOneRow ( IMemoryPool *pmp, CExpression *pexprChild ); // helper for adding CTE producer to global CTE info structure static CExpression *PexprAddCTEProducer ( IMemoryPool *pmp, ULONG ulCTEId, DrgPcr *pdrgpcr, CExpression *pexpr ); // does transformation generate an Apply expression static BOOL FGenerateApply ( CXform::EXformId exfid ) { return CXform::ExfSelect2Apply == exfid || CXform::ExfProject2Apply == exfid || CXform::ExfGbAgg2Apply == exfid || CXform::ExfSubqJoin2Apply == exfid || CXform::ExfSubqNAryJoin2Apply == exfid || CXform::ExfSequenceProject2Apply == exfid; } // helper for creating IndexGet/DynamicIndexGet expression static CExpression *PexprLogicalIndexGet ( IMemoryPool *pmp, CMDAccessor *pmda, CExpression *pexprGet, ULONG ulOriginOpId, DrgPexpr *pdrgpexprConds, CColRefSet *pcrsReqd, CColRefSet *pcrsScalarExpr, CColRefSet *pcrsOuterRefs, const IMDIndex *pmdindex, const IMDRelation *pmdrel, BOOL fAllowPartialIndex, CPartConstraint *ppcartcnstrIndex ) { return PexprBuildIndexPlan ( pmp, pmda, pexprGet, ulOriginOpId, pdrgpexprConds, pcrsReqd, pcrsScalarExpr, pcrsOuterRefs, pmdindex, pmdrel, fAllowPartialIndex, ppcartcnstrIndex, IMDIndex::EmdindBtree, PopDynamicBtreeIndexOpConstructor, PopStaticBtreeIndexOpConstructor, PexprRewrittenBtreeIndexPath ); } // helper for creating bitmap bool op expressions static CExpression *PexprScalarBitmapBoolOp ( IMemoryPool *pmp, CMDAccessor *pmda, CExpression *pexprOriginalPred, DrgPexpr *pdrgpexpr, CTableDescriptor *ptabdesc, const IMDRelation *pmdrel, DrgPcr *pdrgpcrOutput, CColRefSet *pcrsOuterRefs, CColRefSet *pcrsReqd, BOOL fConjunction, CExpression **ppexprRecheck, CExpression **ppexprResidual ); // construct a bitmap bool op given the left and right bitmap access // path expressions static CExpression *PexprBitmapBoolOp ( IMemoryPool *pmp, IMDId *pmdidBitmapType, CExpression *pexprLeft, CExpression *pexprRight, BOOL fConjunction ); // construct a bitmap index path expression for the given predicate static CExpression *PexprBitmap ( IMemoryPool *pmp, CMDAccessor *pmda, CExpression *pexprOriginalPred, CExpression *pexprPred, CTableDescriptor *ptabdesc, const IMDRelation *pmdrel, DrgPcr *pdrgpcrOutput, CColRefSet *pcrsOuterRefs, CColRefSet *pcrsReqd, BOOL fConjunction, CExpression **ppexprRecheck, CExpression **ppexprResidual ); // given an array of predicate expressions, construct a bitmap access path // expression for each predicate and accumulate it in the pdrgpexprBitmap array static void CreateBitmapIndexProbeOps ( IMemoryPool *pmp, CMDAccessor *pmda, CExpression *pexprOriginalPred, DrgPexpr *pdrgpexpr, CTableDescriptor *ptabdesc, const IMDRelation *pmdrel, DrgPcr *pdrgpcrOutput, CColRefSet *pcrsOuterRefs, CColRefSet *pcrsReqd, BOOL fConjunction, DrgPexpr *pdrgpexprBitmap, DrgPexpr *pdrgpexprRecheck, DrgPexpr *pdrgpexprResidual ); // check if expression has any scalar node with ambiguous return type static BOOL FHasAmbiguousType(CExpression *pexpr, CMDAccessor *pmda); // construct a Bitmap(Dynamic)TableGet over BitmapBoolOp for the given // logical operator if bitmap indexes exist static CExpression *PexprBitmapTableGet ( IMemoryPool *pmp, CLogical *popGet, ULONG ulOriginOpId, CTableDescriptor *ptabdesc, CExpression *pexprScalar, CColRefSet *pcrsOuterRefs, CColRefSet *pcrsReqd ); // transform a Select over a (dynamic) table get into a bitmap table scan // over bitmap bool op static CExpression *PexprSelect2BitmapBoolOp ( IMemoryPool *pmp, CExpression *pexpr ); // find a set of partial index combinations static DrgPdrgPpartdig *PdrgpdrgppartdigCandidates ( IMemoryPool *pmp, CMDAccessor *pmda, DrgPexpr *pdrgpexprScalar, DrgDrgPcr *pdrgpdrgpcrPartKey, const IMDRelation *pmdrel, CPartConstraint *ppartcnstrRel, DrgPcr *pdrgpcrOutput, CColRefSet *pcrsReqd, CColRefSet *pcrsScalarExpr, CColRefSet *pcrsAcceptedOuterRefs // set of columns to be considered for index apply ); // compute the newly covered part constraint based on the old covered part // constraint and the given part constraint static CPartConstraint *PpartcnstrUpdateCovered ( IMemoryPool *pmp, CMDAccessor *pmda, DrgPexpr *pdrgpexprScalar, CPartConstraint *ppartcnstrCovered, CPartConstraint *ppartcnstr, DrgPcr *pdrgpcrOutput, DrgPexpr *pdrgpexprIndex, DrgPexpr *pdrgpexprResidual, const IMDRelation *pmdrel, const IMDIndex *pmdindex, CColRefSet *pcrsAcceptedOuterRefs ); // remap the expression from the old columns to the new ones static CExpression *PexprRemapColumns ( IMemoryPool *pmp, CExpression *pexprScalar, DrgPcr *pdrgpcrA, DrgPcr *pdrgpcrRemappedA, DrgPcr *pdrgpcrB, DrgPcr *pdrgpcrRemappedB ); // construct a partial dynamic index get static CExpression *PexprPartialDynamicIndexGet ( IMemoryPool *pmp, CLogicalDynamicGet *popGet, ULONG ulOriginOpId, DrgPexpr *pdrgpexprIndex, DrgPexpr *pdrgpexprResidual, DrgPcr *pdrgpcrDIG, const IMDIndex *pmdindex, const IMDRelation *pmdrel, CPartConstraint *ppartcnstr, CColRefSet *pcrsAcceptedOuterRefs, // set of columns to be considered for index apply DrgPcr *pdrgpcrOuter, DrgPcr *pdrgpcrNewOuter ); // create a new CTE consumer for the given CTE id static CExpression *PexprCTEConsumer(IMemoryPool *pmp, ULONG ulCTEId, DrgPcr *pdrgpcrConsumer); // return a new array containing the columns from the given column array 'pdrgpcr' // at the positions indicated by the given ULONG array 'pdrgpulIndexesOfRefs' // e.g., pdrgpcr = {col1, col2, col3}, pdrgpulIndexesOfRefs = {2, 1} // the result will be {col3, col2} static DrgPcr *PdrgpcrReorderedSubsequence ( IMemoryPool *pmp, DrgPcr *pdrgpcr, DrgPul *pdrgpulIndexesOfRefs ); // check if given xform is an Agg splitting xform static BOOL FSplitAggXform(CXform::EXformId exfid); // check if given expression is a multi-stage Agg based on origin xform static BOOL FMultiStageAgg(CExpression *pexprAgg); // check if expression handle is attached to a Join with a predicate that uses columns from only one child static BOOL FJoinPredOnSingleChild(IMemoryPool *pmp, CExpressionHandle &exprhdl); // add a redundant SELECT node on top of Dynamic (Bitmap) IndexGet to be able to use index // predicate in partition elimination static CExpression *PexprRedundantSelectForDynamicIndex(IMemoryPool *pmp, CExpression *pexpr); // if there is predicate that can be used for hash join then convert the // expression to CNF, else return the original expression static CExpression *Pexpr2CNFWhenBeneficial(IMemoryPool *pmp, CExpression *pexprOuter, CExpression *pexprInner, CExpression *pexprScalar); // convert an Agg window function into regular Agg static CExpression *PexprWinFuncAgg2ScalarAgg(IMemoryPool *pmp, CExpression *pexprWinFunc); // create a map from the argument of each Distinct Agg to the array of project elements that define Distinct Aggs on the same argument static void MapPrjElemsWithDistinctAggs(IMemoryPool *pmp, CExpression *pexprPrjList, HMExprDrgPexpr **pphmexprdrgpexpr, ULONG *pulDifferentDQAs); // convert GbAgg with distinct aggregates to a join static CExpression *PexprGbAggOnCTEConsumer2Join(IMemoryPool *pmp, CExpression *pexprGbAgg); }; // class CXformUtils } #include "CXformUtils.inl" #endif // !GPOPT_CXformUtils_H // EOF
4e545ac3986e7fda0954d41b49579a5237eba44f
1a218c67ad04f99e52c37425fdb933b053af6244
/Ch03/exercise3.43.cc
ab2f87e3912e0a20f5d79b7882f49de32dbd15c8
[]
no_license
xiaonengmiao/Cpp_Primer
5a91cd223c9b0870f4ab9a45c6f679333a98fa20
be20a29b49be19f6959b7873077ea698da940bf6
refs/heads/master
2020-12-25T14:23:58.976008
2020-06-18T07:54:43
2020-06-18T07:54:43
66,343,361
1
1
null
null
null
null
UTF-8
C++
false
false
556
cc
exercise3.43.cc
#include <iostream> #include <vector> using namespace::std; int main() { constexpr size_t rowCnt = 3, colCnt = 4; int ia[rowCnt][colCnt]={0}; // using a range for for (auto &row : ia) for (auto &col : row) cout << col << " "; cout << endl; // using pointers for (auto q=ia; q!=ia+rowCnt; ++q) for (auto p=*q; p!=*q+colCnt; ++p) cout << *p << " "; cout << endl; // using subscripts for (size_t i=0; i!=rowCnt; ++i) for (size_t j=0; j!=colCnt; ++j) cout << ia[i][j] << " "; cout << endl; return 0; }
3c40a459a0cc86e80bd3cc7d468b174cfa3a10ed
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/Editor/CurveTableEditor/Private/CurveTableEditor.h
5d1ed7ab642621edb38ff9559f0c7a7887ec65de
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
5,909
h
CurveTableEditor.h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Types/SlateStructs.h" #include "Layout/Visibility.h" #include "Widgets/SWidget.h" #include "Toolkits/IToolkitHost.h" #include "ICurveTableEditor.h" #include "Widgets/Views/STableViewBase.h" #include "Widgets/Views/STableRow.h" #include "CurveTableEditorHandle.h" struct FCurveTableEditorColumnHeaderData { /** Unique ID used to identify this column */ FName ColumnId; /** Display name of this column */ FText DisplayName; /** The calculated width of this column taking into account the cell data for each row */ float DesiredColumnWidth; }; struct FCurveTableEditorRowListViewData { /** Unique ID used to identify this row */ FName RowId; /** Display name of this row */ FText DisplayName; /** Array corresponding to each cell in this row */ TArray<FText> CellData; /** Handle to the row */ FCurveTableEditorHandle RowHandle; }; /** The manner in which curve tables are displayed */ enum class ECurveTableViewMode : int32 { /** Displays values in a spreadsheet-like table */ Grid, /** Displays values as curves */ CurveTable, }; typedef TSharedPtr<FCurveTableEditorColumnHeaderData> FCurveTableEditorColumnHeaderDataPtr; typedef TSharedPtr<FCurveTableEditorRowListViewData> FCurveTableEditorRowListViewDataPtr; /** Viewer/editor for a CurveTable */ class FCurveTableEditor : public ICurveTableEditor { friend class SCurveTableListViewRow; friend class SCurveTableCurveViewRow; public: virtual void RegisterTabSpawners(const TSharedRef<class FTabManager>& TabManager) override; virtual void UnregisterTabSpawners(const TSharedRef<class FTabManager>& TabManager) override; /** * Edits the specified table * * @param Mode Asset editing mode for this editor (standalone or world-centric) * @param InitToolkitHost When Mode is WorldCentric, this is the level editor instance to spawn this editor within * @param Table The table to edit */ void InitCurveTableEditor( const EToolkitMode::Type Mode, const TSharedPtr< class IToolkitHost >& InitToolkitHost, UCurveTable* Table ); /** Destructor */ virtual ~FCurveTableEditor(); /** IToolkit interface */ virtual FName GetToolkitFName() const override; virtual FText GetBaseToolkitName() const override; virtual FString GetWorldCentricTabPrefix() const override; virtual FLinearColor GetWorldCentricTabColorScale() const override; /** Get the curve table being edited */ const UCurveTable* GetCurveTable() const; /** Spawns the tab with the curve table inside */ TSharedRef<SDockTab> SpawnTab_CurveTable( const FSpawnTabArgs& Args ); /** Get the mode that we are displaying data in */ ECurveTableViewMode GetViewMode() const { return ViewMode; } private: /** Add extra menu items */ void ExtendMenu(); /** Bind commands to delegates */ void BindCommands(); /** Update the cached state of this curve table, and then reflect that new state in the UI */ void RefreshCachedCurveTable(); /** Cache the data from the current curve table so that it can be shown in the editor */ void CacheDataTableForEditing(); /** Make the widget for a row name entry in the data table row list view */ TSharedRef<ITableRow> MakeRowNameWidget(FCurveTableEditorRowListViewDataPtr InRowDataPtr, const TSharedRef<STableViewBase>& OwnerTable); /** Make the widget for a row entry in the data table row list view */ TSharedRef<ITableRow> MakeRowWidget(FCurveTableEditorRowListViewDataPtr InRowDataPtr, const TSharedRef<STableViewBase>& OwnerTable); /** Make the widget for a cell entry in the data table row list view */ TSharedRef<SWidget> MakeCellWidget(FCurveTableEditorRowListViewDataPtr InRowDataPtr, const int32 InRowIndex, const FName& InColumnId); /** Make the curve widget for a row entry in the data table row list view */ TSharedRef<SWidget> MakeCurveWidget(FCurveTableEditorRowListViewDataPtr InRowDataPtr, const int32 InRowIndex); /** Called when the row names list is scrolled - used to keep the two list views in sync */ void OnRowNamesListViewScrolled(double InScrollOffset); /** Called when the cell names list view is scrolled - used to keep the two list views in sync */ void OnCellsListViewScrolled(double InScrollOffset); /** Get the width to use for the row names column */ FOptionalSize GetRowNameColumnWidth() const; /** Called when an asset has finished being imported */ void OnPostReimport(UObject* InObject, bool); /** Control control visibility based on view mode */ EVisibility GetGridViewControlsVisibility() const; /** Control control visibility based on view mode */ EVisibility GetCurveViewControlsVisibility() const; /** Toggle between curve & grid view */ void ToggleViewMode(); /** Get whether the curve view checkbox should be toggled on */ bool IsCurveViewChecked() const; /** Array of the columns that are available for editing */ TArray<FCurveTableEditorColumnHeaderDataPtr> AvailableColumns; /** Array of the rows that are available for editing */ TArray<FCurveTableEditorRowListViewDataPtr> AvailableRows; /** Header row containing entries for each column in AvailableColumns */ TSharedPtr<SHeaderRow> ColumnNamesHeaderRow; /** List view responsible for showing the row names column */ TSharedPtr<SListView<FCurveTableEditorRowListViewDataPtr>> RowNamesListView; /** List view responsible for showing the rows from AvailableColumns */ TSharedPtr<SListView<FCurveTableEditorRowListViewDataPtr>> CellsListView; /** Menu extender */ TSharedPtr<FExtender> MenuExtender; /** Width of the row name column */ float RowNameColumnWidth; /** The tab id for the curve table tab */ static const FName CurveTableTabId; /** The column id for the row name list view column */ static const FName RowNameColumnId; /** The manner in which curve tables are displayed */ ECurveTableViewMode ViewMode; };
1b1ab5fee750a5c63be4896a4ffccc85cddb6f28
5975ff5a30a059e34cbde93f57a58d8170d90d31
/src/Plane.cpp
8f2c91794144fd7a188d6fbc357144ac240c5b6e
[]
no_license
spaske00/RG113-virus-defender
565a4a7a593e4a255333e728df1de94f284af169
74e1f88477f82ac3ceead22036c1c077a2ef8dd0
refs/heads/master
2020-12-26T22:17:54.712493
2019-04-04T22:06:45
2019-04-04T22:06:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
746
cpp
Plane.cpp
#include "Plane.hpp" #include <cmath> namespace vd { Plane::Plane() { m_material.set_ambient(0.3, 0.3, 0.2, 1); m_material.set_diffuse(0.4, 0.4, 0.8, 1); m_material.set_specular(0.1, 0.1, 0.3, 1); m_material.set_shininess(10); m_material.set_side(GL_FRONT); glShadeModel(GL_FLAT); } void Plane::init() { m_draw_list = glGenLists(1); glNewList(m_draw_list, GL_COMPILE); m_material.draw(); for (float y = 0; y < 50; y += 0.5) { glBegin(GL_TRIANGLE_STRIP); for (float x = 0; x < 50; x += 0.5) { glNormal3f(0, 0, 1); glVertex3f(x, y, 0); glNormal3f(0, 0, 1); glVertex3f(x, y + 0.5, 0); } glEnd(); } glEndList(); } void Plane::draw() { glCallList(m_draw_list); } }; // namespace vd
7fcd72dccbd89fad6d07e2bcdd44b8fd7eaf9f56
beaeefee8412d35e8afee2643098dbc3870d47bc
/src/EAWebkit/Webkit-owb/BAL/OWBAL/Concretizations/Memory/WK/BCArenaWK.cpp
4bcba4a3c1bb59994f8cc35545ff3458a2cd6ae6
[]
no_license
weimingtom/duibrowser
831d13626c8560b2b4c270dcc8d2bde746fe8dba
74f4b51f741978f5a9d3b3509e6267fd261e9d3f
refs/heads/master
2021-01-10T01:36:36.573836
2012-05-11T16:38:17
2012-05-11T16:38:17
43,038,328
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
9,045
cpp
BCArenaWK.cpp
/* * Copyright (C) 1998-2000 Netscape Communications Corporation. * Copyright (C) 2003-6 Apple Computer * * Other contributors: * Nick Blievers <nickb@adacel.com.au> * Jeff Hostetler <jeff@nerdone.com> * Tom Rini <trini@kernel.crashing.org> * Raffaele Sena <raff@netwinder.org> * * 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 * * Alternatively, the contents of this file may be used under the terms * of either the Mozilla Public License Version 1.1, found at * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html * (the "GPL"), in which case the provisions of the MPL or the GPL are * applicable instead of those above. If you wish to allow use of your * version of this file only under the terms of one of those two * licenses (the MPL or the GPL) and not to allow others to use your * version of this file under the LGPL, indicate your decision by * deletingthe provisions above and replace them with the notice and * other provisions required by the MPL or the GPL, as the case may be. * If you do not delete the provisions above, a recipient may use your * version of this file under any of the LGPL, the MPL or the GPL. */ /* * Lifetime-based fast allocation, inspired by much prior art, including * "Fast Allocation and Deallocation of Memory Based on Object Lifetimes" * David R. Hanson, Software -- Practice and Experience, Vol. 20(1). */ /* * This file was modified by Electronic Arts Inc Copyright © 2010 */ #include "config.h" #include "Arena.h" #include <algorithm> #include <stdlib.h> #include <string.h> #include <wtf/Assertions.h> #include <wtf/FastMalloc.h> using namespace std; namespace OWBAL { //#define DEBUG_ARENA_MALLOC #ifdef DEBUG_ARENA_MALLOC static int i = 0; #endif #define FREELIST_MAX 30 static Arena *arena_freelist; static int freelist_count = 0; #define ARENA_DEFAULT_ALIGN sizeof(double) #define BIT(n) ((unsigned int)1 << (n)) #define BITMASK(n) (BIT(n) - 1) #define CEILING_LOG2(_log2,_n) \ unsigned int j_ = (unsigned int)(_n); \ (_log2) = 0; \ if ((j_) & ((j_)-1)) \ (_log2) += 1; \ if ((j_) >> 16) \ (_log2) += 16, (j_) >>= 16; \ if ((j_) >> 8) \ (_log2) += 8, (j_) >>= 8; \ if ((j_) >> 4) \ (_log2) += 4, (j_) >>= 4; \ if ((j_) >> 2) \ (_log2) += 2, (j_) >>= 2; \ if ((j_) >> 1) \ (_log2) += 1; static int CeilingLog2(unsigned int i) { int log2; CEILING_LOG2(log2,i); return log2; } void InitArenaPool(ArenaPool *pool, const char *name, unsigned int size, unsigned int align) { if (align == 0) align = ARENA_DEFAULT_ALIGN; pool->mask = BITMASK(CeilingLog2(align)); pool->first.next = NULL; pool->first.base = pool->first.avail = pool->first.limit = (uword)ARENA_ALIGN(pool, &pool->first + 1); pool->current = &pool->first; pool->arenasize = size; } /* ** ArenaAllocate() -- allocate space from an arena pool ** ** Description: ArenaAllocate() allocates space from an arena ** pool. ** ** First try to satisfy the request from arenas starting at ** pool->current. ** ** If there is not enough space in the arena pool->current, try ** to claim an arena, on a first fit basis, from the global ** freelist (arena_freelist). ** ** If no arena in arena_freelist is suitable, then try to ** allocate a new arena from the heap. ** ** Returns: pointer to allocated space or NULL ** */ void* ArenaAllocate(ArenaPool *pool, unsigned int nb) { Arena *a; char *rp; /* returned pointer */ ASSERT((nb & pool->mask) == 0); nb = (uword)ARENA_ALIGN(pool, nb); /* force alignment */ /* attempt to allocate from arenas at pool->current */ { a = pool->current; do { if ( a->avail +nb <= a->limit ) { pool->current = a; rp = (char *)a->avail; a->avail += nb; return rp; } } while( NULL != (a = a->next) ); } /* attempt to allocate from arena_freelist */ { Arena *p = NULL; /* previous pointer, for unlinking from freelist */ for ( a = arena_freelist; a != NULL ; p = a, a = a->next ) { if ( a->base +nb <= a->limit ) { if ( p == NULL ) arena_freelist = a->next; else p->next = a->next; a->avail = a->base; rp = (char *)a->avail; a->avail += nb; /* the newly allocated arena is linked after pool->current * and becomes pool->current */ a->next = pool->current->next; pool->current->next = a; pool->current = a; if ( 0 == pool->first.next ) pool->first.next = a; freelist_count--; return(rp); } } } /* attempt to allocate from the heap */ { unsigned int sz = max(pool->arenasize, nb); sz += sizeof *a + pool->mask; /* header and alignment slop */ #ifdef DEBUG_ARENA_MALLOC i++; OWB_PRINTF("Malloc: %d\n", i); #endif a = (Arena*)fastMalloc(sz); if (a) { a->limit = (uword)a + sz; a->base = a->avail = (uword)ARENA_ALIGN(pool, a + 1); rp = (char *)a->avail; a->avail += nb; /* the newly allocated arena is linked after pool->current * and becomes pool->current */ a->next = pool->current->next; pool->current->next = a; pool->current = a; if ( !pool->first.next ) pool->first.next = a; return(rp); } } /* we got to here, and there's no memory to allocate */ return(0); } /* --- end ArenaAllocate() --- */ void* ArenaGrow(ArenaPool *pool, void *p, unsigned int size, unsigned int incr) { void *newp; ARENA_ALLOCATE(newp, pool, size + incr); if (newp) memcpy(newp, p, size); return newp; } /* * Free tail arenas linked after head, which may not be the true list head. * Reset pool->current to point to head in case it pointed at a tail arena. */ static void FreeArenaList(ArenaPool *pool, Arena *head, bool reallyFree) { Arena **ap, *a; ap = &head->next; a = *ap; if (!a) return; #ifdef DEBUG do { ASSERT(a->base <= a->avail && a->avail <= a->limit); a->avail = a->base; CLEAR_UNUSED(a); } while ((a = a->next) != 0); a = *ap; #endif if (freelist_count >= FREELIST_MAX) reallyFree = true; if (reallyFree) { do { *ap = a->next; CLEAR_ARENA(a); #ifdef DEBUG_ARENA_MALLOC if (a) { i--; OWB_PRINTF("Free: %d\n", i); } #endif fastFree(a); a = 0; } while ((a = *ap) != 0); } else { /* Insert the whole arena chain at the front of the freelist. */ do { ap = &(*ap)->next; freelist_count++; } while (*ap); *ap = arena_freelist; arena_freelist = a; head->next = 0; } pool->current = head; } void ArenaRelease(ArenaPool *pool, char *mark) { Arena *a; for (a = pool->first.next; a; a = a->next) { if (UPTRDIFF(mark, a->base) < UPTRDIFF(a->avail, a->base)) { a->avail = (uword)ARENA_ALIGN(pool, mark); FreeArenaList(pool, a, false); return; } } } void FreeArenaPool(ArenaPool *pool) { FreeArenaList(pool, &pool->first, false); } void FinishArenaPool(ArenaPool *pool) { FreeArenaList(pool, &pool->first, true); } }
d86651f08876a058b3542ea2a3ffe610205aa937
df18dca0d8241679ae7cc08f2e3e9deacfd144a3
/src/5.1-a.cpp
e558bc006104c694f2155955ec7266ccf45ab784
[]
no_license
yuyu0127/DA
c22ca3699237551e494e1db353150a8d16731420
55053109d2d63c0a39b980ddbc955ce4752cb2c1
refs/heads/master
2020-04-15T15:25:18.710259
2019-01-09T05:17:18
2019-01-09T05:17:18
164,559,690
0
0
null
null
null
null
UTF-8
C++
false
false
4,457
cpp
5.1-a.cpp
#include <iostream> #include <string> #define HASH_SIZE 701 class SinglyLinkedList { private: struct Node { public: std::string value; Node* next; }; Node* head; public: SinglyLinkedList() { head = nullptr; } Node* insert_first(std::string value) { /* ノードがない場合 */ if (head == nullptr) { Node* new_node = new Node(); new_node->value = value; new_node->next = nullptr; head = new_node; return new_node; } Node* new_node = new Node(); new_node->value = value; new_node->next = head; head = new_node; return new_node; } void remove(std::string value) { Node* node_ptr = head; Node* node_prev_ptr = nullptr; while (true) { /* そもそもノードがない場合例外を吐く */ if (node_ptr == nullptr) { throw "Error : List is empty"; } /* 参照中の値が消したい値と一致していたらそのノードを消す */ if (node_ptr->value == value) { if (node_ptr == head) { head = node_ptr->next; } else { node_prev_ptr->next = node_ptr->next; } delete node_ptr; return; } /* 最後のノードまで行き着いたら消す値がないということで例外を吐く */ if (node_ptr->next == nullptr) { throw "Error : Value does not exist in the list"; } node_prev_ptr = node_ptr; node_ptr = node_ptr->next; } } Node* search(std::string value) { /* リストが空であればnullptrを返す */ if (head == nullptr) { return nullptr; } /* ノードを辿る */ for (Node* node_ptr = head; node_ptr != nullptr; node_ptr = node_ptr->next) { if (node_ptr->value == value) { return node_ptr; } } return nullptr; } void print() { if (head == nullptr) { std::cout << "No node" << std::endl; return; } for (Node* node_ptr = head; node_ptr != nullptr; node_ptr = node_ptr->next) { std::cout << node_ptr->value << " "; } std::cout << std::endl; } }; int cahc_hash(std::string str) { int hash_num = 0; for (int i = 0; i < str.size(); i++) { hash_num += ((int)str[str.size() - i - 1] * (1 << i)) % HASH_SIZE; hash_num %= HASH_SIZE; } return hash_num; } int main(int argc, char const* argv[]) { SinglyLinkedList lists[HASH_SIZE]; for (int i = 0; i < HASH_SIZE; i++) { lists[i] = SinglyLinkedList(); } while (true) { char command; std::cout << "command? (a=add r=remove s=search q=quit) : "; std::cin >> command; switch (command) { case 'a': { std::string str; std::cout << "string to add? : "; std::cin >> str; int hash_num = cahc_hash(str); std::cout << "hash=" << hash_num << "\n"; lists[hash_num].insert_first(str); break; } case 'r': { std::string str; std::cout << "string to remove? : "; std::cin >> str; int hash_num = cahc_hash(str); std::cout << "hash=" << hash_num << "\n"; try { lists[hash_num].remove(str); std::cout << "Remove succeed!\n"; } catch (const char* str) { std::cout << "Not found\n"; } break; } case 's': { std::string str; std::cout << "string to search? : "; std::cin >> str; int hash_num = cahc_hash(str); std::cout << "hash=" << hash_num << "\n"; auto node_ptr = lists[hash_num].search(str); if (node_ptr != nullptr) { std::cout << "Found!\n"; } else { std::cout << "Not found\n"; } break; } case 'q': { return 0; } default: break; } std::cout << "\n"; } return 0; }
fb76be5455b5ed8e3b6bd866e4390e67638157e9
982bae350aaf9e106205901f7e39cc7d213e52af
/spoj/EPALIN.cpp
fe8620a391a58c60c84fed8aa6f2f74c26afa835
[]
no_license
rafaelrds/competitive-programming
74e2403cc18f7a6e56a424a932d015c656bcaa0c
73b0364f88b744e266a7b2605ffc10b18e67b486
refs/heads/master
2023-06-10T02:15:32.849083
2023-06-02T23:07:09
2023-06-02T23:07:09
104,693,062
3
1
null
2022-12-12T14:45:29
2017-09-25T02:11:07
C++
UTF-8
C++
false
false
799
cpp
EPALIN.cpp
#include <cstdio> #include <cstring> using namespace std; int L, pref[100000],k; char T[100001],P[100001]; int main(){ while(scanf("%s",T)==1){ L = strlen(T); for(int i = 0,j = L-1;i<L;++i,--j) P[i] = T[j]; pref[0] = 0; for(int i = 1;i<L;++i){ k = pref[i-1]; while(k>0 && P[k]!=P[i]) k = pref[k-1]; if(P[k]==P[i]) ++k; pref[i] = k; } k = 0; for(int i = 0;i<L;++i){ while(k>0 && P[k]!=T[i]) k = pref[k-1]; if(P[k]==T[i]) ++k; if(i!=L-1 && k==L) k = pref[L-1]; } printf("%s",T); for(int i = L-k-1;i>=0;--i) putchar(T[i]); putchar('\n'); } return 0; }
5f86b38a4774c22ce4f219dfd0a10d7e6ca09556
715aba5d770d25c999e081a099bdadacc9b9156a
/src/shared/solv/solvinfo.hpp
64d108fd71a650c8972e4c7e56a703959aeef89d
[ "MIT" ]
permissive
master-clown/feata
342b91025af5d1f7731a36b1c72892f1b9ca8fa3
306cbc3a402551fb62b3925d23a2d4f63f60d525
refs/heads/master
2020-05-29T09:37:44.311743
2019-08-14T06:02:57
2019-08-14T06:02:57
189,070,795
1
1
null
null
null
null
UTF-8
C++
false
false
556
hpp
solvinfo.hpp
#pragma once struct MeshInfo; /** * All important fields will be marked with "[i][o]!". * i -- important for input, o -- for output */ struct SolvInfo { typedef double num_t; const MeshInfo* Mesh; /*i!*/ /** * \brief DispLst * Displacement vector list for every node. Three numbers per node. */ num_t* DispLst; /*o!*/ #pragma message("Think where dealloc it") SolvInfo(); ~SolvInfo(); void Dealloc(); void Nullify(); }; #include "solv/solvinfo.inl"
479763708668936c73e2baf2400ad19ae67d91fa
beaccd4ca566e9f7f112b98dfe3e32ade0feabcc
/code chef/maxpr.cpp
2ed15d7b98153f7eeea3813749d3f86aab129b30
[]
no_license
maddotexe/Competitive-contest-programs
83bb41521f80e2eea5c08f198aa9384cd0986cde
4bc37c5167a432c47a373c548721aedd871fc6b7
refs/heads/master
2020-04-17T08:08:43.922419
2015-03-10T19:26:55
2015-03-10T19:26:55
31,177,844
1
1
null
null
null
null
UTF-8
C++
false
false
3,060
cpp
maxpr.cpp
#include<bits/stdc++.h> using namespace std; #define TRACE #ifdef TRACE #define trace1(x) cerr << #x << ": " << x << endl; #define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl; #define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl; #define trace4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl; #define trace5(a, b, c, d, e) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl; #define trace6(a, b, c, d, e, f) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl; #else #define trace1(x) #define trace2(x, y) #define trace3(x, y, z) #define trace4(a, b, c, d) #define trace5(a, b, c, d, e) #define trace6(a, b, c, d, e, f) #endif #define ull unsigned long long #define ll long long #define Max(x,y) ((x)>(y)?(x):(y)) #define Min(x,y) ((x)<(y)?(x):(y)) #define Sl(x) scanf("%lld",&x) #define Su(x) scanf("%llu",&x) #define S(x) scanf("%d",&x) #define IS(x) cin>>x #define ISF(x) getline(cin,x) #define pii pair<int,int> #define ppi pair<int, pii> #define pll pair<ll,ll> #define ppl pair<ll,pll> #define ppf pair<pll,ll> #define psi pair<string,int> #define pis pair<int,string> #define fr first #define se second #define MOD 1000000007 #define MP(x,y) make_pair(x,y) #define eps 1e-7 #define V(x) vector<x> #define pb(x) push_back(x) #define mem(x,i) memset(x,i,sizeof(x)) #define fori(i,s,n) for(i=(s);i<(n);i++) #define ford(i,s,n) for(i=(n);i>=(s);--i) #define INF 8944674407370955161LL #define all(a) a.begin(),a.end() int abs(int x) {if(x < 0) return -x; return x;} int dpp[101][101], dpn[101][101]; int p2[200100], vis[101]; int a[200100]; int main() { ios_base::sync_with_stdio(false); int t, n; cin >> t; p2[0] = 1; for (int i = 1; i < 200010; i++) { p2[i] = ((ll)p2[i-1] * 2LL) % MOD; } while (t--) { mem(dpp, 0); mem(dpn, 0); mem(vis, 0); cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) { for (int j = 1; j < a[i]; j++) { if (vis[a[i] - j]) { dpp[a[i]][j] += dpp[a[i] - j][j] + vis[a[i] - j]; dpp[a[i]][j] %= MOD; } } for (int j = 1; j + a[i] <= 100; j++) { if (vis[a[i] + j]) { dpn[a[i]][j] += dpn[a[i] + j][j] + vis[a[i] + j]; dpn[a[i]][j] %= MOD; } } vis[a[i]]++; } int res = 1, ans = p2[n]; for (int i = 1; i <= 100; i++) { int val = p2[vis[i]] - 1; if (val < 0) val += MOD; res = (res + val) % MOD; } for (int i = 1; i < 101; i++) { for (int j = 1; j < 101; j++) { res = (res + dpp[i][j]) % MOD; res = (res + dpn[i][j]) % MOD; } } cout << (ans + MOD - res) % MOD << endl; } return 0; }
181cf09de4aca3656aa5b0e9692c2875e93e6864
325629fde51468c5d03f4028a13c43d967d1b05b
/signal-slot-benchmarks/benchmark/lib/jeffomatic/jl_signal/src/DoublyLinkedListTest.cpp
f113d2ee98e1cf3601d92e7d080270213280aa12
[ "MIT", "CPOL-1.02", "LicenseRef-scancode-public-domain" ]
permissive
j-jorge/signals
cc05945517f377735e3b38741d41868dedafe9dd
02653304840ed294bb907d13cdce3cc260b5d8ce
refs/heads/master
2021-03-10T02:25:01.766388
2020-03-11T07:39:20
2020-03-11T07:39:20
246,407,802
0
0
MIT
2020-03-10T21:03:29
2020-03-10T21:03:28
null
UTF-8
C++
false
false
4,883
cpp
DoublyLinkedListTest.cpp
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include "DoublyLinkedList.h" #include "ObjectPoolScopedAllocator.h" using namespace jl; namespace { typedef DoublyLinkedList<const char*> StringList; typedef StaticObjectPoolAllocator< sizeof(StringList::Node), 100 > StringNodeAllocator; } void DoublyLinkedListTest() { const char* pTestStrings[] = { "Test 1", "Test 2", "Test 3", "Test 4", "Test 5", "Test 6", "Test 7", "Test 8", "Test 9", "Test 10", "Test 11", "Test 12", "Test 13", "Test 14", "Test 15", "Test 16", "Test 17", "Test 18", "Test 19", "Test 20", "Test 21", "Test 22", "Test 23", "Test 24", "Test 25", "Test 26", "Test 27", "Test 28", "Test 29", "Test 30", "Test 31", "Test 32", }; StringNodeAllocator oAllocator; StringList oList; oList.Init( & oAllocator ); // Insertion test printf( "Inserting objects...\n" ); for ( unsigned i = 0; i < JL_ARRAY_SIZE(pTestStrings); ++i ) { assert( oList.Add(pTestStrings[i]) ); } // Test object count assert( oList.Count() == JL_ARRAY_SIZE(pTestStrings) ); // Iterator test printf( "Iterating through list...\n" ); for ( StringList::iterator i = oList.begin(); i.isValid(); ++i ) { printf( "\tObject: %s\n", *i ); } // Value-based removal printf( "Value-based removal...\n" ); for ( unsigned i = 0; i < JL_ARRAY_SIZE(pTestStrings); ++i ) { printf( "\tRemoving: %s\n", pTestStrings[i] ); assert( oList.Remove(pTestStrings[i]) ); } // Test object count assert( oList.Count() == 0 ); assert( oAllocator.CountAllocations() == 0 ); // Value-based reverse removal printf( "Value-based reverse removal...\n" ); for ( unsigned i = 0; i < JL_ARRAY_SIZE(pTestStrings); ++i ) { assert( oList.Add(pTestStrings[i]) ); } for ( unsigned i = JL_ARRAY_SIZE(pTestStrings); i > 0; --i ) { printf( "\tRemoving: %s\n", pTestStrings[i - 1] ); assert( oList.Remove(pTestStrings[i - 1]) ); } // Test object count assert( oList.Count() == 0 ); assert( oAllocator.CountAllocations() == 0 ); // Iterator-based removal printf( "Iterator-based removal...\n" ); for ( unsigned i = 0; i < JL_ARRAY_SIZE(pTestStrings); ++i ) { assert( oList.Add(pTestStrings[i]) ); } for ( StringList::iterator i = oList.begin(); i.isValid(); ) { printf( "\tRemoving: %s\n", *i ); assert( oList.Remove(i) ); } // Test object count assert( oList.Count() == 0 ); assert( oAllocator.CountAllocations() == 0 ); // Random removal enum { eRandomTrials = 16 }; printf( "\nStarting %d random removal tests\n", eRandomTrials ); for ( unsigned i = 0; i < 5; ++i ) { const unsigned nInsert = ( rand() % JL_ARRAY_SIZE(pTestStrings) ) + 1; const unsigned nRemove = ( rand() % nInsert ) + 1; printf( "\tTrial %d: inserting %d objects and removing %d objects\n", i + 1, nInsert, nRemove ); // Insert objects printf( "\t\tInserting %d objects\n", nInsert ); for ( unsigned j = 0; j < nInsert; ++j ) { printf( "\t\t\tInserting %s\n", pTestStrings[j] ); assert( oList.Add(pTestStrings[j]) ); } // Remove objects printf( "\t\tRemoving %d objects\n", nRemove ); for ( unsigned j = 0; j < nRemove; ++j ) { // Create iterator and seek to random position const unsigned nSeek = rand() % oList.Count(); StringList::iterator iter = oList.begin(); for ( unsigned k = 0; k < nSeek; ++k ) { ++iter; } // Remove object from list printf( "\t\t\tRemoving item ID%d: %s\n", nSeek, *iter ); assert( oList.Remove(iter) ); } // Display leftovers printf( "\t\tRemaining objects (%d):\n", oList.Count() ); for ( StringList::iterator i = oList.begin(); i.isValid(); ++i ) { printf( "\t\t\tObject: %s\n", *i ); } // Test object count const unsigned nCount = nInsert - nRemove; assert( oList.Count() == nCount ); assert( oAllocator.CountAllocations() == nCount ); // Clear oList.Clear(); // Test object count assert( oList.Count() == 0 ); assert( oAllocator.CountAllocations() == 0 ); } }
653caa40e9fa82c2c47984267c016794e2f358e6
a8fc3ed50d169a2503de09d6448b08051595204e
/S.0824/S.0824/stack.cpp
1ee0b4f279a0a34b354af854d4ca1237179f1a39
[]
no_license
STong01/C-.0826
17cce96c86e68071a45ac97ea78929774a2c471e
c62d12916c129b30e87047abab994ff8be10f17e
refs/heads/master
2020-07-11T03:18:43.622333
2019-08-26T08:47:29
2019-08-26T08:47:29
204,434,048
0
0
null
null
null
null
UTF-8
C++
false
false
925
cpp
stack.cpp
#include "stack.h" void StackInit(Stack* psl, size_t capicity){ assert(psl); psl->capicity = capicity; psl->array = (StDataType*)malloc(capicity* sizeof(StDataType)); assert(psl->array); psl->size = 0; } void StackDestory(Stack* psl){ assert(psl); if (psl->array){ free(psl->array); psl->array = NULL; psl->size = 0; psl->capicity = 0; } } void CheckCapacity(Stack* psl){ assert(psl); if (psl->size == psl->capicity){ psl->capicity *= 2; psl->array = (StDataType*)realloc(psl->array, psl->capicity*sizeof(StDataType)); } } void StackPush(Stack* psl, StDataType x){ assert(psl); CheckCapacity(psl); psl->array[psl->size] = x; psl->size++; } void StackPop(Stack* psl){ assert(psl || psl->size); psl->size--; } StDataType StackTop(Stack* psl){ if (StackIsEmpty(psl)){ return (StDataType)0; } return psl->array[psl->size - 1]; } int StackIsEmpty(Stack* pal){ return pal->size == 0; }
6816077c6bb975172b9988169a12dc89d3210f03
055ed53c7de70c5d214254bc0c9bb797e4b4bae4
/QDcm/dcmcore/src/DcmTagUL.cpp
7d575e82a8f0034daf6242260408f075b99f6d9f
[]
no_license
kevinlq/MyQt
8ad0593db71171be64008038c766fcd79c64540c
1bfedfb6a186feb177f291b28fdf5ca2393ed0e4
refs/heads/master
2022-11-23T11:24:44.888305
2022-11-07T15:41:30
2022-11-07T15:41:30
91,306,496
21
8
null
2018-04-25T10:49:40
2017-05-15T07:13:54
C++
UTF-8
C++
false
false
2,417
cpp
DcmTagUL.cpp
/* 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. */ #include "DcmTagUL.h" DcmTagUL::DcmTagUL() : DcmTag(DcmTagKey(), DcmVr::UL), m_values() { } DcmTagUL::DcmTagUL(const DcmTagKey &tagKey) : DcmTag(tagKey, DcmVr::UL), m_values() { } DcmTagUL::DcmTagUL(const DcmTagUL &tag) : DcmTag(tag), m_values(tag.m_values) { } DcmTagUL& DcmTagUL::operator =(const DcmTagUL &tag) { if (this != &tag) { DcmTag::operator =(tag); m_values = tag.m_values; } return *this; } DcmTag* DcmTagUL::clone() const { return new DcmTagUL(*this); } DcmTagUL::~DcmTagUL() { } QVariant DcmTagUL::value() const { if (m_values.count() > 0) { return QVariant(m_values.at(0)); } return QVariant(); } QVariantList DcmTagUL::values() const { QVariantList res; foreach (DcmUnsignedLong v, m_values) { res.append(QVariant(v)); } return res; } void DcmTagUL::setValue(const QVariant &v) { m_values.clear(); if (v.isValid()) { m_values.append((DcmUnsignedLong)v.toUInt()); } } void DcmTagUL::appendValue(const QVariant &v) { if (v.isValid()) { m_values.append((DcmUnsignedLong)v.toUInt()); } } DcmTagUL& DcmTagUL::operator =(const QVariant &v) { setValue(v); return *this; } int DcmTagUL::multiplicity() const { return m_values.count(); } DcmUnsignedLong DcmTagUL::asUnsignedLong() const { DcmUnsignedLong res = 0; if (m_values.count() > 0) { res = m_values.at(0); } return res; } QList<DcmUnsignedLong> DcmTagUL::asUnsignedLongList() const { return m_values; } void DcmTagUL::setUnsignedLong(DcmUnsignedLong v) { m_values.clear(); m_values.append(v); } void DcmTagUL::appendUnsignedLong(DcmUnsignedLong v) { m_values.append(v); } DcmSize DcmTagUL::contentSize(const DcmTransferSyntax &transferSyntax) const { Q_UNUSED(transferSyntax) return 4 * multiplicity(); }
3f3f69eeb1aaf57112c0b28aa35799a6cc4cec56
9f9266a40a869e34c8627f66d0ef05ec25c40236
/AnvilEldorado/Source/Game/Players/PlayerImpl.cpp
c8e342ac500d24ca14852c6f76823b878246b5e5
[ "MIT" ]
permissive
AnvilOnline/AnvilClient
b2d6273de7c1f7d436f939e19948edf2c69631da
9b7751d9583d7221fd9c9f1b864f27e7ff9fcf79
refs/heads/development
2020-04-13T22:12:16.638751
2017-04-22T17:22:10
2017-04-22T17:22:10
44,775,425
57
23
null
2017-04-22T17:22:10
2015-10-22T21:53:19
C++
UTF-8
C++
false
false
12,208
cpp
PlayerImpl.cpp
#include "PlayerImpl.hpp" #include "Hooks.hpp" #include <Game\Cache\StringIdCache.hpp> #include <Game\Players\PlayerArmorExtension.hpp> #include <Interfaces\Client.hpp> #include <EngineImpl.hpp> #include <Globals.hpp> #include <codecvt> using namespace AnvilEldorado::Game::Players; const size_t AnvilEldorado::Game::Players::PlayerPropertiesPacketHeaderSize = 0x18; const size_t AnvilEldorado::Game::Players::PlayerPropertiesSize = 0x30; const size_t AnvilEldorado::Game::Players::PlayerPropertiesPacketFooterSize = 0x4; bool PlayerImpl::Init() { m_PlayerPropertiesExtender->Add(std::make_shared<PlayerArmorExtension>()); m_Hooks = std::make_shared<Players::Hooks>(); if (!m_Hooks->Init()) return false; return true; } Blam::Data::DataArray<Blam::Game::Players::PlayerDatum> &PlayerImpl::GetPlayers() { return *AnvilCommon::GetThreadStorage<Blam::Data::DataArray<Blam::Game::Players::PlayerDatum>>(0x40); } Blam::Data::DatumIndex PlayerImpl::GetLocalPlayer(const int32_t p_Index) { typedef uint32_t(*GetLocalPlayerPtr)(int index); auto GetLocalPlayer = reinterpret_cast<GetLocalPlayerPtr>(0x589C30); return GetLocalPlayer(p_Index); } size_t PlayerImpl::GetPlayerPropertiesPacketSize() { static size_t size; if (size == 0) { size_t extensionSize = m_PlayerPropertiesExtender->GetTotalSize(); size = PlayerPropertiesPacketHeaderSize + PlayerPropertiesSize + extensionSize + PlayerPropertiesPacketFooterSize; } return size; } uint8_t GetArmorIndex(Blam::Text::StringID p_Name, const std::map<Blam::Text::StringID, uint8_t> &p_Indices) { auto it = p_Indices.find(p_Name); return (it != p_Indices.end()) ? it->second : 0; } bool AddArmorPermutations(const Blam::Tags::Game::MultiplayerGlobals::Universal::ArmorCustomization &p_Element, std::map<Blam::Text::StringID, uint8_t> &p_Map) { for (auto i = 0; i < p_Element.Permutations.Count; i++) { auto &s_Permutation = p_Element.Permutations[i]; if (!s_Permutation.FirstPersonArmorModel && !s_Permutation.ThirdPersonArmorObject) continue; p_Map.emplace(s_Permutation.Name.Value, i); } return true; } bool PlayerImpl::LoadArmor(Blam::Tags::Game::MultiplayerGlobals *p_MultiplayerGlobals) { for (auto &s_Customization : p_MultiplayerGlobals->Universal->SpartanArmorCustomization) { auto s_PieceRegion = s_Customization.PieceRegion.Value; if (s_PieceRegion == 0x1CE7) // helmet AddArmorPermutations(s_Customization, m_ArmorHelmetIndices); else if (s_PieceRegion == 0x9E) // chest AddArmorPermutations(s_Customization, m_ArmorChestIndices); else if (s_PieceRegion == 0x35D8) // shoulders AddArmorPermutations(s_Customization, m_ArmorShouldersIndices); else if (s_PieceRegion == 0x606) // arms AddArmorPermutations(s_Customization, m_ArmorArmsIndices); else if (s_PieceRegion == 0x605) // legs AddArmorPermutations(s_Customization, m_ArmorLegsIndices); else if (s_PieceRegion == 0x35D9) // acc AddArmorPermutations(s_Customization, m_ArmorAccessoryIndices); else if (s_PieceRegion == 0x268) // pelvis AddArmorPermutations(s_Customization, m_ArmorPelvisIndices); else { WriteLog("ERROR: Invalid armor piece region: 0x%X", s_PieceRegion); return false; } } for (auto &s_Variant : p_MultiplayerGlobals->Universal->GameVariantWeapons) { if (s_Variant.Weapon.TagIndex != 0xFFFF) m_PodiumWeaponIndices.emplace(s_Variant.Name.Value, s_Variant.Weapon.TagIndex); } m_ArmorPrimaryColor = 0xFFFFFF; m_ArmorSecondaryColor = 0xFFFFFF; m_ArmorVisorColor = 0xFFFFFF; m_ArmorLightsColor = 0xFFFFFF; m_ArmorHoloColor = 0xFFFFFF; m_ArmorHelmet = 0x358F; // air_assault m_ArmorChest = 0x358F; // air_assault m_ArmorShoulders = 0x358F; // air_assault m_ArmorArms = 0x358F; // air_assault m_ArmorLegs = 0x358F; // air_assault m_ArmorPelvis = 0x358F; // air_assault m_ArmorAccessory = 0x0; m_UpdateArmor = true; return true; } Blam::Data::DatumIndex PlayerImpl::GetPodiumBiped() const { return Blam::Data::DatumIndex(*reinterpret_cast<uint32_t *>((uint8_t *)AnvilCommon::Internal_GetModuleStorage() + 0x4BE67A0)); } void PlayerImpl::BuildCustomization(Blam::Game::Players::PlayerCustomization *p_Customization) const { memset(p_Customization, 0, sizeof(Blam::Game::Players::PlayerCustomization)); memset(p_Customization->Colors, 0, 5 * sizeof(uint32_t)); p_Customization->Colors[(int)Blam::Game::Players::PlayerColor::Primary] = m_ArmorPrimaryColor; p_Customization->Colors[(int)Blam::Game::Players::PlayerColor::Secondary] = m_ArmorSecondaryColor; p_Customization->Colors[(int)Blam::Game::Players::PlayerColor::Visor] = m_ArmorVisorColor; p_Customization->Colors[(int)Blam::Game::Players::PlayerColor::Lights] = m_ArmorLightsColor; p_Customization->Colors[(int)Blam::Game::Players::PlayerColor::Holo] = m_ArmorHoloColor; p_Customization->Armor[(int)Blam::Game::Players::PlayerArmor::Helmet] = GetArmorIndex(m_ArmorHelmet, m_ArmorHelmetIndices); p_Customization->Armor[(int)Blam::Game::Players::PlayerArmor::Chest] = GetArmorIndex(m_ArmorChest, m_ArmorChestIndices); p_Customization->Armor[(int)Blam::Game::Players::PlayerArmor::Shoulders] = GetArmorIndex(m_ArmorShoulders, m_ArmorShouldersIndices); p_Customization->Armor[(int)Blam::Game::Players::PlayerArmor::Arms] = GetArmorIndex(m_ArmorArms, m_ArmorArmsIndices); p_Customization->Armor[(int)Blam::Game::Players::PlayerArmor::Legs] = GetArmorIndex(m_ArmorLegs, m_ArmorLegsIndices); p_Customization->Armor[(int)Blam::Game::Players::PlayerArmor::Acc] = GetArmorIndex(m_ArmorAccessory, m_ArmorAccessoryIndices); p_Customization->Armor[(int)Blam::Game::Players::PlayerArmor::Pelvis] = GetArmorIndex(m_ArmorPelvis, m_ArmorPelvisIndices); } const auto Biped_ApplyArmor = reinterpret_cast<void(*)(Blam::Game::Players::PlayerCustomization *, uint32_t)>(0x5A4430); const auto Biped_ApplyArmorColor = reinterpret_cast<void(*)(uint32_t, int32_t, float *)>(0xB328F0); const auto Biped_UpdateArmorColors = reinterpret_cast<void(*)(uint32_t)>(0x5A2FA0); /*void Biped_PoseWithWeapon(uint32_t p_Unit, uint32_t p_Weapon) { const auto sub_B450F0 = reinterpret_cast<char(*)(uint16_t, int)>(0xB450F0); const auto sub_B31590 = reinterpret_cast<DWORD*(*)(void*, int, int, int)>(0xB31590); const auto sub_B30440 = reinterpret_cast<signed int(*)(double, __m128, void*)>(0xB30440); const auto sub_B393D0 = reinterpret_cast<char(*)(double, __m128, int, int, int)>(0xB393D0); const auto sub_B2CD10 = reinterpret_cast<int(*)(double, __m128, int)>(0xB2CD10); if (!sub_B450F0(p_Unit, p_Weapon)) { char v9; sub_B31590(&v9, p_Weapon, -1, 0); signed int v7 = sub_B30440(a1, a2, &v9);//crash if (v7 != -1 && !sub_B393D0(a1, a2, p_Unit, v7, 8)) sub_B2CD10(a1, a2, v7); } }*/ //TODO: Remove inlined assembly (WIP version above) __declspec(naked) void Biped_PoseWithWeapon(uint32_t p_Unit, uint32_t p_Weapon) { // This is a pretty big hack, basically I don't know where the function pulls the weapon index from // so this lets us skip over the beginning of the function and set the weapon tag to whatever we want __asm { push ebp mov ebp, esp sub esp, 0x18C push esi push edi sub esp, 0x8 mov esi, p_Unit mov edi, p_Weapon push 0x7B77DA ret } } void PlayerImpl::CustomizeBiped(const Blam::Data::DatumIndex &p_BipedIndex) { // Generate customization data Blam::Game::Players::PlayerCustomization customization; BuildCustomization(&customization); // Apply armor to the biped Biped_ApplyArmor(&customization, p_BipedIndex.Value); // Apply each color for (int32_t i = 0; i < (int)Blam::Game::Players::PlayerColor::Count; i++) { // Convert the color data from RGB to float3 float colorData[3]; typedef void(*RgbToFloatColorPtr)(uint32_t rgbColor, float *result); RgbToFloatColorPtr RgbToFloatColor = reinterpret_cast<RgbToFloatColorPtr>(0x521300); RgbToFloatColor(customization.Colors[i], colorData); // Apply the color Biped_ApplyArmorColor(p_BipedIndex.Value, i, colorData); } // Need to call this or else colors don't actually show up Biped_UpdateArmorColors(p_BipedIndex.Value); // Give the biped a weapon (0x151E = tag index for Assault Rifle) auto s_WeaponName = m_PodiumWeapon; if (m_PodiumWeaponIndices.find(s_WeaponName) == m_PodiumWeaponIndices.end()) s_WeaponName = (m_PodiumWeapon = 0x41A); // assault_rifle Biped_PoseWithWeapon(p_BipedIndex.Value, m_PodiumWeaponIndices.find(s_WeaponName)->second); } std::wstring PlayerImpl::GetName() const { return m_UserName; } void PlayerImpl::SetName(const std::string &p_UserName) { m_UserName = std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>().from_bytes(p_UserName.c_str()); m_UserName.resize(17); m_UserName.back() = 0; } bool PlayerImpl::NeedsArmorUpdate() const { return m_UpdateArmor; } void PlayerImpl::SetUpdateArmor(const bool p_UpdateArmor) { m_UpdateArmor = p_UpdateArmor; } uint32_t PlayerImpl::GetArmorPrimaryColor() const { return m_ArmorPrimaryColor; } void PlayerImpl::SetArmorPrimaryColor(const uint32_t p_Color) { m_ArmorPrimaryColor = p_Color; } void PlayerImpl::SetArmorPrimaryColor(const uint8_t p_Red, const uint8_t p_Green, const uint8_t p_Blue) { SetArmorPrimaryColor((p_Blue << 16) | (p_Green << 8) | (p_Red << 0)); } uint32_t PlayerImpl::GetArmorSecondaryColor() const { return m_ArmorSecondaryColor; } void PlayerImpl::SetArmorSecondaryColor(const uint32_t p_Color) { m_ArmorSecondaryColor = p_Color; } void PlayerImpl::SetArmorSecondaryColor(const uint8_t p_Red, const uint8_t p_Green, const uint8_t p_Blue) { SetArmorSecondaryColor((p_Blue << 16) | (p_Green << 8) | (p_Red << 0)); } uint32_t PlayerImpl::GetArmorVisorColor() const { return m_ArmorVisorColor; } void PlayerImpl::SetArmorVisorColor(const uint32_t p_Color) { m_ArmorVisorColor = p_Color; } void PlayerImpl::SetArmorVisorColor(const uint8_t p_Red, const uint8_t p_Green, const uint8_t p_Blue) { SetArmorVisorColor((p_Blue << 16) | (p_Green << 8) | (p_Red << 0)); } uint32_t PlayerImpl::GetArmorLightsColor() const { return m_ArmorLightsColor; } void PlayerImpl::SetArmorLightsColor(const uint32_t p_Color) { m_ArmorLightsColor = p_Color; } void PlayerImpl::SetArmorLightsColor(const uint8_t p_Red, const uint8_t p_Green, const uint8_t p_Blue) { SetArmorLightsColor((p_Blue << 16) | (p_Green << 8) | (p_Red << 0)); } uint32_t PlayerImpl::GetArmorHoloColor() const { return m_ArmorHoloColor; } void PlayerImpl::SetArmorHoloColor(const uint32_t p_Color) { m_ArmorHoloColor = p_Color; } void PlayerImpl::SetArmorHoloColor(const uint8_t p_Red, const uint8_t p_Green, const uint8_t p_Blue) { SetArmorHoloColor((p_Blue << 16) | (p_Green << 8) | (p_Red << 0)); } Blam::Text::StringID PlayerImpl::GetArmorHelmet() const { return m_ArmorHelmet; } void PlayerImpl::SetArmorHelmet(const Blam::Text::StringID &p_ArmorHelmet) { m_ArmorHelmet = p_ArmorHelmet; } Blam::Text::StringID PlayerImpl::GetArmorChest() const { return m_ArmorChest; } void PlayerImpl::SetArmorChest(const Blam::Text::StringID &p_ArmorChest) { m_ArmorChest = p_ArmorChest; } Blam::Text::StringID PlayerImpl::GetArmorShoulders() const { return m_ArmorShoulders; } void PlayerImpl::SetArmorShoulders(const Blam::Text::StringID &p_ArmorShoulders) { m_ArmorShoulders = p_ArmorShoulders; } Blam::Text::StringID PlayerImpl::GetArmorArms() const { return m_ArmorArms; } void PlayerImpl::SetArmorArms(const Blam::Text::StringID &p_ArmorArms) { m_ArmorArms = p_ArmorArms; } Blam::Text::StringID PlayerImpl::GetArmorLegs() const { return m_ArmorLegs; } void PlayerImpl::SetArmorLegs(const Blam::Text::StringID &p_ArmorLegs) { m_ArmorLegs = p_ArmorLegs; } Blam::Text::StringID PlayerImpl::GetArmorPelvis() const { return m_ArmorPelvis; } void PlayerImpl::SetArmorPelvis(const Blam::Text::StringID &p_ArmorPelvis) { m_ArmorPelvis = p_ArmorPelvis; } Blam::Text::StringID PlayerImpl::GetArmorAccessory() const { return m_ArmorAccessory; } void PlayerImpl::SetArmorAccessory(const Blam::Text::StringID &p_ArmorAccessory) { m_ArmorAccessory = p_ArmorAccessory; } Blam::Text::StringID PlayerImpl::GetPodiumWeapon() const { return m_PodiumWeapon; } void PlayerImpl::SetPodiumWeapon(const Blam::Text::StringID &p_PodiumWeapon) { m_PodiumWeapon = p_PodiumWeapon; }
e1575c3ea8471643f2a2f427d12c7aaa730bff75
c335a90b03c3898ee66db88c19f5423b204ebb90
/Source/DACrypt/DCryptAES.cpp
b26f098e012a2428c4ddac3881e9b983199d416a
[ "MIT" ]
permissive
XDAppDeprecated/DawnAppFramework
df28c4e6d428c64bea6b5ccaac80faa7f5ac3b56
8655de88200e847ce0e822899395247ade515bc6
refs/heads/master
2021-05-30T03:30:33.326587
2015-07-16T12:43:07
2015-07-16T12:43:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,945
cpp
DCryptAES.cpp
#include "stdafx.h" #include "DCryptAES.h" #include "DAESKey.h" #include "DCryptException.h" DCryptAES::DCryptAES() { } DCryptAES::~DCryptAES() { } void DCryptAES::AES_Encrypt(DAESKey *key, unsigned char* &Crypt, size_t &CryptLength, const unsigned char* Origin, const size_t OriginLength, const unsigned char* iv) { EVP_CIPHER_CTX *ctx; int len; if (!(ctx = EVP_CIPHER_CTX_new())) GlobalDF->DebugManager->ThrowError<DCryptException>(nullptr, L"Failed to create Context"); if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key->GetKey(), iv)) GlobalDF->DebugManager->ThrowError<DCryptException>(nullptr, L"Failed to initialize encrypt"); if (1 != EVP_EncryptUpdate(ctx, Crypt, &len, Origin, OriginLength)) GlobalDF->DebugManager->ThrowError<DCryptException>(nullptr, L"Failed to update encrypt"); CryptLength = len; if (1 != EVP_EncryptFinal_ex(ctx, Crypt + len, &len)) GlobalDF->DebugManager->ThrowError<DCryptException>(nullptr, L"Failed to final encrypt"); CryptLength += len; EVP_CIPHER_CTX_free(ctx); } void DCryptAES::AES_Decrypt(DAESKey *key, unsigned char* &Crypt, size_t &CryptLength, const unsigned char* Origin, const size_t OriginLength, const unsigned char* iv) { EVP_CIPHER_CTX *ctx; int len; if (!(ctx = EVP_CIPHER_CTX_new())) GlobalDF->DebugManager->ThrowError<DCryptException>(nullptr, L"Failed to create Context"); if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key->GetKey(), iv)) GlobalDF->DebugManager->ThrowError<DCryptException>(nullptr, L"Failed to initialize decrypt"); if (1 != EVP_DecryptUpdate(ctx, Crypt, &len, Origin, OriginLength)) GlobalDF->DebugManager->ThrowError<DCryptException>(nullptr, L"Failed to update decrypt"); CryptLength = len; if (1 != EVP_DecryptFinal_ex(ctx, Crypt + len, &len)) GlobalDF->DebugManager->ThrowError<DCryptException>(nullptr, L"Failed to final decrypt"); CryptLength += len; EVP_CIPHER_CTX_free(ctx); }
ad33cd60fb292063dcad4cc1d8b9d735f07548a1
f8f3da6fa276a1bbf9f18262bdb53f4f6772b31b
/graph/Graf.h
fd30731a630d42af96462870008711b399e02cb8
[ "MIT" ]
permissive
azimiqbal/Structures
3fe05493dd64ffe99d83db5f8e6051802623a738
71318d7c48fc3588451febc7c3d5a9855e55168e
refs/heads/main
2023-04-16T06:30:44.835023
2021-04-26T23:49:37
2021-04-26T23:49:37
361,906,724
0
0
null
null
null
null
UTF-8
C++
false
false
797
h
Graf.h
// // Created by Azim Iqbal on 2019-04-07. // #ifndef OBLIG2_GRAF_H #define OBLIG2_GRAF_H #include "std_lib_facilities.h" struct node { int data; vector<node*> naboer; //vector i nodene som inneholder peker til naboene til en node void add_nabo(node* n); }; class Graf { public: Graf(); ~Graf(); vector <node*> noder; //vector som peker til node void createNode(int value); void removeNode(int a); node* find(int a); //peker som brukes til å finne node void add_edge_directed(int a, int b); //rettet graf void add_edge_undirected(int a, int b); //urettet graf void remove_edge_directed(int a, int b); //fjern rettet void remove_edge_undirected(int a, int b); //fjern urettet void printGraf(); }; #endif //OBLIG2_GRAF_H
628414c970b98caf2948454e076b2004ab12110e
82b16d6de8d9bced1cb0bc615a913af23169ed4e
/src/generation/semantic_remover.h
7560f1bebd844a6a1e97b4a3010ccbef7fc677e4
[]
no_license
FishingCactus/ShaderShaker2
753784f6a22896160a418e3b179d3c6a3ec2bc69
b300ec80c00685325b1937cbfbbad3ea559373a8
refs/heads/master
2021-03-12T23:03:54.908551
2015-05-08T13:50:24
2015-05-08T13:50:24
18,032,320
9
0
null
2016-11-24T11:28:33
2014-03-23T11:59:26
HTML
UTF-8
C++
false
false
540
h
semantic_remover.h
#ifndef SEMANTIC_REMOVER_H #define SEMANTIC_REMOVER_H #include <ast/empty_visitor.h> namespace Generation { class SemanticRemover : public AST::EmptyVisitor { virtual void Visit( AST::TranslationUnit & translation_unit ) override; virtual void Visit( AST::FunctionDeclaration & function_declaration ) override; virtual void Visit( AST::ArgumentList & argument_list ) override; virtual void Visit( AST::Argument & argument ) override; }; } #endif
99f0c217679ce35e929aa98defab3be8a93b2ffd
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
/contact/contact_table.cc
9182b0968c5a79bb9333a7bbe5c69b9e35890585
[ "BSD-3-Clause" ]
permissive
ric2b/Vivaldi-browser
388a328b4cb838a4c3822357a5529642f86316a5
87244f4ee50062e59667bf8b9ca4d5291b6818d7
refs/heads/master
2022-12-21T04:44:13.804535
2022-12-17T16:30:35
2022-12-17T16:30:35
86,637,416
166
41
BSD-3-Clause
2021-03-31T18:49:30
2017-03-29T23:09:05
null
UTF-8
C++
false
false
5,943
cc
contact_table.cc
// Copyright (c) 2017 Vivaldi Technologies AS. All rights reserved // // Based on code that is: // // 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 "contact/contact_table.h" #include <string> #include <vector> #include "base/strings/utf_string_conversions.h" #include "contact/contact_type.h" #include "sql/statement.h" namespace contact { namespace { void FillContactRow(sql::Statement& statement, ContactRow* contact) { int id = statement.ColumnInt(0); std::u16string name = statement.ColumnString16(1); base::Time birthday = base::Time::FromInternalValue(statement.ColumnInt64(2)); std::u16string note = statement.ColumnString16(3); std::u16string avatar_url = statement.ColumnString16(4); int separator = statement.ColumnInt(5); int generated_from_sent_mail = statement.ColumnInt(6); bool trusted = statement.ColumnInt(7) == 1 ? true : false; contact->set_contact_id(id); contact->set_name(name); contact->set_birthday(birthday); contact->set_note(note); contact->set_avatar_url(avatar_url); contact->set_separator(separator == 1 ? true : false); contact->set_generated_from_sent_mail(generated_from_sent_mail == 1 ? true : false); contact->set_trusted(trusted); } } // namespace ContactTable::ContactTable() {} ContactTable::~ContactTable() {} bool ContactTable::CreateContactTable() { const char* name = "contacts"; if (GetDB().DoesTableExist(name)) return true; std::string sql; sql.append("CREATE TABLE "); sql.append(name); sql.append( "(" "id INTEGER PRIMARY KEY AUTOINCREMENT," // Using AUTOINCREMENT is for sync propose. Sync uses this |id| as an // unique key to identify the Contact. If here did not use // AUTOINCREMEclNT, and Sync was not working somehow, a ROWID could be // deleted and re-used during this period. Once Sync come back, Sync would // use ROWIDs and timestamps to see if there are any updates need to be // synced. And sync // will only see the new Contact, but missed the deleted Contact. "fn LONGVARCHAR," "birthday INTEGER," // Timestamp since epoch "note LONGVARCHAR," "avatar_url LONGVARCHAR," "separator INTEGER," "generated_from_sent_mail INTEGER DEFAULT 0," "last_used INTEGER," // Timestamp since epoch since you either sent or // received an email for given contact "trusted INTEGER DEFAULT 0," "created INTEGER," "last_modified INTEGER" ")"); bool res = GetDB().Execute(sql.c_str()); return res; } ContactID ContactTable::CreateContact(ContactRow row) { sql::Statement statement( GetDB().GetCachedStatement(SQL_FROM_HERE, "INSERT INTO contacts " "(fn, birthday, note, avatar_url, separator, " "generated_from_sent_mail, trusted, created, " "last_modified) " "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")); statement.BindString16(0, row.name()); statement.BindInt64(1, row.birthday().ToInternalValue()); statement.BindString16(2, row.note()); statement.BindString16(3, row.avatar_url()); statement.BindInt(4, row.separator() ? 1 : 0); statement.BindInt(5, row.generated_from_sent_mail() ? 1 : 0); statement.BindInt(6, row.trusted() ? 1 : 0); int created = base::Time().Now().ToInternalValue(); statement.BindInt64(7, created); statement.BindInt64(8, created); if (!statement.Run()) { return 0; } return GetDB().GetLastInsertRowId(); } bool ContactTable::GetAllContacts(ContactRows* contacts) { contacts->clear(); sql::Statement s(GetDB().GetCachedStatement( SQL_FROM_HERE, "SELECT id, fn, birthday, note, avatar_url, separator, " "generated_from_sent_mail, trusted FROM contacts")); while (s.Step()) { ContactRow contact; FillContactRow(s, &contact); contacts->push_back(contact); } return true; } bool ContactTable::UpdateContactRow(const ContactRow& contact) { sql::Statement statement( GetDB().GetCachedStatement(SQL_FROM_HERE, "UPDATE contacts SET fn=?, birthday=?, " "note=?, avatar_url=?, separator=?, " "generated_from_sent_mail=?, trusted=?, " "last_modified=? WHERE id=?")); statement.BindString16(0, contact.name()); statement.BindInt64(1, contact.birthday().ToInternalValue()); statement.BindString16(2, contact.note()); statement.BindString16(3, contact.avatar_url()); statement.BindInt(4, contact.separator() == true ? 1 : 0); statement.BindInt(5, contact.generated_from_sent_mail() == true ? 1 : 0); statement.BindInt(6, contact.trusted() == true ? 1 : 0); statement.BindInt64(7, base::Time().Now().ToInternalValue()); statement.BindInt64(8, contact.contact_id()); return statement.Run(); } bool ContactTable::DeleteContact(contact::ContactID contact_id) { sql::Statement statement(GetDB().GetCachedStatement( SQL_FROM_HERE, "DELETE from contacts WHERE id=?")); statement.BindInt64(0, contact_id); return statement.Run(); } bool ContactTable::GetRowForContact(ContactID contact_id, ContactRow* out_contact) { sql::Statement statement(GetDB().GetCachedStatement( SQL_FROM_HERE, "SELECT id, fn, birthday, note, avatar_url, " "separator, generated_from_sent_mail, trusted, created, " "last_modified FROM contacts WHERE id=?")); statement.BindInt64(0, contact_id); if (!statement.Step()) return false; FillContactRow(statement, out_contact); return true; } } // namespace contact
0471008040f5b2590caa62c4fd18f11d89ef4e35
550e9c4a8d56d47aaf1df2e15a71cd4cd35d16b9
/2out/NamedTest.cpp
010f609122e62c2a741950273d468f0b907fb0bc
[ "MIT" ]
permissive
DronMDF/2out
6ceadcdf74c63e46d8f5c769a619ce76afc162c5
d41a8e8ca6bfb5c66a8b77cd62ac9ab69e61b295
refs/heads/master
2021-09-08T11:49:15.507642
2021-09-05T06:31:16
2021-09-05T06:31:16
91,911,330
12
3
MIT
2021-09-05T06:31:17
2017-05-20T19:23:16
C++
UTF-8
C++
false
false
816
cpp
NamedTest.cpp
// Copyright (c) 2017-2021 Andrey Valyaev <dron.valyaev@gmail.com> // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #include "NamedTest.h" #include "NamedResult.h" #include "SuiteTest.h" using namespace std; using namespace oout; NamedTest::NamedTest(const string &name, const shared_ptr<const Test> &test) : name(name), test(test) { } NamedTest::NamedTest(const string &name, const shared_ptr<const NamedTest> &test) : NamedTest(name, make_shared<const SuiteTest>(test)) { } NamedTest::NamedTest(const string &name, const list<shared_ptr<const Test>> &tests) : NamedTest(name, make_shared<const SuiteTest>(tests)) { } unique_ptr<const Result> NamedTest::result() const { return make_unique<NamedResult>(name, test->result()); }
de355211cc666a4074bcc5ab2f0ac40c02733886
82e6375dedb79df18d5ccacd048083dae2bba383
/src/main/y/hashing/digest.cpp
3fdbe67f52d6f6801efaaa1e5f06c9363ef2c616
[]
no_license
ybouret/upsylon
0c97ac6451143323b17ed923276f3daa9a229e42
f640ae8eaf3dc3abd19b28976526fafc6a0338f4
refs/heads/master
2023-02-16T21:18:01.404133
2023-01-27T10:41:55
2023-01-27T10:41:55
138,697,127
0
0
null
null
null
null
UTF-8
C++
false
false
7,975
cpp
digest.cpp
#include "y/hashing/digest.hpp" #include "y/code/utils.hpp" #include "y/string.hpp" #include "y/exception.hpp" #include "y/memory/allocator/pooled.hpp" #include "y/ios/ostream.hpp" namespace upsylon { bool digest:: UPPER_CASE = false; static inline uint8_t * __digest_acquire( size_t &blen ) { static memory::allocator &mgr = memory::pooled::instance(); if(blen) { return static_cast<uint8_t *>( mgr.acquire(blen) ); } else { return NULL; } } void digest:: ldz() throw() { memset(byte,0,size); } #define Y_DIGEST_CTOR(SZ) \ object(), \ counted_object(), \ memory::rw_buffer(), \ ios::serializable(), \ size(SZ), \ blen(size), \ byte( __digest_acquire(blen) ) digest:: digest( const size_t n, const uint8_t b) : Y_DIGEST_CTOR(n) { memset(byte,b,size); } digest:: ~digest() throw() { assert( memory::pooled::exists() ); static memory::allocator &mgr = memory::pooled::location(); ldz(); { void *p = byte; mgr.release(p,blen); } byte = 0; } const void * digest:: ro() const throw() { return byte; } size_t digest:: length() const throw() { return size; } uint8_t & digest:: operator[]( const size_t i ) throw() { assert(i<size); return byte[i]; } const uint8_t & digest:: operator[]( const size_t i ) const throw() { assert(i<size); return byte[i]; } std::ostream & digest:: display( std::ostream &os ) const { if( digest::UPPER_CASE ) { for(size_t i=0;i<size;++i) { os << hexadecimal::uppercase[ byte[i] ]; } } else { for(size_t i=0;i<size;++i) { os << hexadecimal::lowercase[ byte[i] ]; } } return os; } digest::digest( const digest &other ) : Y_DIGEST_CTOR(other.size) { memcpy(byte,other.byte,size); } digest & digest:: operator=( const digest &other ) throw() { if(this!=&other) { if(size<=other.size) { memcpy(byte,other.byte,size); } else { assert(other.size<size); memcpy(byte,other.byte,other.size); memset(byte+other.size,0,size-other.size); } } return *this; } digest & digest:: operator=( const memory::ro_buffer &other) throw() { const memory::ro_buffer &self = *this; if( &self != &other ) { const size_t olen = other.length(); if(size<=olen) { memcpy(byte,other.ro(),size); } else { memcpy(byte,other.ro(),olen); memset(byte+olen,0,size-olen); } } return *this; } static inline uint8_t __digest_hex2dec(const char c) { const int value = hexadecimal::to_decimal(c); if(value<0) throw exception("digest::hexadecimal(invalid char '%s')", cchars::visible[ uint8_t(c) ]); return uint8_t(value); } static inline uint8_t __digest_word(const char * &text) { assert(text); const uint8_t hi = __digest_hex2dec(*(text++)); const uint8_t lo = __digest_hex2dec(*(text++)); return (hi<<4) | lo; } digest digest:: hex(const char *txt, const size_t len) { assert(!(0==txt&&len>0)); if(len&0x1) { size_t w = (len+1)>>1; digest d(w); d[0] = __digest_hex2dec(txt[0]); ++txt; size_t i=1; for(--w;w>0;--w,++i) { d[i] = __digest_word(txt); } return d; } else { size_t w = len>>1; digest d(w); size_t i=0; for(;w>0;--w,++i) { d[i] = __digest_word(txt); } return d; } } digest digest:: hex(const char *text) { return hex(text,length_of(text)); } digest digest::hex( const string &s ) { return hex(*s,s.size()); } bool operator==( const digest &lhs, const digest &rhs) throw() { if(lhs.size==rhs.size) { for(size_t i=0;i<lhs.size;++i) { if(lhs[i]!=rhs[i]) return false; } return true; } else { return false; } } bool operator!=( const digest &lhs, const digest &rhs) throw() { if(lhs.size==rhs.size) { for(size_t i=0;i<lhs.size;++i) { if(lhs[i]!=rhs[i]) return true; } return false; } else { return true; } } void digest:: _xor( const digest &other ) throw() { assert(size==other.size); for(size_t i=0;i<size;++i) { byte[i] ^= other.byte[i]; } } void digest:: _xor( const digest &lhs, const digest &rhs) throw() { assert(size==lhs.size); assert(size==rhs.size); for(size_t i=0;i<size;++i) { byte[i] = lhs.byte[i] ^ rhs.byte[i]; } } void digest:: _swp( digest &other ) throw() { assert(size==other.size); for(size_t i=0;i<size;++i) { cswap(byte[i],other.byte[i]); } } void digest:: _inc(const uint8_t delta) throw() { unsigned sum = delta; for(size_t i=0;i<size;++i) { sum += byte[i]; byte[i] = (sum&0xff); sum >>= 8; } } void digest:: _inc() throw() { _inc(1); } void digest:: _set( const digest &other ) throw() { assert(size==other.size); memcpy(byte,other.byte,size); } const char digest:: CLASS_NAME[] = "digest"; const char * digest:: className() const throw() { return CLASS_NAME; } size_t digest:: serialize( ios::ostream &fp ) const { return fp.write_block(*this); } digest digest:: read(ios::istream &fp, size_t &nr, const string &which) { static const char fn[] = "digest::read"; // read size size_t nr_size = 0; size_t md_size = 0; if( !fp.query_upack(md_size,nr_size) ) throw exception("%s(missing size ofr '%s')",fn,*which); // read content digest md(md_size,0); assert(md_size==md.size); const size_t nr_data = fp.try_query(md.byte,md.size); if(nr_data!=md.size) throw exception("%s(missing data for '%s')",fn,*which); //update and return nr = nr_size+nr_data; return md; } bool digest:: equals_hex(const char *txt, const size_t len) const { const digest &lhs = *this; const digest rhs = hex(txt,len); return lhs==rhs; } bool digest:: equals_hex(const char *s) const { const digest &lhs = *this; const digest rhs = hex(s); return lhs==rhs; } bool digest:: equals_hex(const string &s) const { const digest &lhs = *this; const digest rhs = hex(s); return lhs==rhs; } } #include "y/randomized/bits.hpp" namespace upsylon { void digest:: rand() throw() { static randomized::bits & ran = randomized::bits::crypto(); Y_LOCK( randomized::bits::access() ); for(size_t i=0;i<size;++i) { byte[i] = ran.full<uint8_t>(); } } }
cd9101adc9f0e01c01bfdfba4990b89c400cc5ce
9f4fccc004fd85bdecea7c5c353cf690b08052c7
/Sorting_Algorithm/quick_sort.cpp
4f522d928d69517f15d317df3f9060a72f248a62
[]
no_license
Rawat-Sagar/LOVE-BABBAR-450-DSA
40bf1fc11864708d1be99f9171974590661ac303
d740e3a7be1702d8689a4d0a34174c9259657aee
refs/heads/main
2023-05-07T09:48:46.851698
2021-06-01T05:37:54
2021-06-01T05:37:54
334,354,530
1
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
quick_sort.cpp
// Quick Sort Complexity : // Depends on pivot. // 1.In best case , pivot would be median element. // T(n) = 2T(n/2) + (n) // The solution of above recurrence is O(nLogn). It can be solved using case 2 of Master Theorem. // 2.In worst case , pivot would be end element. // T(n) = T(n-1) + n // The solution of above recurrence is O(n**2). #include <bits/stdc++.h> using namespace std; void swap(int arr[] , int i , int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } int partition(int arr[] , int l, int r) { int pivot = arr[r]; int i = l-1; for(int j=l ; j<r;j++) { if(arr[j]<pivot) { i++; swap(arr,i,j); } } swap(arr,i+1,r); return i+1; } void quickSort(int arr[] , int l, int r) { if(l<r) { int pi = partition(arr,l,r); quickSort(arr,l,pi-1); quickSort(arr,pi+1,r); } } int main() { int arr[] = {2,3,5,8,4,6,9,7,1,}; int n = sizeof(arr)/sizeof(arr[0]); // r = size(n) - 1 ; quickSort(arr,0,n-1); for(int i=0 ; i<n; i++) { cout<<arr[i]<<" "; } return 0; }
c9241d75e9b7a0a7022ad12b8cb3aa20bb8b6ea7
b162de01d1ca9a8a2a720e877961a3c85c9a1c1c
/871.minimum-number-of-refueling-stops.cpp
8e6c4b31e319a8f97ccdf4cd41a426b6288519be
[]
no_license
richnakasato/lc
91d5ff40a1a3970856c76c1a53d7b21d88a3429c
f55a2decefcf075914ead4d9649d514209d17a34
refs/heads/master
2023-01-19T09:55:08.040324
2020-11-19T03:13:51
2020-11-19T03:13:51
114,937,686
0
0
null
null
null
null
UTF-8
C++
false
false
2,433
cpp
871.minimum-number-of-refueling-stops.cpp
/* * [902] Minimum Number of Refueling Stops * * https://leetcode.com/problems/minimum-number-of-refueling-stops/description/ * * algorithms * Hard (27.13%) * Total Accepted: 5.2K * Total Submissions: 19K * Testcase Example: '1\n1\n[]' * * A car travels from a starting position to a destination which is target * miles east of the starting position. * * Along the way, there are gas stations.  Each station[i] represents a gas * station that is station[i][0] miles east of the starting position, and has * station[i][1] liters of gas. * * The car starts with an infinite tank of gas, which initially has startFuel * liters of fuel in it.  It uses 1 liter of gas per 1 mile that it drives. * * When the car reaches a gas station, it may stop and refuel, transferring all * the gas from the station into the car. * * What is the least number of refueling stops the car must make in order to * reach its destination?  If it cannot reach the destination, return -1. * * Note that if the car reaches a gas station with 0 fuel left, the car can * still refuel there.  If the car reaches the destination with 0 fuel left, it * is still considered to have arrived. * * * * * Example 1: * * * Input: target = 1, startFuel = 1, stations = [] * Output: 0 * Explanation: We can reach the target without refueling. * * * * Example 2: * * * Input: target = 100, startFuel = 1, stations = [[10,100]] * Output: -1 * Explanation: We can't reach the target (or even the first gas station). * * * * Example 3: * * * Input: target = 100, startFuel = 10, stations = * [[10,60],[20,30],[30,30],[60,40]] * Output: 2 * Explanation: * We start with 10 liters of fuel. * We drive to position 10, expending 10 liters of fuel. We refuel from 0 * liters to 60 liters of gas. * Then, we drive from position 10 to position 60 (expending 50 liters of * fuel), * and refuel from 10 liters to 50 liters of gas. We then drive to and reach * the target. * We made 2 refueling stops along the way, so we return 2. * * * * * Note: * * * 1 <= target, startFuel, stations[i][1] <= 10^9 * 0 <= stations.length <= 500 * 0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < * target * * * * * */ class Solution { public: int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) { } };
7044deeaee534f2ebeafcc85439303b5ad3b3ea3
3193195d1b08ce84e57957c1385e9e3756e42d9e
/set1/2.cpp
b080dbb696c4ff111d4aba831b04fa51efaec5b4
[]
no_license
jmkjohns/Cryptopals
8bb8872be357d4c13ab727e09369354919693822
781ab123fd468dfc73d2ec6e6d9cc429f2fb328e
refs/heads/master
2021-07-21T09:42:40.582454
2017-11-01T09:23:58
2017-11-01T09:23:58
107,012,177
0
0
null
null
null
null
UTF-8
C++
false
false
426
cpp
2.cpp
#include "..\Common\CryptoLib.cpp" //============================================================================== int main( int argc, char *argv[] ) //============================================================================== { ByteStream one = hexToBytes( "1c0111001f010100061a024b53535009181c" ); ByteStream two = hexToBytes( "686974207468652062756c6c277320657965" ); printHex( fixedXOR( one, two ) ); }
108411c714ea72144da32267bfe50157f6000f4f
98a283daef91a5c6381708ffa41966f0a9dd88a2
/Unique Binary Search Trees II.cpp
907d6c77f21ddd496685271ee9af8545d3396599
[]
no_license
shadowmydx/leetcode
b5aa9b00ad91fe66d9ec026f1b371098a44dbf5e
d907e38cb210669cb74478341a4ee4c8b79bebdd
refs/heads/master
2021-01-13T02:04:16.767790
2014-11-15T16:21:07
2014-11-15T16:21:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,347
cpp
Unique Binary Search Trees II.cpp
class Solution { public: vector<TreeNode *> generateTrees(int n) { vector<int> number; vector<TreeNode *> res; for (int i = 0;i < n;i++) number.push_back(i + 1); buildTree(res,number,0,number.size()); return res; } // left and right vec is the last call's vec to find a tree; void buildTree(vector<TreeNode *> &frompare,vector<int> &num,int start,int fin) { if (start >= fin) { frompare.push_back(NULL); return; } TreeNode *root; vector<TreeNode *> myleft; vector<TreeNode *> myright; for (int i = start;i < fin;i++) { int now = i; buildTree(myleft,num,start,i); buildTree(myright,num,i+1,fin); for (int i = 0;i < myleft.size();i++) { for (int j = 0;j < myright.size();j++) { root = (TreeNode *)malloc(sizeof(TreeNode)); // 'cause every tree has his rootnode...-3- root->val = num[now]; root->left = myleft[i]; root->right = myright[j]; frompare.push_back(root); } } myright.clear(); myleft.clear(); } } };
43c29f557e5d6eaa2cc1e46354d2686b3cf1cb64
dad6a8033f8412790cbf9c2cb1a27064689875a7
/SKWIN/SkwinSDL.h
67500dc64cecc7d44f6d7bdf46cb321b0fabf3a3
[]
no_license
gbsphenx/skproject
d95b28221187ada06b12dfa7550c5540bdf262dc
48fb31883df76ecff0b6ebe533c89f779b66b12c
refs/heads/master
2023-09-04T10:57:47.634857
2023-09-01T17:15:56
2023-09-01T17:15:56
32,668,925
13
3
null
2022-12-07T17:22:37
2015-03-22T09:08:24
C++
UTF-8
C++
false
false
1,576
h
SkwinSDL.h
#ifndef _SKWINSDL_H_ #define _SKWINSDL_H_ #include <SDL.h> #include "SkWin.h" class CSkWinSDL : public CSkWin { public: // SDL_Surface *pScreen; U8 curMiceState; // void UpdateRect(i16 x, i16 y, i16 cx, i16 cy); void SndPlayHi(const U8 *buff, U32 buffSize, i8 vol); void SndPlayLo(const U8 *buff, U32 buffSize, i8 dX, i8 dY); bool ML(); U32 GetTickCount(); void Sleep(U32 millisecs); bool IsAvail(); void ShowMessage(const char *psz); bool AskMe(const char *psz); bool OpenAudio(); void CloseAudio(); U8 GetLang(); // CSkWinSDL(); bool CreateSurface(); void UpdateTitle(); public: // int spfact; protected: // int sxfact; U8 pressCtrl; // class SndBuf { public: void *pMem; int pos, len, dist; SndBuf(): pMem(NULL), pos(0), len(0) { } ~SndBuf() { if (pMem != NULL) free(pMem), pMem = NULL, pos = len = 0; } void Alloc(const void *pSrc, int cchSrc, int dist) { void *p = realloc(pMem, cchSrc); if (p != NULL) { pMem = p; this->dist = dist; for (int x=0; x<cchSrc; x++) ((U8 *)pMem)[x] = 0x80 +((const U8 *)pSrc)[x]; pos = 0; len = cchSrc; } } bool IsFree() const { return pos == len; } bool IsOnline() const { return pos != len; } }; // SDL_AudioSpec asavail; #define MAX_SB 16U SndBuf sbs[MAX_SB]; // void paint(SDL_Surface *surface); void processMinput(U8 button, bool pressed, int x, int y); void processKinput(SDLKey nChar, bool press); static void sdlAudMix(void *userdata, Uint8 *stream, int len); void sdlAudMix(Uint8 *stream, int len); }; #endif // _SKWINSDL_H_
1af9f64ce614f8dae0c9310df85e7fd473030b59
14a93a8d9a75bb5a9d115e193931d6291910f054
/check.cpp
f6567d6ffc282721497bf452ba136bd3cb52eddd
[]
no_license
Sujay2611/Coding
94a4f24fa5665d807fb2a95f8aa67c7fa8e9e518
67d95d4183592cdb6f92e81f38a88664273e117a
refs/heads/master
2023-01-11T03:02:04.439617
2022-12-30T10:13:47
2022-12-30T10:13:47
244,128,290
0
0
null
null
null
null
UTF-8
C++
false
false
976
cpp
check.cpp
// // check.cpp // coding // // Created by sujay2611 on 25/07/20. // Copyright © 2020 sujay2611. All rights reserved. // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <cassert> #include <fstream> #include <string> using namespace std; int main() { int t,v,w,total; string s; char u; cin>>t; while (t--) { cin>>s; total=0; for(int i=0;i<s.size();) { u=s[i]; v=1; w=i+1; while(w<s.size() && s[i]==s[w]) { v+=1; w+=1; } while(v>0) { total+=1; v/=10; } total++; i=w; } cout<<total<<endl; if(total>=s.size()) { cout<<"NO"<<endl; } else { cout<<"YES"<<endl; } } return 0; }
a49024dc319445e687a334ade8128cb72c6c9237
e2a9835d3bc0b60177ca6b574b4a96e52868650b
/DragonBase.cpp
db8c514dbfaf44548f4d4d05ae23275bfef1e185
[]
no_license
ErinDuXiao/DragonMovementPrototypeUE4
356be3830e81cfd78795a06c519a93dcff4d4dfe
0f61a669eceae8ee18b14d96b2e39ed99bdd203e
refs/heads/master
2021-05-10T21:03:07.957559
2018-01-25T19:59:56
2018-01-25T19:59:56
118,217,166
0
0
null
null
null
null
UTF-8
C++
false
false
4,110
cpp
DragonBase.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "DragonBase.h" #include "Kismet/KismetMathLibrary.h" #include "Kismet/GameplayStatics.h" // Sets default values ADragonBase::ADragonBase() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // Set default values to setup this class. CurrentSpeed = 1.0f; InitialLength = 10; Speed = 1.0f; TurnSpeed = 1.0f; BalancingSpeed = 1.0f; WaveSpeed = 300.0f; WaveScale = 0.01f; SpeedScale = 150.0f; MinDistanceOfSegments = 100.0f; } // Called when the game starts or when spawned void ADragonBase::BeginPlay() { Super::BeginPlay(); UWorld * const World = GetWorld(); // Guard from wrong setup if (HeadPartClass == nullptr || BodyPartClass == nullptr) { UE_LOG(LogTemp, Warning, TEXT("DragonBase is not setup properly.")); return; } // Instansiate head parts Head = World->SpawnActor<AActor>(HeadPartClass); // Move to spawn point Head->SetActorLocation(GetActorLocation()); // Attach the head to myself Head->AttachToActor(this, FAttachmentTransformRules(EAttachmentRule::KeepWorld, true)); // Initialize segments array Segments = TArray<class AActor*>(); // Add head to the body parts array Segments.Add(Head); FVector prev = Head->GetActorLocation(); // Append body parts for (int i = 1; i < InitialLength; i++) { AActor* segment = World->SpawnActor<AActor>(BodyPartClass); prev.Y = prev.Y + MinDistanceOfSegments; segment->SetActorLocation(prev); segment->SetActorScale3D(segment->GetActorScale() / (i / 3)); // Attach the segment to myself segment->AttachToActor(this, FAttachmentTransformRules(EAttachmentRule::KeepWorld, true)); // Add body parts to segments array Segments.Add(segment); prev = segment->GetActorLocation(); } } // Called every frame void ADragonBase::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (DebugNoMove) { return; } // Guard from wrong setup if (HeadPartClass == nullptr || BodyPartClass == nullptr) { UE_LOG(LogTemp, Warning, TEXT("DragonBase is not setup properly.")); return; } FindTarget(); Move(DeltaTime); } // TODO: Move this to AI Controller void ADragonBase::Move(float DeltaTime) { // Check if I know my target // Move head if (TargetLocation.IsZero()) return; TargetLocation.Z = FMath::Sin(GFrameNumber * WaveScale) * WaveSpeed + TargetLocation.Z; UE_LOG(LogTemp, Warning, TEXT("%d"), (int)GFrameNumber); Head->SetActorLocation(FMath::Lerp(Head->GetActorLocation(), TargetLocation, Speed / SpeedScale)); Head->SetActorRotation(UKismetMathLibrary::FindLookAtRotation(Head->GetActorLocation(), TargetLocation)); AActor* prevSegment = Head; // Move body parts for (int i = 1; i < Segments.Num(); i++) { AActor* currentSegment = Segments[i]; FVector currentLocation = currentSegment->GetActorLocation(); FVector prevLocation = prevSegment->GetActorLocation(); float distance = FVector::Dist(currentLocation, prevLocation); float alpha = DeltaTime * distance / MinDistanceOfSegments * CurrentSpeed; currentSegment->SetActorLocation(FMath::Lerp(currentLocation, prevLocation, alpha)); currentSegment->SetActorRotation(FMath::Lerp(currentSegment->GetActorRotation(), prevSegment->GetActorRotation(), alpha)); prevSegment = currentSegment; } } void ADragonBase::FindTarget() { // TODO: Find random in the world // Find player location APawn* player = UGameplayStatics::GetPlayerController(GetWorld(), 0)->GetPawn(); if (player) { TargetLocation = player->GetActorLocation(); } } int ADragonBase::GetTurnDirection(FVector forward, FVector location, FVector targetLocationVector) { FVector normalizedDelta = (location - targetLocationVector).GetSafeNormal(); float dotProduct = FVector::DotProduct(normalizedDelta, forward); FVector crossProduct = FVector::CrossProduct(normalizedDelta, forward); if (crossProduct.Z > 0) { // left return 1; } else if (crossProduct.Z < 0) { // right return -1; } // straight return 0; }
6a3a2352aea668c82ff3275b1b870d6fb9659b3e
53546284fd7d95c871f472731bb1ad52b69d7cdb
/23/F.cpp
40261f775ba63da11213381d6e61cc62fc696279
[]
no_license
BlackSamorez/cpp-algo
b5e42845ceac6378c983986f8c4d3f06d58ca5fc
961ec044dd648148453a7e35e219c6abb7ed9e0b
refs/heads/master
2023-01-24T22:41:34.571811
2020-12-11T10:32:40
2020-12-11T10:32:40
262,581,888
0
0
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
F.cpp
#include <iostream> #include <vector> #include <algorithm> #include <stdint.h> #include <set> using namespace std; int main(){ int n; cin >> n; vector<int> numbers(n); for (int i = 0; i < n; ++i){ cin >> numbers[i]; } set<vector<int>> answer; int req; cin >> req; for (int i = 0; i < n; ++i){ for (int j = i + 1; j < n; ++j){ for (int k = j + 1; k < n; ++k){ for (int p = k + 1; p < n; ++p){ if (numbers[i] + numbers[j] + numbers[k] + numbers[p] == req){ vector<int> squad; squad.push_back(numbers[i]); squad.push_back(numbers[j]); squad.push_back(numbers[k]); squad.push_back(numbers[p]); sort(squad.begin(), squad.end()); answer.insert(squad); } } } } } for (auto it = answer.begin(); it != answer.end(); ++it){ cout << (*it)[0] <<" "<< (*it)[1] << " " << (*it)[2] << " " << (*it)[3] << "\n"; } //O(n^4), класс return 0; }
3de9b1743711d9d81c8107ba2e153637c1a1abbe
1fb357bb753988011e0f20c4ca8ec6227516b84b
/Flavour/src/BR_Kmumu.h
1981c4421eec12620e836a7f65f2fb23eaa75a2c
[ "DOC" ]
permissive
silvest/HEPfit
4240dcb05938596558394e97131872269cfa470e
cbda386f893ed9d8d2d3e6b35c0e81ec056b65d2
refs/heads/master
2023-08-05T08:22:20.891324
2023-05-19T09:12:45
2023-05-19T09:12:45
5,481,938
18
11
null
2022-05-15T19:53:40
2012-08-20T14:03:58
C++
UTF-8
C++
false
false
1,931
h
BR_Kmumu.h
/* * Copyright (C) 2012 HEPfit Collaboration * * * For the licensing terms see doc/COPYING. */ #ifndef BR_KMUMU_H #define BR_KMUMU_H #include "ThObservable.h" #include "OrderScheme.h" #include "gslpp.h" #include "CPenguinBoxMu.h" class StandardModel; /** * @class BR_Kmumu * @ingroup Flavour * @brief A class for the branching ratio of \f$K\to\mu^+\mu^-\f$ * @author HEPfit Collaboration * @copyright GNU General Public License * @details This class is used to compute the theoretical value of * the branching ratio of \f$K\to\mu^+\mu^-\f$. * * * * @anchor BR_Kmumu * <h3>%Model parameters</h3> * * The model parameters of %BR_Kmumu are summarized below: * <table class="model"> * <tr> * <th>Label</th> * <th>LaTeX symbol</th> * <th>Description</th> * </tr> * <tr> * <td class="mod_name">%Br_Kp_munu</td> * <td class="mod_symb">@f$\mathrm{BR}(K^+\to\mu^+\nu)@f$</td> * <td class="mod_desc">The experimental value for the branching ratio of \f$K^+\to\mu^+\nu\f$.</td> * </tr> * <tr> * <td class="mod_name">%DeltaP_cu</td> * <td class="mod_symb">@f$@f$</td> * <td class="mod_desc">The long-distance correction to the charm contribution of \f$K^+\to\pi^+\nu\bar{\nu}\f$.</td> * </tr> * </table> * */ class BR_Kmumu : public ThObservable { public: /** * constructor * @param Flavour */ BR_Kmumu(StandardModel& SM_i); /** * * @return theoretical value of |\f$ BR(K_L \rightarrow \mu \bar{\mu}) \f$|, * for example see hep-ph/0603079 section 2.3 */ double computeThValue(); protected: /** * * @param order * @param order_qed * @return the short distance contribution to the * |\f$ BR(K_L \rightarrow \mu \bar{\mu}) \f$|, */ gslpp::complex BRKmumu(orders order); private: StandardModel& mySM; CPenguinBoxMu CPB; }; #endif /* BR_KMUMU_H */
aef916268d7cb9c83f5f26bdc9fefd722e567bff
3b5241d097e6abeb5359ba147f2bd17471d94ec9
/Lab/Lab022218/Savitch_9thEd_Chap1_ProgProj4_freefall/main.cpp
c8e8b5c610045d73b003e15214bc4f9dc84a4f63
[]
no_license
elisechue/ChueElise_CSC5_Spring2018
19d80a4caa127763288d26001003d141f90f7387
72bc0b64b458cda76f50e5cf87580bc96cda6dd9
refs/heads/master
2018-09-10T05:42:28.021679
2018-06-05T08:52:16
2018-06-05T08:52:16
124,119,545
0
0
null
null
null
null
UTF-8
C++
false
false
1,064
cpp
main.cpp
/* * File: main.cpp * Author: Elise Chue * Created on February 22, 2018, 12:17 PM * Purpose: Calculate distance of object in Free Fall assuming no drag */ //System Libraries Here #include <iostream> using namespace std; //User Libraries Here //Global Constants Only, No Global Variables //Math, Physics, Science, Conversions, 2-D Array Columns const float GRAVITY=32.174; //in feet/sec^2 //Function Prototypes //Program Execution Begins Here int main(int argc, char** argv) { //Declare all Variables, no doubles float d, //distance in feet //float a - would have been for acceleration t; //time in seconds //Input or initialize values //a in this case would have been GRAVITY cout<<"Input the amount of time object was falling (in seconds)" <<endl; cin>>t; d=(GRAVITY*(t*t))/2; //Map/Process/Calculations, Inputs to Outputs //Display Outputs cout<<"The distance the object fell is "<<d<<" feet"<<endl; //Exit Program! return 0; }
1d9850e3c8953c16e13bc3f6727dca0cff62e144
332f9ba2997fcced6df503e4ce3bd827e117de6e
/include/jules/array/slicing/absolute.hpp
8adfb7de4a216d7678e5972161255a73589d5d3e
[ "Zlib" ]
permissive
mutual-ai/jules
c1138672abaf69cbd880a10d92aa276e872d1907
ce2417d90606cc0ba0868be56f6b67d6aa235afd
refs/heads/master
2020-03-11T00:38:38.118603
2017-10-11T15:26:33
2017-10-11T15:26:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,384
hpp
absolute.hpp
// Copyright (c) 2017 Filipe Verri <filipeverri@gmail.com> #ifndef JULES_ARRAY_SLICING_ABSOLUTE_H #define JULES_ARRAY_SLICING_ABSOLUTE_H #include <jules/core/type.hpp> namespace jules { inline namespace slicing { struct absolute_strided_slice { absolute_strided_slice() = delete; constexpr absolute_strided_slice(index_t start, index_t extent, index_t stride) noexcept : start{start}, extent{extent}, stride{stride} {} index_t start; index_t extent; index_t stride; }; struct absolute_slice { absolute_slice() = delete; constexpr absolute_slice(index_t start, index_t extent) noexcept : start{start}, extent{extent} {} constexpr operator absolute_strided_slice() const noexcept { return {start, extent, 1u}; } index_t start; index_t extent; }; static inline constexpr auto slice(index_t start, index_t extent) noexcept -> absolute_slice { return {start, extent}; } static inline constexpr auto slice(index_t start, index_t extent, index_t stride) noexcept -> absolute_strided_slice { return {start, extent, stride}; } static inline constexpr auto eval(absolute_slice slice, index_t) noexcept -> absolute_slice { return slice; } static inline constexpr auto eval(absolute_strided_slice slice, index_t) noexcept -> absolute_strided_slice { return slice; } } // namespace slicing } // namespace jules #endif // JULES_ARRAY_SLICING_ABSOLUTE_H
b0a0e988a1734e40923fe90b20ca83960c7da1a5
25d01103cdceffd02aa09607791fc85708ba6d50
/NJUPT_2018_SpringTraining/NJUPT_2018_SpringTraining_3/B_Highway/main.cpp
f540df6a2368fa28b138994bcfe0da1b0f1990df
[]
no_license
MoonChasing/ACM
3aea87957c695eec5dced21e0cc53c2fcb0fe3e6
aa5878646a47bf258cb2698d5068edb57fe1d03e
refs/heads/master
2020-03-24T13:07:31.432360
2019-02-27T14:53:10
2019-02-27T14:53:10
142,735,585
0
0
null
null
null
null
UTF-8
C++
false
false
1,609
cpp
main.cpp
#include <cstdio> #include <cstring> #include <cstdlib> #include <iostream> #include <set> #include <map> #include <queue> #include <vector> #include <utility> #include <algorithm> #define MAXN 755 #define MAXM 1005 #define INF 0x3f3f3f3f #define DEBUG #define DataIn typedef long long LL; using namespace std; int n,m; int cost[MAXN][MAXN]; int x[MAXN], y[MAXN]; bool vis[MAXN]; int dis[MAXN]; int path[MAXN]; void prim() { memset(vis, false, sizeof(vis)); for(int i=1; i<=n; i++) { dis[i] = cost[1][i]; path[i] = 1; } dis[1] = 0; vis[1] = true; for(int i=1; i<=n; i++) { int v=0; int minn = INF; for(int j=1; j<=n; j++) { if(!vis[j] && dis[j]<minn) { minn = dis[j]; v = j; } } vis[v] = true; if(cost[path[v]][v]) printf("%d %d\n", v, path[v]); for(int j=1; j<=n; j++) { if(!vis[j] && dis[j] > cost[v][j]) { dis[j] = cost[v][j]; path[j] = v; } } } } int main() { scanf("%d", &n); memset(cost, 0, sizeof(cost)); for(int i=1; i<=n; i++) { scanf("%d%d", &x[i], y+i); for(int j=1; j<=i; j++) { cost[i][j] = cost[j][i] = (x[i]-x[j]) * (x[i]- x[j]) + (y[i] - y[j])*(y[i] - y[j]); } } scanf("%d", &m); int v1,v2; for(int j=1; j<=m; j++) { scanf("%d%d", &v1, &v2); cost[v1][v2] = cost[v2][v1] = 0; } prim(); return 0; }
dc4c30dc79ec7b1f79fb1b89436c7633e206b9bd
41160548cbbe4222db6064d3ed6d6b902a70fe3f
/zork/Project2/exit.h
bfcb23a73269528b054a591b927bba7d5640008f
[]
no_license
mizquierdo97/Zork-
cdd028fe77a8e4743e7859c6b1cef24d85bd3835
f74946b7ca4ee7231eec524a668c24c0280fc6f3
refs/heads/master
2021-01-10T06:40:33.601425
2016-04-18T21:08:01
2016-04-18T21:08:01
52,227,312
0
0
null
null
null
null
UTF-8
C++
false
false
307
h
exit.h
#ifndef _EXIT #define _EXIT #include "entity.h" class Exit :public Entity{ public: Exit(); Exit(const char* name, const char* description, Room* origin, Room* destination, bool open, int direction); Room* origin; Room* destination; bool open; int direction; Room* get_destination()const; }; #endif
385b51e411adec05ddc5ea24957699090cdb5960
772d932a0e5f6849227a38cf4b154fdc21741c6b
/CPP_Joc_Windows_Android/SH_Client_Win_Cpp_Cmake/App/src/rpg3D/gw/entity/module/toolsHandler/tool/melleArea/TMA_UnitContacts.h
6969b29e4fc3e0ab263398e22b7740881b121316
[]
no_license
AdrianNostromo/CodeSamples
1a7b30fb6874f2059b7d03951dfe529f2464a3c0
a0307a4b896ba722dd520f49d74c0f08c0e0042c
refs/heads/main
2023-02-16T04:18:32.176006
2021-01-11T17:47:45
2021-01-11T17:47:45
328,739,437
0
0
null
null
null
null
UTF-8
C++
false
false
328
h
TMA_UnitContacts.h
#pragma once #include <base/gh.h> #include "TMA_Visual.h" namespace rpg3D { class TMA_UnitContacts : public TMA_Visual {priv typedef TMA_Visual super;pub dCtor(TMA_UnitContacts); pub explicit TMA_UnitContacts(ToolConfigMelleArea* config, std::shared_ptr<ExtraData> extraData); pub ~TMA_UnitContacts() override; }; };
46a06de2732c03c3a5c184838cf0e7dac8200c9f
ace20ae898aadf18c4ef8a2355b528422fc27bb5
/codeforces/catchoverflow.cpp
9dae2480e7f7447f39fbd1334ca6e45dae21ad7c
[]
no_license
pidddgy/competitive-programming
19fd79e7888789c68bf93afa3e63812587cbb0fe
ec86287a0a70f7f43a13cbe26f5aa9c5b02f66cc
refs/heads/master
2022-01-28T07:01:07.376581
2022-01-17T21:37:06
2022-01-17T21:37:06
139,354,420
0
3
null
2021-04-06T16:56:29
2018-07-01T19:03:53
C++
UTF-8
C++
false
false
753
cpp
catchoverflow.cpp
// https://codeforces.com/contest/1175/problem/B #include <bits/stdc++.h> using namespace std; #define endl '\n' int main() { #define int long long ios::sync_with_stdio(0); cin.sync_with_stdio(0); cin.tie(0); const int lim = pow(2, 32); stack<int> S; int l; cin >> l; S.push(1); int tot = 0; while(l--) { string type; cin >> type; if(type == "for") { int n; cin >> n; S.push(min(lim, S.top()*n)); } else if(type == "end") { S.pop(); } else if(type == "add") { tot += S.top(); } } if(tot >= lim) { cout << "OVERFLOW!!!" << endl; } else { cout << tot << endl; } }
08850b0f6c6234c19de1b4a35b8444280ec92e33
f0d7d208a2d2f93bf7cb5217e737ba066d31658f
/2019_W/Array/4344_overMean.cpp
c2ae48927968913c275fa17794fe3ece7e374918
[]
no_license
Aranch422/Algorithm_Study
c26f82bc7884886e1558edbb2c13799df946dddd
a61a546cc8ddce4fa51272aa9c42ba4933880a58
refs/heads/master
2023-07-23T17:13:13.827634
2023-07-07T15:53:56
2023-07-07T15:53:56
234,075,498
0
0
null
null
null
null
UTF-8
C++
false
false
533
cpp
4344_overMean.cpp
#include <iostream> using namespace std; int N,n; int num[1000]; void init(){ cin>>n; for(int i=0;i<n;i++){ cin>>num[i]; } } void solve(){ int sum=0; int mean=0; for(int i=0;i<n;i++){ sum+=num[i]; } mean=sum/n; double cnt=0; for(int i=0;i<n;i++){ if(mean<num[i]) cnt++; } cout<<cnt/n*100<<"%\n"; } int main(){ cout.setf(ios::fixed); cout.precision(3); cin>>N; for(int i=0;i<N;i++){ init(); solve(); } return 0; }
2e84b674815b523fda96ccb565485d815a353433
b7d4fc29e02e1379b0d44a756b4697dc19f8a792
/deps/icu4c/source/test/intltest/itercoll.h
747f80f6689c70847674b1ec5bac125c0548b462
[ "GPL-1.0-or-later", "MIT", "LicenseRef-scancode-unknown-license-reference", "ICU", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "NAIST-2003", "BSD-3-Clause", "LicenseRef-scancode-unicode", "GPL-3.0-or-later", "NTP", "LicenseRef-scancode-unicode-icu-58", "LicenseRef-scancode-autoconf-simple-exception" ]
permissive
vslavik/poedit
45140ca86a853db58ddcbe65ab588da3873c4431
1b0940b026b429a10f310d98eeeaadfab271d556
refs/heads/master
2023-08-29T06:24:16.088676
2023-08-14T15:48:18
2023-08-14T15:48:18
477,156
1,424
275
MIT
2023-09-01T16:57:47
2010-01-18T08:23:13
C++
UTF-8
C++
false
false
2,827
h
itercoll.h
/******************************************************************** * COPYRIGHT: * Copyright (c) 1997-2001, International Business Machines Corporation and * others. All Rights Reserved. ********************************************************************/ /** * Collation Iterator tests. * (Let me reiterate my position...) */ #ifndef _ITERCOLL #define _ITERCOLL #include "unicode/utypes.h" #if !UCONFIG_NO_COLLATION #include "unicode/tblcoll.h" #include "unicode/coleitr.h" #include "tscoll.h" class CollationIteratorTest: public IntlTestCollator { public: // If this is too small for the test data, just increase it. // Just don't make it too large, otherwise the executable will get too big enum EToken_Len { MAX_TOKEN_LEN = 16 }; CollationIteratorTest(); virtual ~CollationIteratorTest(); void runIndexedTest(int32_t index, UBool exec, const char* &name, char* par = NULL); /** * Test that results from CollationElementIterator.next is equivalent to * the reversed results from CollationElementIterator.previous, for the set * of BMP characters. */ void TestUnicodeChar(); /** * Test for CollationElementIterator.previous() * * @bug 4108758 - Make sure it works with contracting characters * */ void TestPrevious(/* char* par */); /** * Test for getOffset() and setOffset() */ void TestOffset(/* char* par */); /** * Test for setText() */ void TestSetText(/* char* par */); /** @bug 4108762 * Test for getMaxExpansion() */ void TestMaxExpansion(/* char* par */); /* * @bug 4157299 */ void TestClearBuffers(/* char* par */); /** * Testing the assignment operator */ void TestAssignment(); /** * Testing the constructors */ void TestConstructors(); /** * Testing the strength order functionality */ void TestStrengthOrder(); //------------------------------------------------------------------------ // Internal utilities // private: struct ExpansionRecord { UChar character; int32_t count; }; /** * Verify that getMaxExpansion works on a given set of collation rules */ void verifyExpansion(UnicodeString rules, ExpansionRecord tests[], int32_t testCount); /** * Return a string containing all of the collation orders * returned by calls to next on the specified iterator */ UnicodeString &orderString(CollationElementIterator &iter, UnicodeString &target); void assertEqual(CollationElementIterator &i1, CollationElementIterator &i2); RuleBasedCollator *en_us; const UnicodeString test1; const UnicodeString test2; }; #endif /* #if !UCONFIG_NO_COLLATION */ #endif
fc3ac738b6c92cdb95c9cc55f9e7562aef8067e0
e334e2d79cbb97d4de9e2c2b13daaa53156c9ee6
/src/image-generator/include/Server.h
9f024f41fa73f4a01722bf477b1f682e7d98b2a5
[]
no_license
ueberaccelerate/image-generator-server-client
f96e57e9d93a6c31f7ce85f30cd48bc3aabe8fbd
164809f9efe4e83b3480ec5b18840e1784974c04
refs/heads/master
2022-11-30T10:05:50.347889
2020-08-12T15:52:11
2020-08-12T15:52:11
286,090,226
0
0
null
null
null
null
UTF-8
C++
false
false
680
h
Server.h
#ifndef SENDER_INCLUDE_SERVER_HPP #define SENDER_INCLUDE_SERVER_HPP #include "Connection.h" #include <resource/config.hpp> #include <boost/asio.hpp> #include <boost/shared_ptr.hpp> namespace server { using boost::asio::ip::tcp; class ImageGeneratorServer { public: ImageGeneratorServer(boost::asio::io_context& io_context, const resource::Config& config); private: void start_accept(); void handle_accept(Connection::pointer new_connection, const boost::system::error_code& error); resource::Config config_; boost::asio::io_context& io_context_; tcp::acceptor acceptor_; Connection::pointer current_connection_; }; } #endif
2021ece1222912ad496931edb11758cc41b2adf6
e9e8064dd3848b85b65e871877c55f025628fb49
/code/MapEngine/MapDisp/MapDispLayer.cpp
713fbc68ce9e0d30fbf99ed198a44c025af78239
[]
no_license
xxh0078/gmapx
eb5ae8eefc2308b8ca3a07f575ee3a27b3e90d95
e265ad90b302db7da05345e2467ec2587e501e90
refs/heads/master
2021-06-02T14:42:30.372998
2019-08-29T02:45:10
2019-08-29T02:45:10
12,397,909
0
0
null
null
null
null
GB18030
C++
false
false
16,359
cpp
MapDispLayer.cpp
#include "stdafx.h" #include "MapDispLayer.h" #include "MapDisp.h" CMapDispLayer::CMapDispLayer(void) { m_iBlockCount = 0; } //创建图层 void CMapDispLayer::Create( CMapDisp* pMapDisp ) { m_hwnd = pMapDisp->m_hwnd; m_pMapDisp = pMapDisp; this->m_MapData.Init( pMapDisp ); //初始化所有数据块 /*for ( int i=0;i<_BLOCK_MAX_NUM;i++) { m_MapBlockUnit[i].Init(m_hwnd); }*/ //建立互斥区,并启动线程 return; //m_bExitProc = false; //m_hLoadMutex = CreateMutex( NULL,false,NULL ); //DWORD dwThreadID = 0; //HANDLE h = ::CreateThread( NULL,0 ,&CMapDispLayer::MapLoadProc,this,0,&dwThreadID ); //CloseHandle( h ); } CMapDispLayer::~CMapDispLayer(void) { } //检查当前的绘制列表中是否存在改绘制参数 bool CMapDispLayer::CheckParamInDrawList( CMapBlockUnit* pBlockParam, int iLevel, int iMinX, int iMaxX, int iMinY, int iMaxY ) { if( pBlockParam->lLevel == iLevel//xxh m_iLevel &&pBlockParam->lNumX >= iMinX && pBlockParam->lNumX <= iMaxX &&pBlockParam->lNumY >= iMinY && pBlockParam->lNumY <= iMaxY && pBlockParam->bDraw ) { return true; } else return false; } //加载地图数据 void CMapDispLayer::LoadMapData( int iLevel, MPoint& gptMapCenter,VOSRect& rcWnd, bool bZoom ) { return; /* VOSRect rcWnd; rcWnd.left = rcWnd1.left - rcWnd1.width(); rcWnd.top = rcWnd1.top - rcWnd1.width(); rcWnd.right = rcWnd1.right + rcWnd1.Height(); rcWnd.bottom = rcWnd1.bottom + rcWnd1.Height();*/ vchar strFileName[256]= {0}; // TODO: Add your message handler code here //MPoint gptMapCenter; //CMapBase::GetMapPoint( iLevel, m_MapCenter20, gptMapCenter ); // int iCenterOffsetX = rcWnd.width()/2 - gptMapCenter.lX % 256; int iCenterOffsetY = rcWnd.height()/2 - gptMapCenter.lY % 256; int iCenterX = gptMapCenter.lX / 256; int iCenterY = gptMapCenter.lY / 256; int iMapMinX = ( gptMapCenter.lX - rcWnd.width()/2 )/ 256 - 3;//5; int iMapMinY = ( gptMapCenter.lY - rcWnd.height()/2 )/ 256 - 2;//4; int iMapMaxX = ( gptMapCenter.lX + rcWnd.width()/2 )/ 256 + 3;//5; int iMapMaxY = ( gptMapCenter.lY + rcWnd.height()/2 )/ 256 + 2;//4; if( !bZoom ) { iMapMinX -= 4; iMapMinY -= 3; iMapMaxX += 4; iMapMaxY += 3; } //检查绘制列表,标记绘制绘制位 for ( int i=0;i<this->m_iBlockCount;i++ ) { if( CheckParamInDrawList( &m_MapBlockUnit[i],iLevel,iMapMinX,iMapMaxX, iMapMinY,iMapMaxY)) m_MapBlockUnit[i].bDraw = true; else m_MapBlockUnit[i].bDraw = false; } int z = iLevel; { for ( int y= iMapMinY ; y<=iMapMaxY; y++ ) { //检查是否超过范围 if ( z == 0 ) { if ( y < 0 || y >= 2>>(1-z) ) { continue; } } else { if ( y < 0 || y >= 2<<(z-1) ) { continue; } } for ( int x = iMapMinX ; x<= iMapMaxX ; x++ ) { if ( z == 0 ) { if ( x < 0 || x >= 2>>(1-z) ) { continue; } } else { if ( x < 0 || x >= 2<<(z-1) ) { continue; } } //检查数据是否被加载 bool bDataIsLoad = false; for ( int i=0;i<this->m_iBlockCount;i++ ) { if( m_MapBlockUnit[i].lLevel == iLevel &&m_MapBlockUnit[i].lNumX == x &&m_MapBlockUnit[i].lNumY==y && m_MapBlockUnit[i].bDraw ) { // m_MapBlockUnit[i].lStartX = iCenterOffsetX - (iCenterX - x )*256; // m_MapBlockUnit[i].lStartY = iCenterOffsetY - (iCenterY - y )*256; bDataIsLoad = true; break; } } //如果已经加载,则查找下一个 if( bDataIsLoad ) { continue; } else { //查找空的没有用的列表 CMapBlockUnit* pParam = NULL; int i = 0; for ( ;i<this->m_iBlockCount;i++ ) { if( !m_MapBlockUnit[i].bDraw ) { pParam = &m_MapBlockUnit[i]; break; } } if ( pParam == NULL ) { m_iBlockCount++; if ( m_iBlockCount >= _BLOCK_MAX_NUM ) { // ASSERT(0); m_iBlockCount = 0; } pParam = &m_MapBlockUnit[m_iBlockCount-1]; } //把要绘制的数据存入绘制列表 if( z == 7 ) { z = 7; if( x > 64 && x < 70 ) { z = 7; if( y > 64 && y < 70 ) { z = 7; } } } string strFileName; if( m_enMapType == GMAP_FILES ) GetMapPath(x,y,z,strFileName); else CMapBase::GetMapDataPath( x,y,z,strFileName,m_enMapType ); //CMapBase::GetMapDataEncryptionPath(x,y,z,strFileName,256); // TRACE("loadimg x=%d,y=%d,z=%d\r\n",x,y,z ); // GetEncryptionFileName( 1,x,y,z,strFileName ); //m_download.GetEncryptionFileName( x,y,z,strFileName); // if ( LoadPngData( strFileName, pParam ) ) //TRACE( strFileName.c_str() ); // if( GMAP_GOOGLE_IMAGE == m_enMapType || GMAP_GOOGLE_MARK == m_enMapType ) { if ( m_MapBlockUnit[i].LoadImg( strFileName ) ) { m_MapBlockUnit[i].lLevel = z; m_MapBlockUnit[i].lNumX = x; m_MapBlockUnit[i].lNumY = y; // m_MapBlockUnit[i].lStartX = iCenterOffsetX - (iCenterX - x )*256; // m_MapBlockUnit[i].lStartY = iCenterOffsetY - (iCenterY - y )*256; m_MapBlockUnit[i].bDraw = true; } else { if( m_enMapType != GMAP_FILES ) { // this->m_pMapDisp->m_MapDataDown.AddDownLoadList( x, y , z, m_enMapType ); } } } /*else { if ( m_MapBlockUnit[i].LoadPng( strFileName ) ) { m_MapBlockUnit[i].lLevel = z; m_MapBlockUnit[i].lNumX = x; m_MapBlockUnit[i].lNumY = y; m_MapBlockUnit[i].lStartX = iCenterOffsetX - (iCenterX - x )*256; m_MapBlockUnit[i].lStartY = iCenterOffsetY - (iCenterY - y )*256; m_MapBlockUnit[i].bDraw = true; } else { this->m_pMapDisp->m_MapDataDown.AddDownLoadList( x, y , z, m_enMapType ); } }*/ } } } } } //重新加载地图数据 void CMapDispLayer::ReLoadMapData( int iLevel, MPoint& gptMapCenter,VOSRect& rcWnd ) { for ( int i=0;i<this->m_iBlockCount;i++ ) { m_MapBlockUnit[i].bDraw = false; } LoadMapData(iLevel,gptMapCenter,rcWnd); } void CMapDispLayer::OnMoveMap( int iDx, int iDy ) { /* for ( int i=0;i<this->m_iBlockCount;i++ ) { if( m_MapBlockUnit[i].bDraw ) { m_MapBlockUnit[i].lStartX += iDx; m_MapBlockUnit[i].lStartY += iDy; } }*/ } void CMapDispLayer::OnDraw( HDC hdc,int iLevel, MPoint& gptMapCenter,VOSRect& rcWnd ) { unsigned long ultime = ::GetTickCount(); int iTimes = 0; if( !hdc ) return; m_MapData.m_MapDataDown.ClearNoDownLoadList(); int iCenterOffsetX = rcWnd.width()/2 - gptMapCenter.lX % 256; int iCenterOffsetY = rcWnd.height()/2 - gptMapCenter.lY % 256; int iCenterX = gptMapCenter.lX / 256; int iCenterY = gptMapCenter.lY / 256; int iMapMinX = ( gptMapCenter.lX - rcWnd.width()/2 )/ 256;//-3 int iMapMinY = ( gptMapCenter.lY - rcWnd.height()/2 )/ 256;//-2 int iMapMaxX = ( gptMapCenter.lX + rcWnd.width()/2 )/ 256;//+3 int iMapMaxY = ( gptMapCenter.lY + rcWnd.height()/2 )/ 256;//+2 //检查绘制列表,标记绘制绘制位 for ( int i=0;i<this->m_iBlockCount;i++ ) { if( CheckParamInDrawList( &m_MapBlockUnit[i],iLevel,iMapMinX,iMapMaxX, iMapMinY,iMapMaxY)) m_MapBlockUnit[i].bDraw = true; else m_MapBlockUnit[i].bDraw = false; } int z = iLevel; { for ( int y= iMapMinY ; y<=iMapMaxY; y++ ) { //检查是否超过范围 if ( z == 0 ) { if ( y < 0 || y >= 2>>(1-z) ) { continue; } } else { if ( y < 0 || y >= 2<<(z-1) ) { continue; } } for ( int x = iMapMinX ; x<= iMapMaxX ; x++ ) { if ( z == 0 ) { if ( x < 0 || x >= 2>>(1-z) ) { continue; } } else { if ( x < 0 || x >= 2<<(z-1) ) { continue; } } CMapBlockUnit* pBlock = this->m_MapData.GetMapBlockUnit( iLevel, x,y, m_enMapType ); if(pBlock) pBlock->Draw( hdc,iCenterOffsetX - (iCenterX - x )*256,iCenterOffsetY - (iCenterY - y )*256); /* //检查数据是否被加载 bool bDataIsLoad = false; for ( int i=0;i<this->m_iBlockCount;i++ ) { if( m_MapBlockUnit[i].lLevel == iLevel &&m_MapBlockUnit[i].lNumX == x &&m_MapBlockUnit[i].lNumY==y && m_MapBlockUnit[i].bDraw ) { // m_MapBlockUnit[i].lStartX = iCenterOffsetX - (iCenterX - x )*256; // m_MapBlockUnit[i].lStartY = iCenterOffsetY - (iCenterY - y )*256; m_MapBlockUnit[i].Draw( hdc,iCenterOffsetX - (iCenterX - x )*256,iCenterOffsetY - (iCenterY - y )*256 ); bDataIsLoad = true; break; } // iTimes++; }*/ } } } //string strText = "客服QQ:214010522"; /*ultime = ::GetTickCount() - ultime; char chTemp[100]; sprintf(chTemp,"%d毫秒:%d次, path =%s",ultime,iTimes, m_strRootPath.c_str()); ::DrawText( hdc, chTemp,strlen(chTemp) ,&rcWnd,DT_LEFT | DT_TOP); for ( int i=0;i<this->m_iBlockCount;i++ ) { if( m_MapBlockUnit[i].bDraw ) { m_MapBlockUnit[i].Draw( hdc ); } }*/ } //设置地图类型 void CMapDispLayer::SetMapType( en_MapType eMapType, string strRootPath, string strMapName, string strMapURL ) { CMapBase::SetMapType( eMapType ); m_enMapType = eMapType; m_strRootPath = strRootPath; switch( m_enMapType ) { case GMAP_GOOGLE_MAP: m_strRootPath += _T("gugemap"); CreateDirectory( m_strRootPath.c_str(),NULL); break; case GMAP_GOOGLE_IMAGE:; m_strRootPath += _T("gugeimap"); CreateDirectory( m_strRootPath.c_str(),NULL); break; case GMAP_CHANGLIAN: m_strRootPath += _T("clmap"); CreateDirectory( m_strRootPath.c_str(),NULL); break; case GMAP_MAPABC: m_strRootPath += _T("mapabc"); CreateDirectory( m_strRootPath.c_str(),NULL); break; case GMAP_MAPBAR: m_strRootPath += _T("mapbar"); CreateDirectory( m_strRootPath.c_str(),NULL); break; case GMAP_MAP365: m_strRootPath += _T("map365"); CreateDirectory( m_strRootPath.c_str(),NULL); break; case GMAP_VM: m_strRootPath += _T("virtualearth"); CreateDirectory( m_strRootPath.c_str(),NULL); break; case GMAP_SUPERMAP: m_strRootPath += _T("SUPERMAP"); CreateDirectory( m_strRootPath.c_str(),NULL); break; case GMAP_MYMAP: { //m_enMapType = GMAP_MYMAP; m_strRootPath = strRootPath + strMapName; CreateDirectory( m_strRootPath.c_str(),NULL); m_strMapURL = strMapURL; } break; case GMAP_GOOGLE_MARK: { //影像标签 m_strRootPath += _T("gugemark"); CreateDirectory( m_strRootPath.c_str(),NULL); break; } case GMAP_GOOGLE_IMAGEMARK: { string strMarkPath = m_strRootPath; strMarkPath += _T("gugemark"); CreateDirectory( strMarkPath.c_str(),NULL); m_strRootPath += _T("gugeimap"); CreateDirectory( m_strRootPath.c_str(),NULL); break; } case GMAP_TIANDT: m_strRootPath += _T("TIANDT"); CreateDirectory( m_strRootPath.c_str(),NULL); break; default: ; } m_MapData.SetMapPath( m_strRootPath, m_enMapType ); //检查绘制列表,标记绘制绘制位 for ( int i=0;i<this->m_iBlockCount;i++ ) { m_MapBlockUnit[i].bDraw = false; } m_iBlockCount = 0; } //设置地图路径 void CMapDispLayer::SetMapPath( string strMapPath ) { m_enMapType = GMAP_FILES; m_strMapPath = strMapPath; m_MapData.SetMapPath( m_strMapPath, m_enMapType ); //检查绘制列表,标记绘制绘制位 for ( int i=0;i<this->m_iBlockCount;i++ ) { m_MapBlockUnit[i].bDraw = false; } m_iBlockCount = 0; } //得到地图文件路径 void CMapDispLayer::GetMapPath( int x,int y,int z,string& strMapPath ) { strMapPath = this->m_strMapPath; char cTemp[20]={0}; sprintf( cTemp,"%d",x); string flag = "%x"; string::size_type position = 0; while(1) { position = strMapPath.find( flag ); if( position != strMapPath.npos ) { strMapPath.replace( position,2,cTemp,strlen(cTemp)); } else break; } sprintf( cTemp,"%d",y); flag = "%y"; while(1) { position = strMapPath.find( flag ); if( position != strMapPath.npos ) { strMapPath.replace( position,2,cTemp,strlen(cTemp)); } else break; } sprintf( cTemp,"%d",z); flag = "%z"; position = 0; while(1) { position = strMapPath.find( flag ); if( position != strMapPath.npos ) { strMapPath.replace( position,2,cTemp,strlen(cTemp)); } else break; } } //获得地图数据文件路径 /* void CMapDispLayer::GetMapDataPath( int x, int y, int z, string& strMapFilePath ) { vchar temp[33]={0}; strMapFilePath = m_strRootPath; //创建比例尺文件目录 strMapFilePath += _T("\\level"); sprintf( temp,_T("%d\\"),z ); //strcat( pPath, temp ); strMapFilePath += temp; CreateDirectory( strMapFilePath.c_str(),NULL); //-----y坐标文件名 memset( temp,0,33); sprintf( temp,_T("%d\\"),y ); strMapFilePath += temp; CreateDirectory( strMapFilePath.c_str(),NULL); memset( temp,0,33); sprintf( temp,_T("%d.png"),x ); strMapFilePath += temp; }*/ //加载其他数据 void CMapDispLayer::LoadMapOther() { return; vchar strFileName[256]= {0}; // TODO: Add your message handler code here //MPoint gptMapCenter; //CMapBase::GetMapPoint( iLevel, m_MapCenter20, gptMapCenter ); // int iCenterOffsetX = m_pMapDisp->m_rcWnd.width()/2 - m_gptMapCenter.lX % 256; int iCenterOffsetY = m_pMapDisp->m_rcWnd.height()/2 - m_gptMapCenter.lY % 256; int iCenterX = m_gptMapCenter.lX / 256; int iCenterY = m_gptMapCenter.lY / 256; int iMapMinX = ( m_gptMapCenter.lX - m_pMapDisp->m_rcWnd.width()/2 )/ 256 - 5; int iMapMinY = ( m_gptMapCenter.lY - m_pMapDisp->m_rcWnd.height()/2 )/ 256 - 4; int iMapMaxX = ( m_gptMapCenter.lX + m_pMapDisp->m_rcWnd.width()/2 )/ 256 + 5; int iMapMaxY = ( m_gptMapCenter.lY + m_pMapDisp->m_rcWnd.height()/2 )/ 256 + 4; //检查绘制列表,标记绘制绘制位 for ( int i=0;i<this->m_iBlockCount;i++ ) { if( CheckParamInDrawList( &m_MapBlockUnit[i],m_iLevel,iMapMinX,iMapMaxX, iMapMinY,iMapMaxY)) m_MapBlockUnit[i].bDraw = true; else m_MapBlockUnit[i].bDraw = false; } int z = m_iLevel; { for ( int y= iMapMinY ; y<=iMapMaxY; y++ ) { //检查是否超过范围 if ( z == 0 ) { if ( y < 0 || y >= 2>>(1-z) ) { continue; } } else { if ( y < 0 || y >= 2<<(z-1) ) { continue; } } for ( int x = iMapMinX ; x<= iMapMaxX ; x++ ) { if ( z == 0 ) { if ( x < 0 || x >= 2>>(1-z) ) { continue; } } else { if ( x < 0 || x >= 2<<(z-1) ) { continue; } } //检查数据是否被加载 bool bDataIsLoad = false; for ( int i=0;i<this->m_iBlockCount;i++ ) { if( m_MapBlockUnit[i].lLevel == m_iLevel &&m_MapBlockUnit[i].lNumX == x &&m_MapBlockUnit[i].lNumY==y && m_MapBlockUnit[i].bDraw ) { // m_MapBlockUnit[i].lStartX = iCenterOffsetX - (iCenterX - x )*256; // m_MapBlockUnit[i].lStartY = iCenterOffsetY - (iCenterY - y )*256; bDataIsLoad = true; break; } } //如果已经加载,则查找下一个 if( bDataIsLoad ) { continue; } else { //查找空的没有用的列表 CMapBlockUnit* pParam = NULL; int i = 0; for ( ;i<this->m_iBlockCount;i++ ) { if( !m_MapBlockUnit[i].bDraw ) { pParam = &m_MapBlockUnit[i]; break; } } if ( pParam == NULL ) { m_iBlockCount++; if ( m_iBlockCount >= _BLOCK_MAX_NUM ) { // ASSERT(0); m_iBlockCount = 0; } pParam = &m_MapBlockUnit[m_iBlockCount-1]; } //把要绘制的数据存入绘制列表 if( z == 7 ) { z = 7; if( x > 64 && x < 70 ) { z = 7; if( y > 64 && y < 70 ) { z = 7; } } } string strFileName; if( m_enMapType == GMAP_FILES ) GetMapPath(x,y,z,strFileName); else CMapBase::GetMapDataPath( x,y,z,strFileName,m_enMapType ); { if ( m_MapBlockUnit[i].LoadImg( strFileName ) ) { m_MapBlockUnit[i].lLevel = z; m_MapBlockUnit[i].lNumX = x; m_MapBlockUnit[i].lNumY = y; // m_MapBlockUnit[i].lStartX = iCenterOffsetX - (iCenterX - x )*256; // m_MapBlockUnit[i].lStartY = iCenterOffsetY - (iCenterY - y )*256; m_MapBlockUnit[i].bDraw = true; } else { if( m_enMapType != GMAP_FILES ) { // this->m_pMapDisp->m_MapDataDown.AddDownLoadList( x, y , z, m_enMapType ); } } } } } } } }
08c8ed0baf5cfb18fc24086767d65aefbb653268
5c6194e025346e672d8d6d760d782eed0e61bb7d
/developer/VSSDK/VisualStudioIntegration/Common/Source/CPP/VSL/MockInterfaces/VSLMockIVsParentProject2.h
4ebe128b45d65fef969bc198cf3b23ca3df07ccf
[ "MIT" ]
permissive
liushouhuo/windows
888c4d9f8ae37ff60dd959eaf15879b8afdb161f
9e211d0cd5cacbd62c9c6ac764a6731985d60e26
refs/heads/master
2021-09-03T06:34:51.320672
2018-01-06T12:48:51
2018-01-06T12:48:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,989
h
VSLMockIVsParentProject2.h
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. This code is a part of the Visual Studio Library. ***************************************************************************/ #ifndef IVSPARENTPROJECT2_H_10C49CA1_2F46_11D3_A504_00C04F5E0BA5 #define IVSPARENTPROJECT2_H_10C49CA1_2F46_11D3_A504_00C04F5E0BA5 #if _MSC_VER > 1000 #pragma once #endif #include "vsshell80.h" #pragma warning(push) #pragma warning(disable : 4510) // default constructor could not be generated #pragma warning(disable : 4610) // can never be instantiated - user defined constructor required #pragma warning(disable : 4512) // assignment operator could not be generated #pragma warning(disable : 6011) // Dereferencing NULL pointer (a NULL derference is just another kind of failure for a unit test namespace VSL { class IVsParentProject2NotImpl : public IVsParentProject2 { VSL_DECLARE_NONINSTANTIABLE_BASE_CLASS(IVsParentProject2NotImpl) public: typedef IVsParentProject2 Interface; STDMETHOD(CreateNestedProject)( /*[in]*/ VSITEMID /*itemidLoc*/, /*[in]*/ REFGUID /*rguidProjectType*/, /*[in]*/ LPCOLESTR /*lpszMoniker*/, /*[in]*/ LPCOLESTR /*lpszLocation*/, /*[in]*/ LPCOLESTR /*lpszName*/, /*[in]*/ VSCREATEPROJFLAGS /*grfCreateFlags*/, /*[in]*/ REFGUID /*rguidProjectID*/, /*[in]*/ REFIID /*iidProject*/, /*[out,iid_is(iidProject)]*/ void** /*ppProject*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(AddNestedSolution)( /*[in]*/ VSITEMID /*itemidLoc*/, /*[in]*/ VSSLNOPENOPTIONS /*grfOpenOpts*/, /*[in]*/ LPCOLESTR /*pszFilename*/)VSL_STDMETHOD_NOTIMPL }; class IVsParentProject2MockImpl : public IVsParentProject2, public MockBase { VSL_DECLARE_NONINSTANTIABLE_BASE_CLASS(IVsParentProject2MockImpl) public: VSL_DEFINE_MOCK_CLASS_TYPDEFS(IVsParentProject2MockImpl) typedef IVsParentProject2 Interface; struct CreateNestedProjectValidValues { /*[in]*/ VSITEMID itemidLoc; /*[in]*/ REFGUID rguidProjectType; /*[in]*/ LPCOLESTR lpszMoniker; /*[in]*/ LPCOLESTR lpszLocation; /*[in]*/ LPCOLESTR lpszName; /*[in]*/ VSCREATEPROJFLAGS grfCreateFlags; /*[in]*/ REFGUID rguidProjectID; /*[in]*/ REFIID iidProject; /*[out,iid_is(iidProject)]*/ void** ppProject; HRESULT retValue; }; STDMETHOD(CreateNestedProject)( /*[in]*/ VSITEMID itemidLoc, /*[in]*/ REFGUID rguidProjectType, /*[in]*/ LPCOLESTR lpszMoniker, /*[in]*/ LPCOLESTR lpszLocation, /*[in]*/ LPCOLESTR lpszName, /*[in]*/ VSCREATEPROJFLAGS grfCreateFlags, /*[in]*/ REFGUID rguidProjectID, /*[in]*/ REFIID iidProject, /*[out,iid_is(iidProject)]*/ void** ppProject) { VSL_DEFINE_MOCK_METHOD(CreateNestedProject) VSL_CHECK_VALIDVALUE(itemidLoc); VSL_CHECK_VALIDVALUE(rguidProjectType); VSL_CHECK_VALIDVALUE_STRINGW(lpszMoniker); VSL_CHECK_VALIDVALUE_STRINGW(lpszLocation); VSL_CHECK_VALIDVALUE_STRINGW(lpszName); VSL_CHECK_VALIDVALUE(grfCreateFlags); VSL_CHECK_VALIDVALUE(rguidProjectID); VSL_CHECK_VALIDVALUE(iidProject); VSL_SET_VALIDVALUE(ppProject); VSL_RETURN_VALIDVALUES(); } struct AddNestedSolutionValidValues { /*[in]*/ VSITEMID itemidLoc; /*[in]*/ VSSLNOPENOPTIONS grfOpenOpts; /*[in]*/ LPCOLESTR pszFilename; HRESULT retValue; }; STDMETHOD(AddNestedSolution)( /*[in]*/ VSITEMID itemidLoc, /*[in]*/ VSSLNOPENOPTIONS grfOpenOpts, /*[in]*/ LPCOLESTR pszFilename) { VSL_DEFINE_MOCK_METHOD(AddNestedSolution) VSL_CHECK_VALIDVALUE(itemidLoc); VSL_CHECK_VALIDVALUE(grfOpenOpts); VSL_CHECK_VALIDVALUE_STRINGW(pszFilename); VSL_RETURN_VALIDVALUES(); } }; } // namespace VSL #pragma warning(pop) #endif // IVSPARENTPROJECT2_H_10C49CA1_2F46_11D3_A504_00C04F5E0BA5
abbc2b1f197f30f6f6c42a99d0f0e0719de96f1f
04fee3ff94cde55400ee67352d16234bb5e62712
/9.20不水题欢乐赛/2019-09-20/source/Stu-32-王宇飞/protect/protect.cpp
5f99ea3e6d6f512cc21473daca5b9ff1469b334d
[]
no_license
zsq001/oi-code
0bc09c839c9a27c7329c38e490c14bff0177b96e
56f4bfed78fb96ac5d4da50ccc2775489166e47a
refs/heads/master
2023-08-31T06:14:49.709105
2021-09-14T02:28:28
2021-09-14T02:28:28
218,049,685
1
0
null
null
null
null
UTF-8
C++
false
false
1,258
cpp
protect.cpp
#include<bits/stdc++.h> using namespace std; int n,x[20],y[20],a[20],l[20],r[20],ans; struct edge{ int loca,num; }use[20]; bool cmp(edge x,edge y){ return x.num<y.num; } bool judgeempty(){ int jecnt=0; for(int jei=1;jei<=n;jei++){ if(use[jei].num==0) jecnt++; } if(jecnt==n) return false; else return true; } int toans(int x){ return pow(x,2); } int main () { freopen("protect.in","r",stdin); freopen("protect.out","w",stdout); cin>>n; a[0]=-214748364; a[n+1]=214748364; for(int i=1;i<=n;i++){ cin>>x[i]>>y[i]; } if(x[1]==x[2]){ for(int i=1;i<=n;i++){ a[i]=y[i]; } } if(y[1]==y[2]){ for(int i=1;i<=n;i++){ a[i]=x[i]; } } sort(a+1,a+1+n); for(int i=1;i<=n;i++){ l[i]=a[i]-a[i-1]; r[i]=a[i+1]-a[i]; use[i].num=min(l[i],r[i]); use[i].loca=i; } sort(use+1,use+1+n,cmp); while(judgeempty()){ ans+=toans(use[n].num); for(int frontloca=1;frontloca<=n;frontloca++){ if(use[frontloca].loca==use[n].loca-1){ use[frontloca].num=0; } } for(int nextloca=1;nextloca<=n;nextloca++){ if(use[nextloca].loca==use[n].loca-1){ use[nextloca].num=0; } } use[n].num=0; sort(use+1,use+1+n,cmp); } cout<<ans<<endl; return 0; }
b95c10581db5f6c46b5c7f56ab8b81bd8d1584e4
b3e525a3c48800303019adac8f9079109c88004e
/nic/hal/plugins/sfw/alg_rtsp/rtsp_parse.hpp
517dfbb95b9ab6120e72705910df48e8d8fea249
[]
no_license
PsymonLi/sw
d272aee23bf66ebb1143785d6cb5e6fa3927f784
3890a88283a4a4b4f7488f0f79698445c814ee81
refs/heads/master
2022-12-16T21:04:26.379534
2020-08-27T07:57:22
2020-08-28T01:15:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,862
hpp
rtsp_parse.hpp
//----------------------------------------------------------------------------- // {C} Copyright 2017 Pensando Systems Inc. All rights reserved //----------------------------------------------------------------------------- #pragma once #include "nic/include/base.hpp" #include "nic/sdk/include/sdk/ip.hpp" namespace hal { namespace plugins { namespace alg_rtsp { #define RTSP_MESSAGE_ENTRIES(ENTRY) \ ENTRY(RTSP_MSG_REQUEST, 0, "Request") \ ENTRY(RTSP_MSG_RESPONSE, 1, "Response") DEFINE_ENUM(rtsp_msg_type_t, RTSP_MESSAGE_ENTRIES) #undef RTSP_MESSAGE_ENTRIES #define RTSP_VER_ENTRIES(ENTRY) \ ENTRY(RTSP_V1, 0, "RTSP/1.0") \ ENTRY(RTSP_V2, 1, "RTSP/2.0") DEFINE_ENUM(rtsp_ver_t, RTSP_VER_ENTRIES) #undef RTSP_VER_ENTRIES #define RTSP_MEHOTD_ENTRIES(ENTRY) \ ENTRY(RTSP_METHOD_NONE, 0, "None") \ ENTRY(RTSP_METHOD_SETUP, 1, "SETUP") \ ENTRY(RTSP_METHOD_TEARDOWN, 2, "TEARDOWN") \ ENTRY(RTSP_METHOD_REDIRECT, 3, "REDIRECT") DEFINE_ENUM(rtsp_method_t, RTSP_MEHOTD_ENTRIES) #undef RTSP_MEHOTD_ENTRIES #define RTSP_HDR_ENTRIES(ENTRY) \ ENTRY(RTSP_HDR_NONE, 0, "None") \ ENTRY(RTSP_HDR_CSEQ, 1, "CSeq") \ ENTRY(RTSP_HDR_TRANSPORT, 2, "Transport") \ ENTRY(RTSP_HDR_SESSION, 3, "Session") \ ENTRY(RTSP_HDR_CONTENT_LENGTH, 4, "Content-Length") DEFINE_ENUM(rtsp_hdr_type_t, RTSP_HDR_ENTRIES) #undef RTSP_HDR_ENTRIES #define RTSP_STATUS_OK 200 #define DEFAULT_SESSION_TIMEOUT 60 #define MAX_TRANSPORT_SPECS 8 typedef char rtsp_session_id_t[512]; struct rtsp_transport_t { ip_addr_t client_ip; uint16_t client_port_start; uint16_t client_port_end; ip_addr_t server_ip; uint16_t server_port_start; uint16_t server_port_end; uint16_t ip_proto; bool interleaved; }; struct rtsp_hdrs_t { struct { uint8_t cseq:1; uint8_t transport:1; uint8_t session:1; uint8_t content_length:1; } valid; uint32_t cseq; struct { rtsp_session_id_t id; uint32_t timeout; } session; struct { uint8_t nspecs; rtsp_transport_t specs[MAX_TRANSPORT_SPECS]; } transport; uint32_t content_length; }; struct rtsp_msg_t { rtsp_msg_type_t type; rtsp_ver_t ver; union { struct { rtsp_method_t method; } req; struct { uint32_t status_code; } rsp; }; rtsp_hdrs_t hdrs; }; // spdlog formatter for flow_key_t std::ostream& operator<<(std::ostream& os, const rtsp_msg_t& msg); bool rtsp_parse_msg(const char *buf, uint32_t len, uint32_t *offset, rtsp_msg_t*msg); } // alg_rtsp } // plugins } // hal
63712a542c7462eff52a852c6db0ac2a1c58c27f
1d98b3237c0efd1994c02910ed31f1f0ae0e8be5
/src/liboslexec/llvm_gen.cpp
8147640fafa43d6dc96704276b448bb30894439c
[ "CC-BY-4.0", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
gkmotu/OpenShadingLanguage
2a2c4dd27bbe645ac236d5e42208a0fc5d62358b
5b32bd1a48b1c270cf78e956068196006b8ec4b7
refs/heads/master
2023-01-28T04:28:18.409638
2020-12-09T06:49:10
2020-12-09T06:49:10
320,123,063
1
0
BSD-3-Clause
2020-12-10T01:16:26
2020-12-10T01:16:26
null
UTF-8
C++
false
false
149,616
cpp
llvm_gen.cpp
// Copyright Contributors to the Open Shading Language project. // SPDX-License-Identifier: BSD-3-Clause // https://github.com/imageworks/OpenShadingLanguage #include <cmath> #include <OpenImageIO/fmath.h> #include "oslexec_pvt.h" #include <OSL/genclosure.h> #include "backendllvm.h" using namespace OSL; using namespace OSL::pvt; OSL_NAMESPACE_ENTER namespace pvt { static ustring op_and("and"); static ustring op_bitand("bitand"); static ustring op_bitor("bitor"); static ustring op_break("break"); static ustring op_ceil("ceil"); static ustring op_cellnoise("cellnoise"); static ustring op_color("color"); static ustring op_compl("compl"); static ustring op_continue("continue"); static ustring op_dowhile("dowhile"); static ustring op_eq("eq"); static ustring op_error("error"); static ustring op_fabs("fabs"); static ustring op_floor("floor"); static ustring op_for("for"); static ustring op_format("format"); static ustring op_fprintf("fprintf"); static ustring op_ge("ge"); static ustring op_gt("gt"); static ustring op_hashnoise("hashnoise"); static ustring op_if("if"); static ustring op_le("le"); static ustring op_logb("logb"); static ustring op_lt("lt"); static ustring op_min("min"); static ustring op_neq("neq"); static ustring op_normal("normal"); static ustring op_or("or"); static ustring op_point("point"); static ustring op_printf("printf"); static ustring op_round("round"); static ustring op_shl("shl"); static ustring op_shr("shr"); static ustring op_sign("sign"); static ustring op_step("step"); static ustring op_trunc("trunc"); static ustring op_vector("vector"); static ustring op_warning("warning"); static ustring op_xor("xor"); static ustring u_distance ("distance"); static ustring u_index ("index"); static ustring u__empty; // empty/default ustring /// Macro that defines the arguments to LLVM IR generating routines /// #define LLVMGEN_ARGS BackendLLVM &rop, int opnum /// Macro that defines the full declaration of an LLVM generator. /// #define LLVMGEN(name) bool name (LLVMGEN_ARGS) // Forward decl LLVMGEN (llvm_gen_generic); void BackendLLVM::llvm_gen_debug_printf (string_view message) { ustring s = ustring::sprintf ("(%s %s) %s", inst()->shadername(), inst()->layername(), message); ll.call_function ("osl_printf", sg_void_ptr(), ll.constant("%s\n"), ll.constant(s)); } void BackendLLVM::llvm_gen_warning (string_view message) { ll.call_function ("osl_warning", sg_void_ptr(), ll.constant("%s\n"), ll.constant(message)); } void BackendLLVM::llvm_gen_error (string_view message) { ll.call_function ("osl_error", sg_void_ptr(), ll.constant("%s\n"), ll.constant(message)); } void BackendLLVM::llvm_call_layer (int layer, bool unconditional) { // Make code that looks like: // if (! groupdata->run[parentlayer]) // parent_layer (sg, groupdata); // if it's a conditional call, or // parent_layer (sg, groupdata); // if it's run unconditionally. // The code in the parent layer itself will set its 'executed' flag. llvm::Value *args[] = { sg_ptr (), groupdata_ptr () }; ShaderInstance *parent = group()[layer]; llvm::Value *trueval = ll.constant_bool(true); llvm::Value *layerfield = layer_run_ref(layer_remap(layer)); llvm::BasicBlock *then_block = NULL, *after_block = NULL; if (! unconditional) { llvm::Value *executed = ll.op_load (layerfield); executed = ll.op_ne (executed, trueval); then_block = ll.new_basic_block (""); after_block = ll.new_basic_block (""); ll.op_branch (executed, then_block, after_block); // insert point is now then_block } // Mark the call as a fast call llvm::Value *funccall = ll.call_function (layer_function_name(group(), *parent).c_str(), args); if (!parent->entry_layer()) ll.mark_fast_func_call (funccall); if (! unconditional) ll.op_branch (after_block); // also moves insert point } void BackendLLVM::llvm_run_connected_layers (Symbol &sym, int symindex, int opnum, std::set<int> *already_run) { if (sym.valuesource() != Symbol::ConnectedVal) return; // Nothing to do bool inmain = (opnum >= inst()->maincodebegin() && opnum < inst()->maincodeend()); for (int c = 0; c < inst()->nconnections(); ++c) { const Connection &con (inst()->connection (c)); // If the connection gives a value to this param if (con.dst.param == symindex) { // already_run is a set of layers run for this particular op. // Just so we don't stupidly do several consecutive checks on // whether we ran this same layer. It's JUST for this op. if (already_run) { if (already_run->count (con.srclayer)) continue; // already ran that one on this op else already_run->insert (con.srclayer); // mark it } if (inmain) { // There is an instance-wide m_layers_already_run that tries // to remember which earlier layers have unconditionally // been run at any point in the execution of this layer. But // only honor (and modify) that when in the main code // section, not when in init ops, which are inherently // conditional. if (m_layers_already_run.count (con.srclayer)) { continue; // already unconditionally ran the layer } if (! m_in_conditional[opnum]) { // Unconditionally running -- mark so we don't do it // again. If we're inside a conditional, don't mark // because it may not execute the conditional body. m_layers_already_run.insert (con.srclayer); } } // If the earlier layer it comes from has not yet been // executed, do so now. llvm_call_layer (con.srclayer); } } } OSL_PRAGMA_WARNING_PUSH OSL_GCC_PRAGMA(GCC diagnostic ignored "-Wunused-parameter") LLVMGEN (llvm_gen_nop) { return true; } OSL_PRAGMA_WARNING_POP LLVMGEN (llvm_gen_useparam) { OSL_DASSERT (! rop.inst()->unused() && "oops, thought this layer was unused, why do we call it?"); // If we have multiple params needed on this statement, don't waste // time checking the same upstream layer more than once. std::set<int> already_run; Opcode &op (rop.inst()->ops()[opnum]); for (int i = 0; i < op.nargs(); ++i) { Symbol& sym = *rop.opargsym (op, i); int symindex = rop.inst()->arg (op.firstarg()+i); rop.llvm_run_connected_layers (sym, symindex, opnum, &already_run); // If it's an interpolated (userdata) parameter and we're // initializing them lazily, now we have to do it. if ((sym.symtype() == SymTypeParam || sym.symtype() == SymTypeOutputParam) && ! sym.lockgeom() && ! sym.typespec().is_closure() && ! sym.connected() && ! sym.connected_down() && rop.shadingsys().lazy_userdata()) { rop.llvm_assign_initial_value (sym); } } return true; } // Used for printf, error, warning, format, fprintf LLVMGEN (llvm_gen_printf) { Opcode &op (rop.inst()->ops()[opnum]); // Prepare the args for the call // Which argument is the format string? Usually 0, but for op // format() and fprintf(), the formatting string is argument #1. int format_arg = (op.opname() == "format" || op.opname() == "fprintf") ? 1 : 0; Symbol& format_sym = *rop.opargsym (op, format_arg); std::vector<llvm::Value*> call_args; if (!format_sym.is_constant()) { rop.shadingcontext()->warningf("%s must currently have constant format\n", op.opname()); return false; } // For some ops, we push the shader globals pointer if (op.opname() == op_printf || op.opname() == op_error || op.opname() == op_warning || op.opname() == op_fprintf) call_args.push_back (rop.sg_void_ptr()); // fprintf also needs the filename if (op.opname() == op_fprintf) { Symbol& Filename = *rop.opargsym (op, 0); llvm::Value* fn = rop.llvm_load_value (Filename); call_args.push_back (fn); } // We're going to need to adjust the format string as we go, but I'd // like to reserve a spot for the char*. size_t new_format_slot = call_args.size(); call_args.push_back(NULL); ustring format_ustring = format_sym.get_string(); const char* format = format_ustring.c_str(); std::string s; int arg = format_arg + 1; size_t optix_size = 0; while (*format != '\0') { if (*format == '%') { if (format[1] == '%') { // '%%' is a literal '%' s += "%%"; format += 2; // skip both percentages continue; } const char *oldfmt = format; // mark beginning of format while (*format && *format != 'c' && *format != 'd' && *format != 'e' && *format != 'f' && *format != 'g' && *format != 'i' && *format != 'm' && *format != 'n' && *format != 'o' && *format != 'p' && *format != 's' && *format != 'u' && *format != 'v' && *format != 'x' && *format != 'X') ++format; char formatchar = *format++; // Also eat the format char if (arg >= op.nargs()) { rop.shadingcontext()->errorf("Mismatch between format string and arguments (%s:%d)", op.sourcefile(), op.sourceline()); return false; } std::string ourformat (oldfmt, format); // straddle the format // Doctor it to fix mismatches between format and data Symbol& sym (*rop.opargsym (op, arg)); OSL_ASSERT (! sym.typespec().is_structure_based()); TypeDesc simpletype (sym.typespec().simpletype()); int num_elements = simpletype.numelements(); int num_components = simpletype.aggregate; if ((sym.typespec().is_closure_based() || simpletype.basetype == TypeDesc::STRING) && formatchar != 's') { ourformat[ourformat.length()-1] = 's'; } if (simpletype.basetype == TypeDesc::INT && formatchar != 'd' && formatchar != 'i' && formatchar != 'o' && formatchar != 'u' && formatchar != 'x' && formatchar != 'X') { ourformat[ourformat.length()-1] = 'd'; } if (simpletype.basetype == TypeDesc::FLOAT && formatchar != 'f' && formatchar != 'g' && formatchar != 'c' && formatchar != 'e' && formatchar != 'm' && formatchar != 'n' && formatchar != 'p' && formatchar != 'v') { ourformat[ourformat.length()-1] = 'f'; } // NOTE(boulos): Only for debug mode do the derivatives get printed... for (int a = 0; a < num_elements; ++a) { llvm::Value *arrind = simpletype.arraylen ? rop.ll.constant(a) : NULL; if (sym.typespec().is_closure_based()) { s += ourformat; llvm::Value *v = rop.llvm_load_value (sym, 0, arrind, 0); v = rop.ll.call_function ("osl_closure_to_string", rop.sg_void_ptr(), v); call_args.push_back (v); continue; } for (int c = 0; c < num_components; c++) { if (c != 0 || a != 0) s += " "; s += ourformat; llvm::Value* loaded = nullptr; if (rop.use_optix() && simpletype.basetype == TypeDesc::STRING) { // In the OptiX case, we register each string separately. if (simpletype.arraylen >= 1) { // Mangle the element's name in case llvm_load_device_string calls getOrAllocateLLVMSymbol ustring name = ustring::sprintf("__symname__%s[%d]", sym.mangled(), a); Symbol lsym(name, TypeDesc::TypeString, sym.symtype()); lsym.data(&((ustring*)sym.data())[a]); loaded = rop.llvm_load_device_string (lsym, /*follow*/ true); } else { loaded = rop.llvm_load_device_string (sym, /*follow*/ true); } optix_size += sizeof(uint64_t); } else { loaded = rop.llvm_load_value (sym, 0, arrind, c); if (simpletype.basetype == TypeDesc::FLOAT) { // C varargs convention upconverts float->double. loaded = rop.ll.op_float_to_double(loaded); // Ensure that 64-bit values are aligned to 8-byte boundaries optix_size = (optix_size + sizeof(double) - 1) & ~(sizeof(double) - 1); optix_size += sizeof(double); } else if (simpletype.basetype == TypeDesc::INT) optix_size += sizeof(int); } call_args.push_back (loaded); } } ++arg; } else { // Everything else -- just copy the character and advance s += *format++; } } // In OptiX, printf currently supports 0 or 1 arguments, and the signature // requires 1 argument, so push a null pointer onto the call args if there // is no argument. if (rop.use_optix() && arg == format_arg + 1) { call_args.push_back(rop.ll.void_ptr_null()); } // Some ops prepend things if (op.opname() == op_error || op.opname() == op_warning) { std::string prefix = Strutil::sprintf ("Shader %s [%s]: ", op.opname(), rop.inst()->shadername()); s = prefix + s; } // Now go back and put the new format string in its place if (! rop.use_optix()) { call_args[new_format_slot] = rop.ll.constant (s.c_str()); } else { // In the OptiX case, we do this: // void* args = { arg0, arg1, arg2 }; // osl_printf(sg, fmt, args); // vprintf(fmt, args); // Symbol sym(format_sym.name(), format_sym.typespec(), format_sym.symtype()); format_ustring = s; sym.data(&format_ustring); call_args[new_format_slot] = rop.llvm_load_device_string (sym, /*follow*/ true); size_t nargs = call_args.size() - (new_format_slot+1); llvm::Value *voids = rop.ll.op_alloca (rop.ll.type_char(), optix_size, std::string(), 8); optix_size = 0; for (size_t i = 0; i < nargs; ++i) { llvm::Value* arg = call_args[new_format_slot+1+i]; if (arg->getType()->isFloatingPointTy()) { // Ensure that 64-bit values are aligned to 8-byte boundaries optix_size = (optix_size + sizeof(double) - 1) & ~(sizeof(double)-1); } llvm::Value* memptr = rop.ll.offset_ptr (voids, optix_size); if (arg->getType()->isIntegerTy()) { llvm::Value* iptr = rop.ll.ptr_cast(memptr, rop.ll.type_int_ptr()); rop.ll.op_store (arg, iptr); optix_size += sizeof(int); } else if (arg->getType()->isFloatingPointTy()) { llvm::Value* fptr = rop.ll.ptr_cast(memptr, rop.ll.type_double_ptr()); rop.ll.op_store (arg, fptr); optix_size += sizeof(double); } else { llvm::Value* vptr = rop.ll.ptr_to_cast(memptr, rop.ll.type_void_ptr()); rop.ll.op_store (arg, vptr); optix_size += sizeof(uint64_t); } } call_args.resize(new_format_slot+2); call_args.back() = rop.ll.void_ptr(voids); } // Construct the function name and call it. std::string opname = std::string("osl_") + op.opname().string(); llvm::Value *ret = rop.ll.call_function (opname.c_str(), call_args); // The format op returns a string value, put in in the right spot if (op.opname() == op_format) rop.llvm_store_value (ret, *rop.opargsym (op, 0)); return true; } LLVMGEN (llvm_gen_add) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); Symbol& B = *rop.opargsym (op, 2); OSL_DASSERT (! A.typespec().is_array() && ! B.typespec().is_array()); if (Result.typespec().is_closure()) { OSL_DASSERT (A.typespec().is_closure() && B.typespec().is_closure()); llvm::Value *valargs[] = { rop.sg_void_ptr(), rop.llvm_load_value (A), rop.llvm_load_value (B) }; llvm::Value *res = rop.ll.call_function ("osl_add_closure_closure", valargs); rop.llvm_store_value (res, Result, 0, NULL, 0); return true; } TypeDesc type = Result.typespec().simpletype(); int num_components = type.aggregate; // The following should handle f+f, v+v, v+f, f+v, i+i // That's all that should be allowed by oslc. for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.loadLLVMValue (A, i, 0, type); llvm::Value *b = rop.loadLLVMValue (B, i, 0, type); if (!a || !b) return false; llvm::Value *r = rop.ll.op_add (a, b); rop.storeLLVMValue (r, Result, i, 0); } if (Result.has_derivs()) { if (A.has_derivs() || B.has_derivs()) { for (int d = 1; d <= 2; ++d) { // dx, dy for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.loadLLVMValue (A, i, d, type); llvm::Value *b = rop.loadLLVMValue (B, i, d, type); llvm::Value *r = rop.ll.op_add (a, b); rop.storeLLVMValue (r, Result, i, d); } } } else { // Result has derivs, operands do not rop.llvm_zero_derivs (Result); } } return true; } LLVMGEN (llvm_gen_sub) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); Symbol& B = *rop.opargsym (op, 2); TypeDesc type = Result.typespec().simpletype(); int num_components = type.aggregate; OSL_DASSERT (! Result.typespec().is_closure_based() && "subtraction of closures not supported"); // The following should handle f-f, v-v, v-f, f-v, i-i // That's all that should be allowed by oslc. for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.loadLLVMValue (A, i, 0, type); llvm::Value *b = rop.loadLLVMValue (B, i, 0, type); if (!a || !b) return false; llvm::Value *r = rop.ll.op_sub (a, b); rop.storeLLVMValue (r, Result, i, 0); } if (Result.has_derivs()) { if (A.has_derivs() || B.has_derivs()) { for (int d = 1; d <= 2; ++d) { // dx, dy for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.loadLLVMValue (A, i, d, type); llvm::Value *b = rop.loadLLVMValue (B, i, d, type); llvm::Value *r = rop.ll.op_sub (a, b); rop.storeLLVMValue (r, Result, i, d); } } } else { // Result has derivs, operands do not rop.llvm_zero_derivs (Result); } } return true; } LLVMGEN (llvm_gen_mul) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); Symbol& B = *rop.opargsym (op, 2); TypeDesc type = Result.typespec().simpletype(); OSL_MAYBE_UNUSED bool is_float = !Result.typespec().is_closure_based() && Result.typespec().is_float_based(); int num_components = type.aggregate; // multiplication involving closures if (Result.typespec().is_closure()) { llvm::Value *valargs[3]; valargs[0] = rop.sg_void_ptr(); bool tfloat; if (A.typespec().is_closure()) { tfloat = B.typespec().is_float(); valargs[1] = rop.llvm_load_value (A); valargs[2] = tfloat ? rop.llvm_load_value (B) : rop.llvm_void_ptr(B); } else { tfloat = A.typespec().is_float(); valargs[1] = rop.llvm_load_value (B); valargs[2] = tfloat ? rop.llvm_load_value (A) : rop.llvm_void_ptr(A); } llvm::Value *res = tfloat ? rop.ll.call_function ("osl_mul_closure_float", valargs) : rop.ll.call_function ("osl_mul_closure_color", valargs); rop.llvm_store_value (res, Result, 0, NULL, 0); return true; } // multiplication involving matrices if (Result.typespec().is_matrix()) { if (A.typespec().is_float()) { if (B.typespec().is_matrix()) rop.llvm_call_function ("osl_mul_mmf", Result, B, A); else OSL_ASSERT(0 && "frontend should not allow"); } else if (A.typespec().is_matrix()) { if (B.typespec().is_float()) rop.llvm_call_function ("osl_mul_mmf", Result, A, B); else if (B.typespec().is_matrix()) rop.llvm_call_function ("osl_mul_mmm", Result, A, B); else OSL_ASSERT(0 && "frontend should not allow"); } else OSL_ASSERT (0 && "frontend should not allow"); if (Result.has_derivs()) rop.llvm_zero_derivs (Result); return true; } // The following should handle f*f, v*v, v*f, f*v, i*i // That's all that should be allowed by oslc. for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.llvm_load_value (A, 0, i, type); llvm::Value *b = rop.llvm_load_value (B, 0, i, type); if (!a || !b) return false; llvm::Value *r = rop.ll.op_mul (a, b); rop.llvm_store_value (r, Result, 0, i); if (Result.has_derivs() && (A.has_derivs() || B.has_derivs())) { // Multiplication of duals: (a*b, a*b.dx + a.dx*b, a*b.dy + a.dy*b) OSL_DASSERT (is_float); llvm::Value *ax = rop.llvm_load_value (A, 1, i, type); llvm::Value *bx = rop.llvm_load_value (B, 1, i, type); llvm::Value *abx = rop.ll.op_mul (a, bx); llvm::Value *axb = rop.ll.op_mul (ax, b); llvm::Value *rx = rop.ll.op_add (abx, axb); llvm::Value *ay = rop.llvm_load_value (A, 2, i, type); llvm::Value *by = rop.llvm_load_value (B, 2, i, type); llvm::Value *aby = rop.ll.op_mul (a, by); llvm::Value *ayb = rop.ll.op_mul (ay, b); llvm::Value *ry = rop.ll.op_add (aby, ayb); rop.llvm_store_value (rx, Result, 1, i); rop.llvm_store_value (ry, Result, 2, i); } } if (Result.has_derivs() && ! (A.has_derivs() || B.has_derivs())) { // Result has derivs, operands do not rop.llvm_zero_derivs (Result); } return true; } LLVMGEN (llvm_gen_div) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); Symbol& B = *rop.opargsym (op, 2); TypeDesc type = Result.typespec().simpletype(); bool is_float = Result.typespec().is_float_based(); int num_components = type.aggregate; OSL_DASSERT (! Result.typespec().is_closure_based()); // division involving matrices if (Result.typespec().is_matrix()) { if (A.typespec().is_float()) { OSL_ASSERT (!B.typespec().is_float() && "frontend should not allow"); if (B.typespec().is_matrix()) rop.llvm_call_function ("osl_div_mfm", Result, A, B); else OSL_ASSERT (0); } else if (A.typespec().is_matrix()) { if (B.typespec().is_float()) rop.llvm_call_function ("osl_div_mmf", Result, A, B); else if (B.typespec().is_matrix()) rop.llvm_call_function ("osl_div_mmm", Result, A, B); else OSL_ASSERT (0); } else OSL_ASSERT (0); if (Result.has_derivs()) rop.llvm_zero_derivs (Result); return true; } // The following should handle f/f, v/v, v/f, f/v, i/i // That's all that should be allowed by oslc. const char *safe_div = is_float ? "osl_safe_div_fff" : "osl_safe_div_iii"; bool deriv = (Result.has_derivs() && (A.has_derivs() || B.has_derivs())); for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.llvm_load_value (A, 0, i, type); llvm::Value *b = rop.llvm_load_value (B, 0, i, type); if (!a || !b) return false; llvm::Value *a_div_b; if (B.is_constant() && ! rop.is_zero(B)) a_div_b = rop.ll.op_div (a, b); else a_div_b = rop.ll.call_function (safe_div, a, b); llvm::Value *rx = NULL, *ry = NULL; if (deriv) { // Division of duals: (a/b, 1/b*(ax-a/b*bx), 1/b*(ay-a/b*by)) OSL_DASSERT (is_float); llvm::Value *binv; if (B.is_constant() && ! rop.is_zero(B)) binv = rop.ll.op_div (rop.ll.constant(1.0f), b); else binv = rop.ll.call_function (safe_div, rop.ll.constant(1.0f), b); llvm::Value *ax = rop.llvm_load_value (A, 1, i, type); llvm::Value *bx = rop.llvm_load_value (B, 1, i, type); llvm::Value *a_div_b_mul_bx = rop.ll.op_mul (a_div_b, bx); llvm::Value *ax_minus_a_div_b_mul_bx = rop.ll.op_sub (ax, a_div_b_mul_bx); rx = rop.ll.op_mul (binv, ax_minus_a_div_b_mul_bx); llvm::Value *ay = rop.llvm_load_value (A, 2, i, type); llvm::Value *by = rop.llvm_load_value (B, 2, i, type); llvm::Value *a_div_b_mul_by = rop.ll.op_mul (a_div_b, by); llvm::Value *ay_minus_a_div_b_mul_by = rop.ll.op_sub (ay, a_div_b_mul_by); ry = rop.ll.op_mul (binv, ay_minus_a_div_b_mul_by); } rop.llvm_store_value (a_div_b, Result, 0, i); if (deriv) { rop.llvm_store_value (rx, Result, 1, i); rop.llvm_store_value (ry, Result, 2, i); } } if (Result.has_derivs() && ! (A.has_derivs() || B.has_derivs())) { // Result has derivs, operands do not rop.llvm_zero_derivs (Result); } return true; } LLVMGEN (llvm_gen_modulus) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); Symbol& B = *rop.opargsym (op, 2); TypeDesc type = Result.typespec().simpletype(); bool is_float = Result.typespec().is_float_based(); int num_components = type.aggregate; #ifdef OSL_LLVM_NO_BITCODE // On Windows 32 bit this calls an unknown instruction, probably need to // link with LLVM compiler-rt to fix, for now just fall back to op if (is_float) return llvm_gen_generic (rop, opnum); #endif // The following should handle f%f, v%v, v%f, i%i // That's all that should be allowed by oslc. const char *safe_mod = is_float ? "osl_fmod_fff" : "osl_safe_mod_iii"; for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.loadLLVMValue (A, i, 0, type); llvm::Value *b = rop.loadLLVMValue (B, i, 0, type); if (!a || !b) return false; llvm::Value *r; if (B.is_constant() && ! rop.is_zero(B)) r = rop.ll.op_mod (a, b); else r = rop.ll.call_function (safe_mod, a, b); rop.storeLLVMValue (r, Result, i, 0); } if (Result.has_derivs()) { OSL_DASSERT (is_float); if (A.has_derivs()) { // Modulus of duals: (a mod b, ax, ay) for (int d = 1; d <= 2; ++d) { for (int i = 0; i < num_components; i++) { llvm::Value *deriv = rop.loadLLVMValue (A, i, d, type); rop.storeLLVMValue (deriv, Result, i, d); } } } else { // Result has derivs, operands do not rop.llvm_zero_derivs (Result); } } return true; } LLVMGEN (llvm_gen_neg) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); TypeDesc type = Result.typespec().simpletype(); int num_components = type.aggregate; for (int d = 0; d < 3; ++d) { // dx, dy for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.llvm_load_value (A, d, i, type); llvm::Value *r = rop.ll.op_neg (a); rop.llvm_store_value (r, Result, d, i); } if (! Result.has_derivs()) break; } return true; } // Implementation for clamp LLVMGEN (llvm_gen_clamp) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& X = *rop.opargsym (op, 1); Symbol& Min = *rop.opargsym (op, 2); Symbol& Max = *rop.opargsym (op, 3); TypeDesc type = Result.typespec().simpletype(); int num_components = type.aggregate; for (int i = 0; i < num_components; i++) { // First do the lower bound llvm::Value *val = rop.llvm_load_value (X, 0, i, type); llvm::Value *min = rop.llvm_load_value (Min, 0, i, type); llvm::Value *cond = rop.ll.op_lt (val, min); val = rop.ll.op_select (cond, min, val); llvm::Value *valdx=NULL, *valdy=NULL; if (Result.has_derivs()) { valdx = rop.llvm_load_value (X, 1, i, type); valdy = rop.llvm_load_value (X, 2, i, type); llvm::Value *mindx = rop.llvm_load_value (Min, 1, i, type); llvm::Value *mindy = rop.llvm_load_value (Min, 2, i, type); valdx = rop.ll.op_select (cond, mindx, valdx); valdy = rop.ll.op_select (cond, mindy, valdy); } // Now do the upper bound llvm::Value *max = rop.llvm_load_value (Max, 0, i, type); cond = rop.ll.op_gt (val, max); val = rop.ll.op_select (cond, max, val); if (Result.has_derivs()) { llvm::Value *maxdx = rop.llvm_load_value (Max, 1, i, type); llvm::Value *maxdy = rop.llvm_load_value (Max, 2, i, type); valdx = rop.ll.op_select (cond, maxdx, valdx); valdy = rop.ll.op_select (cond, maxdy, valdy); } rop.llvm_store_value (val, Result, 0, i); rop.llvm_store_value (valdx, Result, 1, i); rop.llvm_store_value (valdy, Result, 2, i); } return true; } LLVMGEN (llvm_gen_mix) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); Symbol& B = *rop.opargsym (op, 2); Symbol& X = *rop.opargsym (op, 3); TypeDesc type = Result.typespec().simpletype(); OSL_DASSERT (!Result.typespec().is_closure_based() && Result.typespec().is_float_based()); int num_components = type.aggregate; int x_components = X.typespec().aggregate(); bool derivs = (Result.has_derivs() && (A.has_derivs() || B.has_derivs() || X.has_derivs())); llvm::Value *one = rop.ll.constant (1.0f); llvm::Value *x = rop.llvm_load_value (X, 0, 0, type); llvm::Value *one_minus_x = rop.ll.op_sub (one, x); llvm::Value *xx = derivs ? rop.llvm_load_value (X, 1, 0, type) : NULL; llvm::Value *xy = derivs ? rop.llvm_load_value (X, 2, 0, type) : NULL; for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.llvm_load_value (A, 0, i, type); llvm::Value *b = rop.llvm_load_value (B, 0, i, type); if (!a || !b) return false; if (i > 0 && x_components > 1) { // Only need to recompute x and 1-x if they change x = rop.llvm_load_value (X, 0, i, type); one_minus_x = rop.ll.op_sub (one, x); } // r = a*one_minus_x + b*x llvm::Value *r1 = rop.ll.op_mul (a, one_minus_x); llvm::Value *r2 = rop.ll.op_mul (b, x); llvm::Value *r = rop.ll.op_add (r1, r2); rop.llvm_store_value (r, Result, 0, i); if (derivs) { // mix of duals: // (a*one_minus_x + b*x, // a*one_minus_x.dx + a.dx*one_minus_x + b*x.dx + b.dx*x, // a*one_minus_x.dy + a.dy*one_minus_x + b*x.dy + b.dy*x) // and since one_minus_x.dx = -x.dx, one_minus_x.dy = -x.dy, // (a*one_minus_x + b*x, // -a*x.dx + a.dx*one_minus_x + b*x.dx + b.dx*x, // -a*x.dy + a.dy*one_minus_x + b*x.dy + b.dy*x) llvm::Value *ax = rop.llvm_load_value (A, 1, i, type); llvm::Value *bx = rop.llvm_load_value (B, 1, i, type); if (i > 0 && x_components > 1) xx = rop.llvm_load_value (X, 1, i, type); llvm::Value *rx1 = rop.ll.op_mul (a, xx); llvm::Value *rx2 = rop.ll.op_mul (ax, one_minus_x); llvm::Value *rx = rop.ll.op_sub (rx2, rx1); llvm::Value *rx3 = rop.ll.op_mul (b, xx); rx = rop.ll.op_add (rx, rx3); llvm::Value *rx4 = rop.ll.op_mul (bx, x); rx = rop.ll.op_add (rx, rx4); llvm::Value *ay = rop.llvm_load_value (A, 2, i, type); llvm::Value *by = rop.llvm_load_value (B, 2, i, type); if (i > 0 && x_components > 1) xy = rop.llvm_load_value (X, 2, i, type); llvm::Value *ry1 = rop.ll.op_mul (a, xy); llvm::Value *ry2 = rop.ll.op_mul (ay, one_minus_x); llvm::Value *ry = rop.ll.op_sub (ry2, ry1); llvm::Value *ry3 = rop.ll.op_mul (b, xy); ry = rop.ll.op_add (ry, ry3); llvm::Value *ry4 = rop.ll.op_mul (by, x); ry = rop.ll.op_add (ry, ry4); rop.llvm_store_value (rx, Result, 1, i); rop.llvm_store_value (ry, Result, 2, i); } } if (Result.has_derivs() && !derivs) { // Result has derivs, operands do not rop.llvm_zero_derivs (Result); } return true; } LLVMGEN (llvm_gen_select) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); Symbol& B = *rop.opargsym (op, 2); Symbol& X = *rop.opargsym (op, 3); TypeDesc type = Result.typespec().simpletype(); OSL_DASSERT (!Result.typespec().is_closure_based() && Result.typespec().is_float_based()); int num_components = type.aggregate; int x_components = X.typespec().aggregate(); bool derivs = (Result.has_derivs() && (A.has_derivs() || B.has_derivs())); llvm::Value *zero = X.typespec().is_int() ? rop.ll.constant (0) : rop.ll.constant (0.0f); llvm::Value *cond[3]; for (int i = 0; i < x_components; ++i) cond[i] = rop.ll.op_ne (rop.llvm_load_value (X, 0, i), zero); for (int i = 0; i < num_components; i++) { llvm::Value *a = rop.llvm_load_value (A, 0, i, type); llvm::Value *b = rop.llvm_load_value (B, 0, i, type); llvm::Value *c = (i >= x_components) ? cond[0] : cond[i]; llvm::Value *r = rop.ll.op_select (c, b, a); rop.llvm_store_value (r, Result, 0, i); if (derivs) { for (int d = 1; d < 3; ++d) { a = rop.llvm_load_value (A, d, i, type); b = rop.llvm_load_value (B, d, i, type); r = rop.ll.op_select (c, b, a); rop.llvm_store_value (r, Result, d, i); } } } if (Result.has_derivs() && !derivs) { // Result has derivs, operands do not rop.llvm_zero_derivs (Result); } return true; } // Implementation for min/max LLVMGEN (llvm_gen_minmax) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& x = *rop.opargsym (op, 1); Symbol& y = *rop.opargsym (op, 2); TypeDesc type = Result.typespec().simpletype(); int num_components = type.aggregate; for (int i = 0; i < num_components; i++) { // First do the lower bound llvm::Value *x_val = rop.llvm_load_value (x, 0, i, type); llvm::Value *y_val = rop.llvm_load_value (y, 0, i, type); llvm::Value* cond = NULL; // NOTE(boulos): Using <= instead of < to match old behavior // (only matters for derivs) if (op.opname() == op_min) { cond = rop.ll.op_le (x_val, y_val); } else { cond = rop.ll.op_gt (x_val, y_val); } llvm::Value* res_val = rop.ll.op_select (cond, x_val, y_val); rop.llvm_store_value (res_val, Result, 0, i); if (Result.has_derivs()) { llvm::Value* x_dx = rop.llvm_load_value (x, 1, i, type); llvm::Value* x_dy = rop.llvm_load_value (x, 2, i, type); llvm::Value* y_dx = rop.llvm_load_value (y, 1, i, type); llvm::Value* y_dy = rop.llvm_load_value (y, 2, i, type); rop.llvm_store_value (rop.ll.op_select(cond, x_dx, y_dx), Result, 1, i); rop.llvm_store_value (rop.ll.op_select(cond, x_dy, y_dy), Result, 2, i); } } return true; } LLVMGEN (llvm_gen_bitwise_binary_op) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); Symbol& B = *rop.opargsym (op, 2); OSL_DASSERT (Result.typespec().is_int() && A.typespec().is_int() && B.typespec().is_int()); llvm::Value *a = rop.loadLLVMValue (A); llvm::Value *b = rop.loadLLVMValue (B); if (!a || !b) return false; llvm::Value *r = NULL; if (op.opname() == op_bitand) r = rop.ll.op_and (a, b); else if (op.opname() == op_bitor) r = rop.ll.op_or (a, b); else if (op.opname() == op_xor) r = rop.ll.op_xor (a, b); else if (op.opname() == op_shl) r = rop.ll.op_shl (a, b); else if (op.opname() == op_shr) r = rop.ll.op_shr (a, b); else return false; rop.storeLLVMValue (r, Result); return true; } // Simple (pointwise) unary ops (Abs, ..., LLVMGEN (llvm_gen_unary_op) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& dst = *rop.opargsym (op, 0); Symbol& src = *rop.opargsym (op, 1); bool dst_derivs = dst.has_derivs(); int num_components = dst.typespec().simpletype().aggregate; bool dst_float = dst.typespec().is_float_based(); bool src_float = src.typespec().is_float_based(); for (int i = 0; i < num_components; i++) { // Get src1/2 component i llvm::Value* src_load = rop.loadLLVMValue (src, i, 0); if (!src_load) return false; llvm::Value* src_val = src_load; // Perform the op llvm::Value* result = 0; ustring opname = op.opname(); if (opname == op_compl) { OSL_DASSERT (dst.typespec().is_int()); result = rop.ll.op_not (src_val); } else { // Don't know how to handle this. rop.shadingcontext()->errorf("Don't know how to handle op '%s', eliding the store\n", opname); } // Store the result if (result) { // if our op type doesn't match result, convert if (dst_float && !src_float) { // Op was int, but we need to store float result = rop.ll.op_int_to_float (result); } else if (!dst_float && src_float) { // Op was float, but we need to store int result = rop.ll.op_float_to_int (result); } // otherwise just fine rop.storeLLVMValue (result, dst, i, 0); } if (dst_derivs) { // mul results in <a * b, a * b_dx + b * a_dx, a * b_dy + b * a_dy> rop.shadingcontext()->infof("punting on derivatives for now\n"); // FIXME!! } } return true; } // Simple assignment LLVMGEN (llvm_gen_assign) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result (*rop.opargsym (op, 0)); Symbol& Src (*rop.opargsym (op, 1)); return rop.llvm_assign_impl (Result, Src); } // Entire array copying LLVMGEN (llvm_gen_arraycopy) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result (*rop.opargsym (op, 0)); Symbol& Src (*rop.opargsym (op, 1)); return rop.llvm_assign_impl (Result, Src); } // Vector component reference LLVMGEN (llvm_gen_compref) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& Val = *rop.opargsym (op, 1); Symbol& Index = *rop.opargsym (op, 2); llvm::Value *c = rop.llvm_load_value(Index); if (rop.inst()->master()->range_checking()) { if (! (Index.is_constant() && Index.get_int() >= 0 && Index.get_int() < 3)) { llvm::Value *args[] = { c, rop.ll.constant(3), rop.ll.constant(Val.unmangled()), rop.sg_void_ptr(), rop.ll.constant(op.sourcefile()), rop.ll.constant(op.sourceline()), rop.ll.constant(rop.group().name()), rop.ll.constant(rop.layer()), rop.ll.constant(rop.inst()->layername()), rop.ll.constant(rop.inst()->shadername()) }; c = rop.ll.call_function ("osl_range_check", args); } } for (int d = 0; d < 3; ++d) { // deriv llvm::Value *val = NULL; if (Index.is_constant()) { int i = Index.get_int(); i = Imath::clamp (i, 0, 2); val = rop.llvm_load_value (Val, d, i); } else { val = rop.llvm_load_component_value (Val, d, c); } rop.llvm_store_value (val, Result, d); if (! Result.has_derivs()) // skip the derivs if we don't need them break; } return true; } // Vector component assignment LLVMGEN (llvm_gen_compassign) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& Index = *rop.opargsym (op, 1); Symbol& Val = *rop.opargsym (op, 2); llvm::Value *c = rop.llvm_load_value(Index); if (rop.inst()->master()->range_checking()) { if (! (Index.is_constant() && Index.get_int() >= 0 && Index.get_int() < 3)) { llvm::Value *args[] = { c, rop.ll.constant(3), rop.ll.constant(Result.unmangled()), rop.sg_void_ptr(), rop.ll.constant(op.sourcefile()), rop.ll.constant(op.sourceline()), rop.ll.constant(rop.group().name()), rop.ll.constant(rop.layer()), rop.ll.constant(rop.inst()->layername()), rop.ll.constant(rop.inst()->shadername()) }; c = rop.ll.call_function ("osl_range_check", args); } } for (int d = 0; d < 3; ++d) { // deriv llvm::Value *val = rop.llvm_load_value (Val, d, 0, TypeDesc::TypeFloat); if (Index.is_constant()) { int i = Index.get_int(); i = Imath::clamp (i, 0, 2); rop.llvm_store_value (val, Result, d, i); } else { rop.llvm_store_component_value (val, Result, d, c); } if (! Result.has_derivs()) // skip the derivs if we don't need them break; } return true; } // Matrix component reference LLVMGEN (llvm_gen_mxcompref) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& M = *rop.opargsym (op, 1); Symbol& Row = *rop.opargsym (op, 2); Symbol& Col = *rop.opargsym (op, 3); llvm::Value *row = rop.llvm_load_value (Row); llvm::Value *col = rop.llvm_load_value (Col); if (rop.inst()->master()->range_checking()) { if (! (Row.is_constant() && Col.is_constant() && Row.get_int() >= 0 && Row.get_int() < 4 && Col.get_int() >= 0 && Col.get_int() < 4)) { llvm::Value *args[] = { row, rop.ll.constant(4), rop.ll.constant(M.name()), rop.sg_void_ptr(), rop.ll.constant(op.sourcefile()), rop.ll.constant(op.sourceline()), rop.ll.constant(rop.group().name()), rop.ll.constant(rop.layer()), rop.ll.constant(rop.inst()->layername()), rop.ll.constant(rop.inst()->shadername()) }; if (! (Row.is_constant() && Row.get_int() >= 0 && Row.get_int() < 4)) { row = rop.ll.call_function ("osl_range_check", args); } if (! (Col.is_constant() && Col.get_int() >= 0 && Col.get_int() < 4)) { args[0] = col; col = rop.ll.call_function ("osl_range_check", args); } } } llvm::Value *val = NULL; if (Row.is_constant() && Col.is_constant()) { int r = Imath::clamp (Row.get_int(), 0, 3); int c = Imath::clamp (Col.get_int(), 0, 3); int comp = 4 * r + c; val = rop.llvm_load_value (M, 0, comp); } else { llvm::Value *comp = rop.ll.op_mul (row, rop.ll.constant(4)); comp = rop.ll.op_add (comp, col); val = rop.llvm_load_component_value (M, 0, comp); } rop.llvm_store_value (val, Result); rop.llvm_zero_derivs (Result); return true; } // Matrix component assignment LLVMGEN (llvm_gen_mxcompassign) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& Row = *rop.opargsym (op, 1); Symbol& Col = *rop.opargsym (op, 2); Symbol& Val = *rop.opargsym (op, 3); llvm::Value *row = rop.llvm_load_value (Row); llvm::Value *col = rop.llvm_load_value (Col); if (rop.inst()->master()->range_checking()) { if (! (Row.is_constant() && Col.is_constant() && Row.get_int() >= 0 && Row.get_int() < 4 && Col.get_int() >= 0 && Col.get_int() < 4)) { llvm::Value *args[] = { row, rop.ll.constant(4), rop.ll.constant(Result.name()), rop.sg_void_ptr(), rop.ll.constant(op.sourcefile()), rop.ll.constant(op.sourceline()), rop.ll.constant(rop.group().name()), rop.ll.constant(rop.layer()), rop.ll.constant(rop.inst()->layername()), rop.ll.constant(rop.inst()->shadername()) }; if (! (Row.is_constant() && Row.get_int() >= 0 && Row.get_int() < 4)) { row = rop.ll.call_function ("osl_range_check", args); } if (! (Col.is_constant() && Col.get_int() >= 0 && Col.get_int() < 4)) { args[0] = col; col = rop.ll.call_function ("osl_range_check", args); } } } llvm::Value *val = rop.llvm_load_value (Val, 0, 0, TypeDesc::TypeFloat); if (Row.is_constant() && Col.is_constant()) { int r = Imath::clamp(Row.get_int(), 0, 3); int c = Imath::clamp(Col.get_int(), 0, 3); int comp = 4 * r + c; rop.llvm_store_value (val, Result, 0, comp); } else { llvm::Value *comp = rop.ll.op_mul (row, rop.ll.constant(4)); comp = rop.ll.op_add (comp, col); rop.llvm_store_component_value (val, Result, 0, comp); } return true; } // Array length LLVMGEN (llvm_gen_arraylength) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& A = *rop.opargsym (op, 1); OSL_DASSERT(Result.typespec().is_int() && A.typespec().is_array()); int len = A.typespec().is_unsized_array() ? A.initializers() : A.typespec().arraylength(); rop.llvm_store_value (rop.ll.constant(len), Result); return true; } // Array reference LLVMGEN (llvm_gen_aref) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& Src = *rop.opargsym (op, 1); Symbol& Index = *rop.opargsym (op, 2); // Get array index we're interested in llvm::Value *index = rop.loadLLVMValue (Index); if (! index) return false; if (rop.inst()->master()->range_checking()) { if (! (Index.is_constant() && Index.get_int() >= 0 && Index.get_int() < Src.typespec().arraylength())) { llvm::Value *args[] = { index, rop.ll.constant(Src.typespec().arraylength()), rop.ll.constant(Src.unmangled()), rop.sg_void_ptr(), rop.ll.constant(op.sourcefile()), rop.ll.constant(op.sourceline()), rop.ll.constant(rop.group().name()), rop.ll.constant(rop.layer()), rop.ll.constant(rop.inst()->layername()), rop.ll.constant(rop.inst()->shadername()) }; index = rop.ll.call_function ("osl_range_check", args); } } int num_components = Src.typespec().simpletype().aggregate; for (int d = 0; d <= 2; ++d) { for (int c = 0; c < num_components; ++c) { llvm::Value *val = rop.llvm_load_value (Src, d, index, c); rop.storeLLVMValue (val, Result, c, d); } if (! Result.has_derivs()) break; } return true; } // Array assignment LLVMGEN (llvm_gen_aassign) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); Symbol& Index = *rop.opargsym (op, 1); Symbol& Src = *rop.opargsym (op, 2); // Get array index we're interested in llvm::Value *index = rop.loadLLVMValue (Index); if (! index) return false; if (rop.inst()->master()->range_checking()) { if (! (Index.is_constant() && Index.get_int() >= 0 && Index.get_int() < Result.typespec().arraylength())) { llvm::Value *args[] = { index, rop.ll.constant(Result.typespec().arraylength()), rop.ll.constant(Result.unmangled()), rop.sg_void_ptr(), rop.ll.constant(op.sourcefile()), rop.ll.constant(op.sourceline()), rop.ll.constant(rop.group().name()), rop.ll.constant(rop.layer()), rop.ll.constant(rop.inst()->layername()), rop.ll.constant(rop.inst()->shadername()) }; index = rop.ll.call_function ("osl_range_check", args); } } int num_components = Result.typespec().simpletype().aggregate; // Allow float <=> int casting TypeDesc cast; if (num_components == 1 && !Result.typespec().is_closure() && !Src.typespec().is_closure() && (Result.typespec().is_int_based() || Result.typespec().is_float_based()) && (Src.typespec().is_int_based() || Src.typespec().is_float_based())) { cast = Result.typespec().simpletype(); cast.arraylen = 0; } else { // Try to warn before llvm_fatal_error is called which provides little // context as to what went wrong. OSL_ASSERT (Result.typespec().simpletype().basetype == Src.typespec().simpletype().basetype); } for (int d = 0; d <= 2; ++d) { for (int c = 0; c < num_components; ++c) { llvm::Value *val = rop.loadLLVMValue (Src, c, d, cast); rop.llvm_store_value (val, Result, d, index, c); } if (! Result.has_derivs()) break; } return true; } // Construct color, optionally with a color transformation from a named // color space. LLVMGEN (llvm_gen_construct_color) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); bool using_space = (op.nargs() == 5); Symbol& Space = *rop.opargsym (op, 1); OSL_MAYBE_UNUSED Symbol& X = *rop.opargsym (op, 1+using_space); OSL_MAYBE_UNUSED Symbol& Y = *rop.opargsym (op, 2+using_space); OSL_MAYBE_UNUSED Symbol& Z = *rop.opargsym (op, 3+using_space); OSL_DASSERT (Result.typespec().is_triple() && X.typespec().is_float() && Y.typespec().is_float() && Z.typespec().is_float() && (using_space == false || Space.typespec().is_string())); // First, copy the floats into the vector int dmax = Result.has_derivs() ? 3 : 1; for (int d = 0; d < dmax; ++d) { // loop over derivs for (int c = 0; c < 3; ++c) { // loop over components const Symbol& comp = *rop.opargsym (op, c+1+using_space); llvm::Value* val = rop.llvm_load_value (comp, d, NULL, 0, TypeDesc::TypeFloat); rop.llvm_store_value (val, Result, d, NULL, c); } } // Do the color space conversion in-place, if called for if (using_space) { llvm::Value *args[] = { rop.sg_void_ptr(), // shader globals rop.llvm_void_ptr(Result, 0), // color rop.llvm_load_string(Space), // from }; rop.ll.call_function ("osl_prepend_color_from", args); // FIXME(deriv): Punt on derivs for color ctrs with space names. // We should try to do this right, but we never had it right for // the interpreter, to it's probably not an emergency. if (Result.has_derivs()) rop.llvm_zero_derivs (Result); } return true; } // Construct spatial triple (point, vector, normal), optionally with a // transformation from a named coordinate system. LLVMGEN (llvm_gen_construct_triple) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); bool using_space = (op.nargs() == 5); Symbol& Space = *rop.opargsym (op, 1); OSL_MAYBE_UNUSED Symbol& X = *rop.opargsym (op, 1+using_space); OSL_MAYBE_UNUSED Symbol& Y = *rop.opargsym (op, 2+using_space); OSL_MAYBE_UNUSED Symbol& Z = *rop.opargsym (op, 3+using_space); OSL_DASSERT (Result.typespec().is_triple() && X.typespec().is_float() && Y.typespec().is_float() && Z.typespec().is_float() && (using_space == false || Space.typespec().is_string())); // First, copy the floats into the vector int dmax = Result.has_derivs() ? 3 : 1; for (int d = 0; d < dmax; ++d) { // loop over derivs for (int c = 0; c < 3; ++c) { // loop over components const Symbol& comp = *rop.opargsym (op, c+1+using_space); llvm::Value* val = rop.llvm_load_value (comp, d, NULL, 0, TypeDesc::TypeFloat); rop.llvm_store_value (val, Result, d, NULL, c); } } // Do the transformation in-place, if called for if (using_space) { ustring from, to; // N.B. initialize to empty strings if (Space.is_constant()) { from = Space.get_string(); if (from == Strings::common || from == rop.shadingsys().commonspace_synonym()) return true; // no transformation necessary } TypeDesc::VECSEMANTICS vectype = TypeDesc::POINT; if (op.opname() == "vector") vectype = TypeDesc::VECTOR; else if (op.opname() == "normal") vectype = TypeDesc::NORMAL; llvm::Value *args[] = { rop.sg_void_ptr(), rop.llvm_void_ptr(Result), rop.ll.constant(Result.has_derivs()), rop.llvm_void_ptr(Result), rop.ll.constant(Result.has_derivs()), rop.llvm_load_value(Space), rop.ll.constant(Strings::common), rop.ll.constant((int)vectype) }; RendererServices *rend (rop.shadingsys().renderer()); if (rend->transform_points (NULL, from, to, 0.0f, NULL, NULL, 0, vectype)) { // renderer potentially knows about a nonlinear transformation. // Note that for the case of non-constant strings, passing empty // from & to will make transform_points just tell us if ANY // nonlinear transformations potentially are supported. rop.ll.call_function ("osl_transform_triple_nonlinear", args); } else { // definitely not a nonlinear transformation rop.ll.call_function ("osl_transform_triple", args); } } return true; } /// matrix constructor. Comes in several varieties: /// matrix (float) /// matrix (space, float) /// matrix (...16 floats...) /// matrix (space, ...16 floats...) /// matrix (fromspace, tospace) LLVMGEN (llvm_gen_matrix) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result = *rop.opargsym (op, 0); int nargs = op.nargs(); bool using_space = (nargs == 3 || nargs == 18); bool using_two_spaces = (nargs == 3 && rop.opargsym(op,2)->typespec().is_string()); int nfloats = nargs - 1 - (int)using_space; OSL_DASSERT (nargs == 2 || nargs == 3 || nargs == 17 || nargs == 18); if (using_two_spaces) { llvm::Value *args[] = { rop.sg_void_ptr(), // shader globals rop.llvm_void_ptr(Result), // result rop.llvm_load_value(*rop.opargsym (op, 1)), // from rop.llvm_load_value(*rop.opargsym (op, 2)), // to }; rop.ll.call_function ("osl_get_from_to_matrix", args); } else { if (nfloats == 1) { for (int i = 0; i < 16; i++) { llvm::Value* src_val = ((i%4) == (i/4)) ? rop.llvm_load_value (*rop.opargsym(op,1+using_space)) : rop.ll.constant(0.0f); rop.llvm_store_value (src_val, Result, 0, i); } } else if (nfloats == 16) { for (int i = 0; i < 16; i++) { llvm::Value* src_val = rop.llvm_load_value (*rop.opargsym(op,i+1+using_space)); rop.llvm_store_value (src_val, Result, 0, i); } } else { OSL_ASSERT (0); } if (using_space) { llvm::Value *args[] = { rop.sg_void_ptr(), // shader globals rop.llvm_void_ptr(Result), // result rop.llvm_load_value(*rop.opargsym (op, 1)), // from }; rop.ll.call_function ("osl_prepend_matrix_from", args); } } if (Result.has_derivs()) rop.llvm_zero_derivs (Result); return true; } /// int getmatrix (fromspace, tospace, M) LLVMGEN (llvm_gen_getmatrix) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT (op.nargs() == 4); Symbol& Result = *rop.opargsym (op, 0); Symbol& From = *rop.opargsym (op, 1); Symbol& To = *rop.opargsym (op, 2); Symbol& M = *rop.opargsym (op, 3); llvm::Value *args[] = { rop.sg_void_ptr(), // shader globals rop.llvm_void_ptr(M), // matrix result rop.llvm_load_value(From), rop.llvm_load_value(To), }; llvm::Value *result = rop.ll.call_function ("osl_get_from_to_matrix", args); rop.llvm_store_value (result, Result); rop.llvm_zero_derivs (M); return true; } // transform{,v,n} (string tospace, triple p) // transform{,v,n} (string fromspace, string tospace, triple p) // transform{,v,n} (matrix, triple p) LLVMGEN (llvm_gen_transform) { Opcode &op (rop.inst()->ops()[opnum]); int nargs = op.nargs(); Symbol *Result = rop.opargsym (op, 0); Symbol *From = (nargs == 3) ? NULL : rop.opargsym (op, 1); Symbol *To = rop.opargsym (op, (nargs == 3) ? 1 : 2); Symbol *P = rop.opargsym (op, (nargs == 3) ? 2 : 3); if (To->typespec().is_matrix()) { // llvm_ops has the matrix version already implemented llvm_gen_generic (rop, opnum); return true; } // Named space versions from here on out. ustring from, to; // N.B.: initialize to empty strings if ((From == NULL || From->is_constant()) && To->is_constant()) { // We can know all the space names at this time from = From ? From->get_string() : Strings::common; to = To->get_string(); ustring syn = rop.shadingsys().commonspace_synonym(); if (from == syn) from = Strings::common; if (to == syn) to = Strings::common; if (from == to) { // An identity transformation, just copy if (Result != P) // don't bother in-place copy rop.llvm_assign_impl (*Result, *P); return true; } } TypeDesc::VECSEMANTICS vectype = TypeDesc::POINT; if (op.opname() == "transformv") vectype = TypeDesc::VECTOR; else if (op.opname() == "transformn") vectype = TypeDesc::NORMAL; llvm::Value *args[] = { rop.sg_void_ptr(), rop.llvm_void_ptr(*P), rop.ll.constant(P->has_derivs()), rop.llvm_void_ptr(*Result), rop.ll.constant(Result->has_derivs()), rop.llvm_load_value(*From), rop.llvm_load_value(*To), rop.ll.constant((int)vectype) }; RendererServices *rend (rop.shadingsys().renderer()); if (rend->transform_points (NULL, from, to, 0.0f, NULL, NULL, 0, vectype)) { // renderer potentially knows about a nonlinear transformation. // Note that for the case of non-constant strings, passing empty // from & to will make transform_points just tell us if ANY // nonlinear transformations potentially are supported. rop.ll.call_function ("osl_transform_triple_nonlinear", args); } else { // definitely not a nonlinear transformation rop.ll.call_function ("osl_transform_triple", args); } return true; } // transformc (string fromspace, string tospace, color p) LLVMGEN (llvm_gen_transformc) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT (op.nargs() == 4); Symbol *Result = rop.opargsym (op, 0); Symbol *From = rop.opargsym (op, 1); Symbol *To = rop.opargsym (op, 2); Symbol *C = rop.opargsym (op, 3); llvm::Value *args[] = { rop.sg_void_ptr(), rop.llvm_void_ptr(*C), rop.ll.constant(C->has_derivs()), rop.llvm_void_ptr(*Result), rop.ll.constant(Result->has_derivs()), rop.llvm_load_string (*From), rop.llvm_load_string (*To) }; rop.ll.call_function ("osl_transformc", args); return true; } // Derivs LLVMGEN (llvm_gen_DxDy) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result (*rop.opargsym (op, 0)); Symbol& Src (*rop.opargsym (op, 1)); int deriv = (op.opname() == "Dx") ? 1 : 2; for (int i = 0; i < Result.typespec().aggregate(); ++i) { llvm::Value* src_val = rop.llvm_load_value (Src, deriv, i); rop.storeLLVMValue (src_val, Result, i, 0); } // Don't have 2nd order derivs rop.llvm_zero_derivs (Result); return true; } // Dz LLVMGEN (llvm_gen_Dz) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result (*rop.opargsym (op, 0)); Symbol& Src (*rop.opargsym (op, 1)); if (&Src == rop.inst()->symbol(rop.inst()->Psym())) { // dPdz -- the only Dz we know how to take int deriv = 3; for (int i = 0; i < Result.typespec().aggregate(); ++i) { llvm::Value* src_val = rop.llvm_load_value (Src, deriv, i); rop.storeLLVMValue (src_val, Result, i, 0); } // Don't have 2nd order derivs rop.llvm_zero_derivs (Result); } else { // Punt, everything else for now returns 0 for Dz // FIXME? rop.llvm_assign_zero (Result); } return true; } LLVMGEN (llvm_gen_filterwidth) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Result (*rop.opargsym (op, 0)); Symbol& Src (*rop.opargsym (op, 1)); OSL_DASSERT (Src.typespec().is_float() || Src.typespec().is_triple()); if (Src.has_derivs()) { if (Src.typespec().is_float()) { llvm::Value *r = rop.ll.call_function ("osl_filterwidth_fdf", rop.llvm_void_ptr (Src)); rop.llvm_store_value (r, Result); } else { rop.ll.call_function ("osl_filterwidth_vdv", rop.llvm_void_ptr (Result), rop.llvm_void_ptr (Src)); } // Don't have 2nd order derivs rop.llvm_zero_derivs (Result); } else { // No derivs to be had rop.llvm_assign_zero (Result); } return true; } // Comparison ops LLVMGEN (llvm_gen_compare_op) { Opcode &op (rop.inst()->ops()[opnum]); Symbol &Result (*rop.opargsym (op, 0)); Symbol &A (*rop.opargsym (op, 1)); Symbol &B (*rop.opargsym (op, 2)); OSL_DASSERT (Result.typespec().is_int() && ! Result.has_derivs()); if (A.typespec().is_closure()) { OSL_ASSERT (B.typespec().is_int() && "Only closure==0 and closure!=0 allowed"); llvm::Value *a = rop.llvm_load_value (A); llvm::Value *b = rop.ll.void_ptr_null (); llvm::Value *r = (op.opname()==op_eq) ? rop.ll.op_eq(a,b) : rop.ll.op_ne(a,b); // Convert the single bit bool into an int r = rop.ll.op_bool_to_int (r); rop.llvm_store_value (r, Result); return true; } int num_components = std::max (A.typespec().aggregate(), B.typespec().aggregate()); bool float_based = A.typespec().is_float_based() || B.typespec().is_float_based(); TypeDesc cast (float_based ? TypeDesc::FLOAT : TypeDesc::UNKNOWN); llvm::Value* final_result = 0; ustring opname = op.opname(); if (rop.use_optix() && A.typespec().is_string()) { OSL_DASSERT (B.typespec().is_string() && "Only string-to-string comparison is supported"); llvm::Value* a = rop.llvm_load_device_string (A, /*follow*/ true); llvm::Value* b = rop.llvm_load_device_string (B, /*follow*/ true); if (opname == op_eq) { final_result = rop.ll.op_eq (a, b); } else if (opname == op_neq) { final_result = rop.ll.op_ne (a, b); } else { // Don't know how to handle this. OSL_ASSERT (0 && "OptiX only supports equality testing for strings"); } OSL_ASSERT (final_result); final_result = rop.ll.op_bool_to_int (final_result); rop.storeLLVMValue (final_result, Result, 0, 0); return true; } for (int i = 0; i < num_components; i++) { // Get A&B component i -- note that these correctly handle mixed // scalar/triple comparisons as well as int->float casts as needed. llvm::Value* a = rop.loadLLVMValue (A, i, 0, cast); llvm::Value* b = rop.loadLLVMValue (B, i, 0, cast); // Trickery for mixed matrix/scalar comparisons -- compare // on-diagonal to the scalar, off-diagonal to zero if (A.typespec().is_matrix() && !B.typespec().is_matrix()) { if ((i/4) != (i%4)) b = rop.ll.constant (0.0f); } if (! A.typespec().is_matrix() && B.typespec().is_matrix()) { if ((i/4) != (i%4)) a = rop.ll.constant (0.0f); } // Perform the op llvm::Value* result = 0; if (opname == op_lt) { result = rop.ll.op_lt (a, b); } else if (opname == op_le) { result = rop.ll.op_le (a, b); } else if (opname == op_eq) { result = rop.ll.op_eq (a, b); } else if (opname == op_ge) { result = rop.ll.op_ge (a, b); } else if (opname == op_gt) { result = rop.ll.op_gt (a, b); } else if (opname == op_neq) { result = rop.ll.op_ne (a, b); } else { // Don't know how to handle this. OSL_ASSERT (0 && "Comparison error"); } OSL_DASSERT (result); if (final_result) { // Combine the component bool based on the op if (opname != op_neq) // final_result &= result final_result = rop.ll.op_and (final_result, result); else // final_result |= result final_result = rop.ll.op_or (final_result, result); } else { final_result = result; } } OSL_ASSERT (final_result); // Convert the single bit bool into an int for now. final_result = rop.ll.op_bool_to_int (final_result); rop.storeLLVMValue (final_result, Result, 0, 0); return true; } // int regex_search (string subject, string pattern) // int regex_search (string subject, int results[], string pattern) // int regex_match (string subject, string pattern) // int regex_match (string subject, int results[], string pattern) LLVMGEN (llvm_gen_regex) { Opcode &op (rop.inst()->ops()[opnum]); int nargs = op.nargs(); OSL_DASSERT (nargs == 3 || nargs == 4); Symbol &Result (*rop.opargsym (op, 0)); Symbol &Subject (*rop.opargsym (op, 1)); bool do_match_results = (nargs == 4); bool fullmatch = (op.opname() == "regex_match"); Symbol &Match (*rop.opargsym (op, 2)); Symbol &Pattern (*rop.opargsym (op, 2+do_match_results)); OSL_DASSERT (Result.typespec().is_int() && Subject.typespec().is_string() && Pattern.typespec().is_string()); OSL_DASSERT (!do_match_results || (Match.typespec().is_array() && Match.typespec().elementtype().is_int())); llvm::Value* call_args[] = { rop.sg_void_ptr(), // First arg is ShaderGlobals ptr rop.llvm_load_value (Subject), // Next arg is subject string rop.llvm_void_ptr(Match), // Pass the results array and length (just pass 0 if no results wanted). do_match_results ? rop.ll.constant(Match.typespec().arraylength()) : rop.ll.constant(0), rop.llvm_load_value (Pattern), // Pass the regex match pattern rop.ll.constant(fullmatch), // Pass whether or not to do the full match }; llvm::Value *ret = rop.ll.call_function ("osl_regex_impl", call_args); rop.llvm_store_value (ret, Result); return true; } // Generic llvm code generation. See the comments in llvm_ops.cpp for // the full list of assumptions and conventions. But in short: // 1. All polymorphic and derivative cases implemented as functions in // llvm_ops.cpp -- no custom IR is needed. // 2. Naming conention is: osl_NAME_{args}, where args is the // concatenation of type codes for all args including return value -- // f/i/v/m/s for float/int/triple/matrix/string, and df/dv/dm for // duals. // 3. The function returns scalars as an actual return value (that // must be stored), but "returns" aggregates or duals in the first // argument. // 4. Duals and aggregates are passed as void*'s, float/int/string // passed by value. // 5. Note that this only works if triples are all treated identically, // this routine can't be used if it must be polymorphic based on // color, point, vector, normal differences. // LLVMGEN (llvm_gen_generic) { // most invocations of this function will only need a handful of args // so avoid dynamic allocation where possible constexpr int SHORT_NUM_ARGS = 16; const Symbol* short_args[SHORT_NUM_ARGS]; std::vector<const Symbol*> long_args; Opcode &op (rop.inst()->ops()[opnum]); const Symbol** args = short_args; if (op.nargs() > SHORT_NUM_ARGS) { long_args.resize(op.nargs()); args = long_args.data(); } Symbol& Result = *rop.opargsym (op, 0); bool any_deriv_args = false; for (int i = 0; i < op.nargs(); ++i) { Symbol *s (rop.opargsym (op, i)); args[i] = s; any_deriv_args |= (i > 0 && s->has_derivs() && !s->typespec().is_matrix()); } // Special cases: functions that have no derivs -- suppress them if (any_deriv_args) if (op.opname() == op_logb || op.opname() == op_floor || op.opname() == op_ceil || op.opname() == op_round || op.opname() == op_step || op.opname() == op_trunc || op.opname() == op_sign) any_deriv_args = false; std::string name = std::string("osl_") + op.opname().string() + "_"; for (int i = 0; i < op.nargs(); ++i) { Symbol *s (rop.opargsym (op, i)); if (any_deriv_args && Result.has_derivs() && s->has_derivs() && !s->typespec().is_matrix()) name += "d"; if (s->typespec().is_float()) name += "f"; else if (s->typespec().is_triple()) name += "v"; else if (s->typespec().is_matrix()) name += "m"; else if (s->typespec().is_string()) name += "s"; else if (s->typespec().is_int()) name += "i"; else OSL_ASSERT (0); } if (! Result.has_derivs() || ! any_deriv_args) { // Don't compute derivs -- either not needed or not provided in args if (Result.typespec().aggregate() == TypeDesc::SCALAR) { llvm::Value *r = rop.llvm_call_function (name.c_str(), cspan<const Symbol*>(args + 1, op.nargs() - 1)); rop.llvm_store_value (r, Result); } else { rop.llvm_call_function (name.c_str(), cspan<const Symbol*>(args, op.nargs())); } rop.llvm_zero_derivs (Result); } else { // Cases with derivs OSL_ASSERT (Result.has_derivs() && any_deriv_args); rop.llvm_call_function (name.c_str(), cspan<const Symbol*>(args, op.nargs()), true); } return true; } LLVMGEN (llvm_gen_sincos) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& Theta = *rop.opargsym (op, 0); Symbol& Sin_out = *rop.opargsym (op, 1); Symbol& Cos_out = *rop.opargsym (op, 2); bool theta_deriv = Theta.has_derivs(); bool result_derivs = (Sin_out.has_derivs() || Cos_out.has_derivs()); std::string name = std::string("osl_sincos_"); for (int i = 0; i < op.nargs(); ++i) { Symbol *s (rop.opargsym (op, i)); if (s->has_derivs() && result_derivs && theta_deriv) name += "d"; if (s->typespec().is_float()) name += "f"; else if (s->typespec().is_triple()) name += "v"; else OSL_ASSERT (0); } // push back llvm arguments llvm::Value* valargs[] = { (theta_deriv && result_derivs) || Theta.typespec().is_triple() ? rop.llvm_void_ptr (Theta) : rop.llvm_load_value (Theta), rop.llvm_void_ptr (Sin_out), rop.llvm_void_ptr (Cos_out) }; rop.ll.call_function (name.c_str(), valargs); // If the input angle didn't have derivatives, we would not have // called the version of sincos with derivs; however in that case we // need to clear the derivs of either of the outputs that has them. if (Sin_out.has_derivs() && !theta_deriv) rop.llvm_zero_derivs (Sin_out); if (Cos_out.has_derivs() && !theta_deriv) rop.llvm_zero_derivs (Cos_out); return true; } LLVMGEN (llvm_gen_andor) { Opcode& op (rop.inst()->ops()[opnum]); Symbol& result = *rop.opargsym (op, 0); Symbol& a = *rop.opargsym (op, 1); Symbol& b = *rop.opargsym (op, 2); llvm::Value* i1_res = NULL; llvm::Value* a_val = rop.llvm_load_value (a, 0, 0, TypeDesc::TypeInt); llvm::Value* b_val = rop.llvm_load_value (b, 0, 0, TypeDesc::TypeInt); if (op.opname() == op_and) { // From the old bitcode generated // define i32 @osl_and_iii(i32 %a, i32 %b) nounwind readnone ssp { // %1 = icmp ne i32 %b, 0 // %not. = icmp ne i32 %a, 0 // %2 = and i1 %1, %not. // %3 = zext i1 %2 to i32 // ret i32 %3 llvm::Value* b_ne_0 = rop.ll.op_ne (b_val, rop.ll.constant(0)); llvm::Value* a_ne_0 = rop.ll.op_ne (a_val, rop.ll.constant(0)); llvm::Value* both_ne_0 = rop.ll.op_and (b_ne_0, a_ne_0); i1_res = both_ne_0; } else { // Also from the bitcode // %1 = or i32 %b, %a // %2 = icmp ne i32 %1, 0 // %3 = zext i1 %2 to i32 llvm::Value* or_ab = rop.ll.op_or(a_val, b_val); llvm::Value* or_ab_ne_0 = rop.ll.op_ne (or_ab, rop.ll.constant(0)); i1_res = or_ab_ne_0; } llvm::Value* i32_res = rop.ll.op_bool_to_int(i1_res); rop.llvm_store_value(i32_res, result, 0, 0); return true; } LLVMGEN (llvm_gen_if) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& cond = *rop.opargsym (op, 0); // Load the condition variable and figure out if it's nonzero llvm::Value* cond_val = rop.llvm_test_nonzero (cond); // Branch on the condition, to our blocks llvm::BasicBlock* then_block = rop.ll.new_basic_block ("then"); llvm::BasicBlock* else_block = rop.ll.new_basic_block ("else"); llvm::BasicBlock* after_block = rop.ll.new_basic_block (""); rop.ll.op_branch (cond_val, then_block, else_block); // Then block rop.build_llvm_code (opnum+1, op.jump(0), then_block); rop.ll.op_branch (after_block); // Else block rop.build_llvm_code (op.jump(0), op.jump(1), else_block); rop.ll.op_branch (after_block); // insert point is now after_block // Continue on with the previous flow return true; } LLVMGEN (llvm_gen_loop_op) { Opcode &op (rop.inst()->ops()[opnum]); Symbol& cond = *rop.opargsym (op, 0); // Branch on the condition, to our blocks llvm::BasicBlock* cond_block = rop.ll.new_basic_block ("cond"); llvm::BasicBlock* body_block = rop.ll.new_basic_block ("body"); llvm::BasicBlock* step_block = rop.ll.new_basic_block ("step"); llvm::BasicBlock* after_block = rop.ll.new_basic_block (""); // Save the step and after block pointers for possible break/continue rop.ll.push_loop (step_block, after_block); // Initialization (will be empty except for "for" loops) rop.build_llvm_code (opnum+1, op.jump(0)); // For "do-while", we go straight to the body of the loop, but for // "for" or "while", we test the condition next. rop.ll.op_branch (op.opname() == op_dowhile ? body_block : cond_block); // Load the condition variable and figure out if it's nonzero rop.build_llvm_code (op.jump(0), op.jump(1), cond_block); llvm::Value* cond_val = rop.llvm_test_nonzero (cond); // Jump to either LoopBody or AfterLoop rop.ll.op_branch (cond_val, body_block, after_block); // Body of loop rop.build_llvm_code (op.jump(1), op.jump(2), body_block); rop.ll.op_branch (step_block); // Step rop.build_llvm_code (op.jump(2), op.jump(3), step_block); rop.ll.op_branch (cond_block); // Continue on with the previous flow rop.ll.set_insert_point (after_block); rop.ll.pop_loop (); return true; } LLVMGEN (llvm_gen_loopmod_op) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 0); if (op.opname() == op_break) { rop.ll.op_branch (rop.ll.loop_after_block()); } else { // continue rop.ll.op_branch (rop.ll.loop_step_block()); } llvm::BasicBlock* next_block = rop.ll.new_basic_block (""); rop.ll.set_insert_point (next_block); return true; } static llvm::Value * llvm_gen_texture_options (BackendLLVM &rop, int opnum, int first_optional_arg, bool tex3d, int nchans, llvm::Value* &alpha, llvm::Value* &dalphadx, llvm::Value* &dalphady, llvm::Value* &errormessage) { llvm::Value* opt = rop.ll.call_function ("osl_get_texture_options", rop.sg_void_ptr()); llvm::Value* missingcolor = NULL; TextureOpt optdefaults; // So we can check the defaults bool swidth_set = false, twidth_set = false, rwidth_set = false; bool sblur_set = false, tblur_set = false, rblur_set = false; bool swrap_set = false, twrap_set = false, rwrap_set = false; bool firstchannel_set = false, fill_set = false, interp_set = false; bool time_set = false, subimage_set = false; Opcode &op (rop.inst()->ops()[opnum]); for (int a = first_optional_arg; a < op.nargs(); ++a) { Symbol &Name (*rop.opargsym(op,a)); OSL_DASSERT (Name.typespec().is_string() && "optional texture token must be a string"); OSL_DASSERT (a+1 < op.nargs() && "malformed argument list for texture"); ustring name = Name.get_string(); ++a; // advance to next argument if (name.empty()) // skip empty string param name continue; Symbol &Val (*rop.opargsym(op,a)); TypeDesc valtype = Val.typespec().simpletype (); const int *ival = Val.typespec().is_int() && Val.is_constant() ? (const int *)Val.data() : NULL; const float *fval = Val.typespec().is_float() && Val.is_constant() ? (const float *)Val.data() : NULL; #define PARAM_INT(paramname) \ if (name == Strings::paramname && valtype == TypeDesc::INT) { \ if (! paramname##_set && \ ival && *ival == optdefaults.paramname) \ continue; /* default constant */ \ llvm::Value *val = rop.llvm_load_value (Val); \ rop.ll.call_function ("osl_texture_set_" #paramname, opt, val); \ paramname##_set = true; \ continue; \ } #define PARAM_FLOAT(paramname) \ if (name == Strings::paramname && \ (valtype == TypeDesc::FLOAT || valtype == TypeDesc::INT)) { \ if (! paramname##_set && \ ((ival && *ival == optdefaults.paramname) || \ (fval && *fval == optdefaults.paramname))) \ continue; /* default constant */ \ llvm::Value *val = rop.llvm_load_value (Val); \ if (valtype == TypeDesc::INT) \ val = rop.ll.op_int_to_float (val); \ rop.ll.call_function ("osl_texture_set_" #paramname, opt, val); \ paramname##_set = true; \ continue; \ } #define PARAM_FLOAT_STR(paramname) \ if (name == Strings::paramname && \ (valtype == TypeDesc::FLOAT || valtype == TypeDesc::INT)) { \ if (! s##paramname##_set && ! t##paramname##_set && \ ! r##paramname##_set && \ ((ival && *ival == optdefaults.s##paramname) || \ (fval && *fval == optdefaults.s##paramname))) \ continue; /* default constant */ \ llvm::Value *val = rop.llvm_load_value (Val); \ if (valtype == TypeDesc::INT) \ val = rop.ll.op_int_to_float (val); \ rop.ll.call_function ("osl_texture_set_st" #paramname, opt, val); \ if (tex3d) \ rop.ll.call_function ("osl_texture_set_r" #paramname, opt, val); \ s##paramname##_set = true; \ t##paramname##_set = true; \ r##paramname##_set = true; \ continue; \ } #define PARAM_STRING_CODE(paramname,decoder,fieldname) \ if (name == Strings::paramname && valtype == TypeDesc::STRING) { \ if (Val.is_constant()) { \ int code = decoder (Val.get_string()); \ if (! paramname##_set && code == optdefaults.fieldname) \ continue; \ if (code >= 0) { \ llvm::Value *val = rop.ll.constant (code); \ rop.ll.call_function ("osl_texture_set_" #paramname "_code", opt, val); \ } \ } else { \ llvm::Value *val = rop.llvm_load_value (Val); \ rop.ll.call_function ("osl_texture_set_" #paramname, opt, val); \ } \ paramname##_set = true; \ continue; \ } PARAM_FLOAT_STR (width) PARAM_FLOAT (swidth) PARAM_FLOAT (twidth) PARAM_FLOAT (rwidth) PARAM_FLOAT_STR (blur) PARAM_FLOAT (sblur) PARAM_FLOAT (tblur) PARAM_FLOAT (rblur) if (name == Strings::wrap && valtype == TypeDesc::STRING) { if (Val.is_constant()) { int mode = TextureOpt::decode_wrapmode (Val.get_string()); llvm::Value *val = rop.ll.constant (mode); rop.ll.call_function ("osl_texture_set_stwrap_code", opt, val); if (tex3d) rop.ll.call_function ("osl_texture_set_rwrap_code", opt, val); } else { llvm::Value *val = rop.llvm_load_value (Val); rop.ll.call_function ("osl_texture_set_stwrap", opt, val); if (tex3d) rop.ll.call_function ("osl_texture_set_rwrap", opt, val); } swrap_set = twrap_set = rwrap_set = true; continue; } PARAM_STRING_CODE(swrap, TextureOpt::decode_wrapmode, swrap) PARAM_STRING_CODE(twrap, TextureOpt::decode_wrapmode, twrap) PARAM_STRING_CODE(rwrap, TextureOpt::decode_wrapmode, rwrap) PARAM_FLOAT (fill) PARAM_FLOAT (time) PARAM_INT (firstchannel) PARAM_INT (subimage) if (name == Strings::subimage && valtype == TypeDesc::STRING) { if (Val.is_constant()) { ustring v = Val.get_string(); if (v.empty() && ! subimage_set) { continue; // Ignore nulls unless they are overrides } } llvm::Value *val = rop.llvm_load_value (Val); rop.ll.call_function ("osl_texture_set_subimagename", opt, val); subimage_set = true; continue; } PARAM_STRING_CODE (interp, tex_interp_to_code, interpmode) if (name == Strings::alpha && valtype == TypeDesc::FLOAT) { alpha = rop.llvm_get_pointer (Val); if (Val.has_derivs()) { dalphadx = rop.llvm_get_pointer (Val, 1); dalphady = rop.llvm_get_pointer (Val, 2); // NO z derivs! dalphadz = rop.llvm_get_pointer (Val, 3); } continue; } if (name == Strings::errormessage && valtype == TypeDesc::STRING) { errormessage = rop.llvm_get_pointer (Val); continue; } if (name == Strings::missingcolor && equivalent(valtype,TypeDesc::TypeColor)) { if (! missingcolor) { // If not already done, allocate enough storage for the // missingcolor value (4 floats), and call the special // function that points the TextureOpt.missingcolor to it. missingcolor = rop.ll.op_alloca(rop.ll.type_float(), 4); rop.ll.call_function ("osl_texture_set_missingcolor_arena", opt, rop.ll.void_ptr(missingcolor)); } rop.ll.op_memcpy (rop.ll.void_ptr(missingcolor), rop.llvm_void_ptr(Val), (int)sizeof(Color3)); continue; } if (name == Strings::missingalpha && valtype == TypeDesc::FLOAT) { if (! missingcolor) { // If not already done, allocate enough storage for the // missingcolor value (4 floats), and call the special // function that points the TextureOpt.missingcolor to it. missingcolor = rop.ll.op_alloca(rop.ll.type_float(), 4); rop.ll.call_function ("osl_texture_set_missingcolor_arena", opt, rop.ll.void_ptr(missingcolor)); } llvm::Value *val = rop.llvm_load_value (Val); rop.ll.call_function ("osl_texture_set_missingcolor_alpha", opt, rop.ll.constant(nchans), val); continue; } rop.shadingcontext()->errorf("Unknown texture%s optional argument: \"%s\", <%s> (%s:%d)", tex3d ? "3d" : "", name, valtype, op.sourcefile(), op.sourceline()); #undef PARAM_INT #undef PARAM_FLOAT #undef PARAM_FLOAT_STR #undef PARAM_STRING_CODE #if 0 // Helps me find any constant optional params that aren't elided if (Name.is_constant() && Val.is_constant()) { std::cout << "! texture constant optional arg '" << name << "'\n"; if (Val.typespec().is_float()) std::cout << "\tf " << *(float *)Val.data() << "\n"; if (Val.typespec().is_int()) std::cout << "\ti " << *(int *)Val.data() << "\n"; if (Val.typespec().is_string()) std::cout << "\t" << *(ustring *)Val.data() << "\n"; } #endif } return opt; } LLVMGEN (llvm_gen_texture) { Opcode &op (rop.inst()->ops()[opnum]); Symbol &Result = *rop.opargsym (op, 0); Symbol &Filename = *rop.opargsym (op, 1); Symbol &S = *rop.opargsym (op, 2); Symbol &T = *rop.opargsym (op, 3); int nchans = Result.typespec().aggregate(); bool user_derivs = false; int first_optional_arg = 4; if (op.nargs() > 4 && rop.opargsym(op,4)->typespec().is_float()) { user_derivs = true; first_optional_arg = 8; OSL_DASSERT(rop.opargsym(op,5)->typespec().is_float()); OSL_DASSERT(rop.opargsym(op,6)->typespec().is_float()); OSL_DASSERT(rop.opargsym(op,7)->typespec().is_float()); } llvm::Value* opt; // TextureOpt llvm::Value *alpha = NULL, *dalphadx = NULL, *dalphady = NULL; llvm::Value *errormessage = NULL; opt = llvm_gen_texture_options (rop, opnum, first_optional_arg, false /*3d*/, nchans, alpha, dalphadx, dalphady, errormessage); RendererServices::TextureHandle *texture_handle = NULL; if (Filename.is_constant() && rop.shadingsys().opt_texture_handle()) { texture_handle = rop.renderer()->get_texture_handle (Filename.get_string(), rop.shadingcontext()); } // Now call the osl_texture function, passing the options and all the // explicit args like texture coordinates. llvm::Value * args[] = { rop.sg_void_ptr(), rop.llvm_load_value (Filename), rop.ll.constant_ptr (texture_handle), opt, rop.llvm_load_value (S), rop.llvm_load_value (T), user_derivs ? rop.llvm_load_value (*rop.opargsym (op, 4)) : rop.llvm_load_value (S, 1), user_derivs ? rop.llvm_load_value (*rop.opargsym (op, 5)) : rop.llvm_load_value (T, 1), user_derivs ? rop.llvm_load_value (*rop.opargsym (op, 6)) : rop.llvm_load_value (S, 2), user_derivs ? rop.llvm_load_value (*rop.opargsym (op, 7)) : rop.llvm_load_value (T, 2), rop.ll.constant (nchans), rop.ll.void_ptr (rop.llvm_get_pointer (Result, 0)), rop.ll.void_ptr (rop.llvm_get_pointer (Result, 1)), rop.ll.void_ptr (rop.llvm_get_pointer (Result, 2)), rop.ll.void_ptr (alpha ? alpha : rop.ll.void_ptr_null()), rop.ll.void_ptr (dalphadx ? dalphadx : rop.ll.void_ptr_null()), rop.ll.void_ptr (dalphady ? dalphady : rop.ll.void_ptr_null()), rop.ll.void_ptr (errormessage ? errormessage : rop.ll.void_ptr_null()), }; rop.ll.call_function ("osl_texture", args); rop.generated_texture_call (texture_handle != NULL); return true; } LLVMGEN (llvm_gen_texture3d) { Opcode &op (rop.inst()->ops()[opnum]); Symbol &Result = *rop.opargsym (op, 0); Symbol &Filename = *rop.opargsym (op, 1); Symbol &P = *rop.opargsym (op, 2); int nchans = Result.typespec().aggregate(); bool user_derivs = false; int first_optional_arg = 3; if (op.nargs() > 3 && rop.opargsym(op,3)->typespec().is_triple()) { user_derivs = true; first_optional_arg = 5; OSL_DASSERT(rop.opargsym(op,3)->typespec().is_triple()); OSL_DASSERT(rop.opargsym(op,4)->typespec().is_triple()); } llvm::Value* opt; // TextureOpt llvm::Value *alpha = NULL, *dalphadx = NULL, *dalphady = NULL; llvm::Value *errormessage = NULL; opt = llvm_gen_texture_options (rop, opnum, first_optional_arg, true /*3d*/, nchans, alpha, dalphadx, dalphady, errormessage); RendererServices::TextureHandle *texture_handle = NULL; if (Filename.is_constant() && rop.shadingsys().opt_texture_handle()) { texture_handle = rop.renderer()->get_texture_handle(Filename.get_string(), rop.shadingcontext()); } // Now call the osl_texture3d function, passing the options and all the // explicit args like texture coordinates. llvm::Value *args[] = { rop.sg_void_ptr(), rop.llvm_load_value (Filename), rop.ll.constant_ptr (texture_handle), opt, rop.llvm_void_ptr (P), // Auto derivs of P if !user_derivs user_derivs ? rop.llvm_void_ptr (*rop.opargsym (op, 3)) : rop.llvm_void_ptr (P, 1), user_derivs ? rop.llvm_void_ptr (*rop.opargsym (op, 4)) : rop.llvm_void_ptr (P, 2), rop.ll.constant (nchans), rop.ll.void_ptr (rop.llvm_void_ptr (Result, 0)), rop.ll.void_ptr (rop.llvm_void_ptr (Result, 1)), rop.ll.void_ptr (rop.llvm_void_ptr (Result, 2)), rop.ll.void_ptr (alpha ? alpha : rop.ll.void_ptr_null()), rop.ll.void_ptr (dalphadx ? dalphadx : rop.ll.void_ptr_null()), rop.ll.void_ptr (dalphady ? dalphady : rop.ll.void_ptr_null()), rop.ll.void_ptr (errormessage ? errormessage : rop.ll.void_ptr_null()), }; rop.ll.call_function ("osl_texture3d", args); rop.generated_texture_call (texture_handle != NULL); return true; } LLVMGEN (llvm_gen_environment) { Opcode &op (rop.inst()->ops()[opnum]); Symbol &Result = *rop.opargsym (op, 0); Symbol &Filename = *rop.opargsym (op, 1); Symbol &R = *rop.opargsym (op, 2); int nchans = Result.typespec().aggregate(); bool user_derivs = false; int first_optional_arg = 3; if (op.nargs() > 3 && rop.opargsym(op,3)->typespec().is_triple()) { user_derivs = true; first_optional_arg = 5; OSL_DASSERT(rop.opargsym(op,4)->typespec().is_triple()); } llvm::Value* opt; // TextureOpt llvm::Value *alpha = NULL, *dalphadx = NULL, *dalphady = NULL; llvm::Value *errormessage = NULL; opt = llvm_gen_texture_options (rop, opnum, first_optional_arg, false /*3d*/, nchans, alpha, dalphadx, dalphady, errormessage); RendererServices::TextureHandle *texture_handle = NULL; if (Filename.is_constant() && rop.shadingsys().opt_texture_handle()) { texture_handle = rop.renderer()->get_texture_handle(Filename.get_string(), rop.shadingcontext()); } // Now call the osl_environment function, passing the options and all the // explicit args like texture coordinates. llvm::Value *args[] = { rop.sg_void_ptr(), rop.llvm_load_value (Filename), rop.ll.constant_ptr (texture_handle), opt, rop.llvm_void_ptr (R), user_derivs ? rop.llvm_void_ptr (*rop.opargsym (op, 3)) : rop.llvm_void_ptr (R, 1), user_derivs ? rop.llvm_void_ptr (*rop.opargsym (op, 4)) : rop.llvm_void_ptr (R, 2), rop.ll.constant (nchans), rop.llvm_void_ptr (Result, 0), rop.llvm_void_ptr (Result, 1), rop.llvm_void_ptr (Result, 2), alpha ? rop.ll.void_ptr (alpha) : rop.ll.void_ptr_null(), dalphadx ? rop.ll.void_ptr (dalphadx) : rop.ll.void_ptr_null(), dalphady ? rop.ll.void_ptr (dalphady) : rop.ll.void_ptr_null(), rop.ll.void_ptr (errormessage ? errormessage : rop.ll.void_ptr_null()), }; rop.ll.call_function ("osl_environment", args); rop.generated_texture_call (texture_handle != NULL); return true; } static llvm::Value * llvm_gen_trace_options (BackendLLVM &rop, int opnum, int first_optional_arg) { llvm::Value* opt = rop.ll.call_function ("osl_get_trace_options", rop.sg_void_ptr()); Opcode &op (rop.inst()->ops()[opnum]); for (int a = first_optional_arg; a < op.nargs(); ++a) { Symbol &Name (*rop.opargsym(op,a)); OSL_DASSERT (Name.typespec().is_string() && "optional trace token must be a string"); OSL_DASSERT (a+1 < op.nargs() && "malformed argument list for trace"); ustring name = Name.get_string(); ++a; // advance to next argument Symbol &Val (*rop.opargsym(op,a)); TypeDesc valtype = Val.typespec().simpletype (); llvm::Value *val = rop.llvm_load_value (Val); if (name == Strings::mindist && valtype == TypeDesc::FLOAT) { rop.ll.call_function ("osl_trace_set_mindist", opt, val); } else if (name == Strings::maxdist && valtype == TypeDesc::FLOAT) { rop.ll.call_function ("osl_trace_set_maxdist", opt, val); } else if (name == Strings::shade && valtype == TypeDesc::INT) { rop.ll.call_function ("osl_trace_set_shade", opt, val); } else if (name == Strings::traceset && valtype == TypeDesc::STRING) { rop.ll.call_function ("osl_trace_set_traceset", opt, val); } else { rop.shadingcontext()->errorf("Unknown trace() optional argument: \"%s\", <%s> (%s:%d)", name, valtype, op.sourcefile(), op.sourceline()); } } return opt; } LLVMGEN (llvm_gen_trace) { Opcode &op (rop.inst()->ops()[opnum]); Symbol &Result = *rop.opargsym (op, 0); Symbol &Pos = *rop.opargsym (op, 1); Symbol &Dir = *rop.opargsym (op, 2); int first_optional_arg = 3; llvm::Value* opt; // TraceOpt opt = llvm_gen_trace_options (rop, opnum, first_optional_arg); // Now call the osl_trace function, passing the options and all the // explicit args like trace coordinates. llvm::Value *args[] = { rop.sg_void_ptr(), opt, rop.llvm_void_ptr (Pos, 0), rop.llvm_void_ptr (Pos, 1), rop.llvm_void_ptr (Pos, 2), rop.llvm_void_ptr (Dir, 0), rop.llvm_void_ptr (Dir, 1), rop.llvm_void_ptr (Dir, 2), }; llvm::Value *r = rop.ll.call_function ("osl_trace", args); rop.llvm_store_value (r, Result); return true; } static std::string arg_typecode (Symbol *sym, bool derivs) { const TypeSpec &t (sym->typespec()); if (t.is_int()) return "i"; else if (t.is_matrix()) return "m"; else if (t.is_string()) return "s"; std::string name; if (derivs) name = "d"; if (t.is_float()) name += "f"; else if (t.is_triple()) name += "v"; else OSL_ASSERT (0); return name; } static llvm::Value * llvm_gen_noise_options (BackendLLVM &rop, int opnum, int first_optional_arg) { llvm::Value* opt = rop.ll.call_function ("osl_get_noise_options", rop.sg_void_ptr()); Opcode &op (rop.inst()->ops()[opnum]); for (int a = first_optional_arg; a < op.nargs(); ++a) { Symbol &Name (*rop.opargsym(op,a)); OSL_DASSERT (Name.typespec().is_string() && "optional noise token must be a string"); OSL_DASSERT (a+1 < op.nargs() && "malformed argument list for noise"); ustring name = Name.get_string(); ++a; // advance to next argument Symbol &Val (*rop.opargsym(op,a)); TypeDesc valtype = Val.typespec().simpletype (); if (name.empty()) // skip empty string param name continue; if (name == Strings::anisotropic && Val.typespec().is_int()) { rop.ll.call_function ("osl_noiseparams_set_anisotropic", opt, rop.llvm_load_value (Val)); } else if (name == Strings::do_filter && Val.typespec().is_int()) { rop.ll.call_function ("osl_noiseparams_set_do_filter", opt, rop.llvm_load_value (Val)); } else if (name == Strings::direction && Val.typespec().is_triple()) { rop.ll.call_function ("osl_noiseparams_set_direction", opt, rop.llvm_void_ptr (Val)); } else if (name == Strings::bandwidth && (Val.typespec().is_float() || Val.typespec().is_int())) { rop.ll.call_function ("osl_noiseparams_set_bandwidth", opt, rop.llvm_load_value (Val, 0, NULL, 0, TypeDesc::TypeFloat)); } else if (name == Strings::impulses && (Val.typespec().is_float() || Val.typespec().is_int())) { rop.ll.call_function ("osl_noiseparams_set_impulses", opt, rop.llvm_load_value (Val, 0, NULL, 0, TypeDesc::TypeFloat)); } else { rop.shadingcontext()->errorf("Unknown %s optional argument: \"%s\", <%s> (%s:%d)", op.opname(), name, valtype, op.sourcefile(), op.sourceline()); } } return opt; } // T noise ([string name,] float s, ...); // T noise ([string name,] float s, float t, ...); // T noise ([string name,] point P, ...); // T noise ([string name,] point P, float t, ...); // T pnoise ([string name,] float s, float sper, ...); // T pnoise ([string name,] float s, float t, float sper, float tper, ...); // T pnoise ([string name,] point P, point Pper, ...); // T pnoise ([string name,] point P, float t, point Pper, float tper, ...); LLVMGEN (llvm_gen_noise) { Opcode &op (rop.inst()->ops()[opnum]); bool periodic = (op.opname() == Strings::pnoise || op.opname() == Strings::psnoise); int arg = 0; // Next arg to read Symbol &Result = *rop.opargsym (op, arg++); int outdim = Result.typespec().is_triple() ? 3 : 1; Symbol *Name = rop.opargsym (op, arg++); ustring name; if (Name->typespec().is_string()) { name = Name->is_constant() ? Name->get_string() : ustring(); } else { // Not a string, must be the old-style noise/pnoise --arg; // forget that arg Name = NULL; name = op.opname(); } Symbol *S = rop.opargsym (op, arg++), *T = NULL; Symbol *Sper = NULL, *Tper = NULL; int indim = S->typespec().is_triple() ? 3 : 1; bool derivs = S->has_derivs(); if (periodic) { if (op.nargs() > (arg+1) && (rop.opargsym(op,arg+1)->typespec().is_float() || rop.opargsym(op,arg+1)->typespec().is_triple())) { // 2D or 4D ++indim; T = rop.opargsym (op, arg++); derivs |= T->has_derivs(); } Sper = rop.opargsym (op, arg++); if (indim == 2 || indim == 4) Tper = rop.opargsym (op, arg++); } else { // non-periodic case if (op.nargs() > arg && rop.opargsym(op,arg)->typespec().is_float()) { // either 2D or 4D, so needs a second index ++indim; T = rop.opargsym (op, arg++); derivs |= T->has_derivs(); } } derivs &= Result.has_derivs(); // ignore derivs if result doesn't need bool pass_name = false, pass_sg = false, pass_options = false; if (name.empty()) { // name is not a constant name = periodic ? Strings::genericpnoise : Strings::genericnoise; pass_name = true; pass_sg = true; pass_options = true; derivs = true; // always take derivs if we don't know noise type } else if (name == Strings::perlin || name == Strings::snoise || name == Strings::psnoise) { name = periodic ? Strings::psnoise : Strings::snoise; // derivs = false; } else if (name == Strings::uperlin || name == Strings::noise || name == Strings::pnoise) { name = periodic ? Strings::pnoise : Strings::noise; // derivs = false; } else if (name == Strings::cell || name == Strings::cellnoise) { name = periodic ? Strings::pcellnoise : Strings::cellnoise; derivs = false; // cell noise derivs are always zero } else if (name == Strings::hash || name == Strings::hashnoise) { name = periodic ? Strings::phashnoise : Strings::hashnoise; derivs = false; // hash noise derivs are always zero } else if (name == Strings::simplex && !periodic) { name = Strings::simplexnoise; } else if (name == Strings::usimplex && !periodic) { name = Strings::usimplexnoise; } else if (name == Strings::gabor) { // already named pass_name = true; pass_sg = true; pass_options = true; derivs = true; name = periodic ? Strings::gaborpnoise : Strings::gabornoise; } else { rop.shadingcontext()->errorf("%snoise type \"%s\" is unknown, called from (%s:%d)", (periodic ? "periodic " : ""), name, op.sourcefile(), op.sourceline()); return false; } if (rop.shadingsys().no_noise()) { // renderer option to replace noise with constant value. This can be // useful as a profiling aid, to see how much it speeds up to have // trivial expense for noise calls. if (name == Strings::uperlin || name == Strings::noise || name == Strings::usimplexnoise || name == Strings::usimplex || name == Strings::cell || name == Strings::cellnoise || name == Strings::hash || name == Strings::hashnoise || name == Strings::pcellnoise || name == Strings::pnoise) name = ustring("unullnoise"); else name = ustring("nullnoise"); pass_name = false; periodic = false; pass_sg = false; pass_options = false; } llvm::Value *opt = NULL; if (pass_options) { opt = llvm_gen_noise_options (rop, opnum, arg); } std::string funcname = "osl_" + name.string() + "_" + arg_typecode(&Result,derivs); llvm::Value * args[10]; int nargs = 0; if (pass_name) { args[nargs++] = rop.llvm_load_string (*Name); } llvm::Value *tmpresult = NULL; // triple return, or float return with derivs, passes result pointer if (outdim == 3 || derivs) { if (derivs && !Result.has_derivs()) { tmpresult = rop.llvm_load_arg (Result, true); args[nargs++] = tmpresult; } else args[nargs++] = rop.llvm_void_ptr (Result); } funcname += arg_typecode(S, derivs); args[nargs++] = rop.llvm_load_arg (*S, derivs); if (T) { funcname += arg_typecode(T, derivs); args[nargs++] = rop.llvm_load_arg (*T, derivs); } if (periodic) { funcname += arg_typecode (Sper, false /* no derivs */); args[nargs++] = rop.llvm_load_arg (*Sper, false); if (Tper) { funcname += arg_typecode (Tper, false /* no derivs */); args[nargs++] = rop.llvm_load_arg (*Tper, false); } } if (pass_sg) args[nargs++] = rop.sg_void_ptr(); if (pass_options) args[nargs++] = opt; OSL_DASSERT(nargs < int(sizeof(args) / sizeof(args[0]))); #if 0 llvm::outs() << "About to push " << funcname << "\n"; for (int i = 0; i < nargs; ++i) llvm::outs() << " " << *args[i] << "\n"; #endif llvm::Value *r = rop.ll.call_function (funcname.c_str(), cspan<llvm::Value*>(args, args + nargs)); if (outdim == 1 && !derivs) { // Just plain float (no derivs) returns its value rop.llvm_store_value (r, Result); } else if (derivs && !Result.has_derivs()) { // Function needed to take derivs, but our result doesn't have them. // We created a temp, now we need to copy to the real result. tmpresult = rop.llvm_ptr_cast (tmpresult, Result.typespec()); for (int c = 0; c < Result.typespec().aggregate(); ++c) { llvm::Value *v = rop.llvm_load_value (tmpresult, Result.typespec(), 0, NULL, c); rop.llvm_store_value (v, Result, 0, c); } } // N.B. other cases already stored their result in the right place // Clear derivs if result has them but we couldn't compute them if (Result.has_derivs() && !derivs) rop.llvm_zero_derivs (Result); if (rop.shadingsys().profile() >= 1) rop.ll.call_function ("osl_count_noise", rop.sg_void_ptr()); return true; } LLVMGEN (llvm_gen_getattribute) { // getattribute() has eight "flavors": // * getattribute (attribute_name, value) // * getattribute (attribute_name, value[]) // * getattribute (attribute_name, index, value) // * getattribute (attribute_name, index, value[]) // * getattribute (object, attribute_name, value) // * getattribute (object, attribute_name, value[]) // * getattribute (object, attribute_name, index, value) // * getattribute (object, attribute_name, index, value[]) Opcode &op (rop.inst()->ops()[opnum]); int nargs = op.nargs(); OSL_DASSERT(nargs >= 3 && nargs <= 5); bool array_lookup = rop.opargsym(op,nargs-2)->typespec().is_int(); bool object_lookup = rop.opargsym(op,2)->typespec().is_string() && nargs >= 4; int object_slot = (int)object_lookup; int attrib_slot = object_slot + 1; int index_slot = array_lookup ? nargs - 2 : 0; Symbol& Result = *rop.opargsym (op, 0); Symbol& ObjectName = *rop.opargsym (op, object_slot); // only valid if object_slot is true Symbol& Attribute = *rop.opargsym (op, attrib_slot); Symbol& Index = *rop.opargsym (op, index_slot); // only valid if array_lookup is true Symbol& Destination = *rop.opargsym (op, nargs-1); OSL_DASSERT(!Result.typespec().is_closure_based() && !ObjectName.typespec().is_closure_based() && !Attribute.typespec().is_closure_based() && !Index.typespec().is_closure_based() && !Destination.typespec().is_closure_based()); // We'll pass the destination's attribute type directly to the // RenderServices callback so that the renderer can perform any // necessary conversions from its internal format to OSL's. const TypeDesc* dest_type = &Destination.typespec().simpletype(); llvm::Value * args[] = { rop.sg_void_ptr(), rop.ll.constant ((int)Destination.has_derivs()), object_lookup ? rop.llvm_load_value (ObjectName) : rop.ll.constant (ustring()), rop.llvm_load_value (Attribute), rop.ll.constant ((int)array_lookup), rop.llvm_load_value (Index), rop.ll.constant_ptr ((void *) dest_type), rop.llvm_void_ptr (Destination), }; llvm::Value *r = rop.ll.call_function ("osl_get_attribute", args); rop.llvm_store_value (r, Result); return true; } LLVMGEN (llvm_gen_gettextureinfo) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 4); Symbol& Result = *rop.opargsym (op, 0); Symbol& Filename = *rop.opargsym (op, 1); Symbol& Dataname = *rop.opargsym (op, 2); Symbol& Data = *rop.opargsym (op, 3); OSL_DASSERT(!Result.typespec().is_closure_based() && Filename.typespec().is_string() && Dataname.typespec().is_string() && !Data.typespec().is_closure_based() && Result.typespec().is_int()); RendererServices::TextureHandle *texture_handle = NULL; if (Filename.is_constant() && rop.shadingsys().opt_texture_handle()) { texture_handle = rop.renderer()->get_texture_handle(Filename.get_string(), rop.shadingcontext()); } llvm::Value * args[] = { rop.sg_void_ptr(), rop.llvm_load_value (Filename), rop.ll.constant_ptr (texture_handle), rop.llvm_load_value (Dataname), // this is passes a TypeDesc to an LLVM op-code rop.ll.constant((int) Data.typespec().simpletype().basetype), rop.ll.constant((int) Data.typespec().simpletype().arraylen), rop.ll.constant((int) Data.typespec().simpletype().aggregate), // destination rop.llvm_void_ptr (Data), // errormessage rop.ll.void_ptr_null(), }; llvm::Value *r = rop.ll.call_function ("osl_get_textureinfo", args); rop.llvm_store_value (r, Result); /* Do not leave derivs uninitialized */ if (Data.has_derivs()) rop.llvm_zero_derivs (Data); rop.generated_texture_call (texture_handle != NULL); return true; } LLVMGEN (llvm_gen_getmessage) { // getmessage() has four "flavors": // * getmessage (attribute_name, value) // * getmessage (attribute_name, value[]) // * getmessage (source, attribute_name, value) // * getmessage (source, attribute_name, value[]) Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 3 || op.nargs() == 4); int has_source = (op.nargs() == 4); Symbol& Result = *rop.opargsym (op, 0); Symbol& Source = *rop.opargsym (op, 1); Symbol& Name = *rop.opargsym (op, 1+has_source); Symbol& Data = *rop.opargsym (op, 2+has_source); OSL_DASSERT(Result.typespec().is_int() && Name.typespec().is_string()); OSL_DASSERT(has_source == 0 || Source.typespec().is_string()); llvm::Value *args[9]; args[0] = rop.sg_void_ptr(); args[1] = has_source ? rop.llvm_load_value(Source) : rop.ll.constant(ustring()); args[2] = rop.llvm_load_value (Name); if (Data.typespec().is_closure_based()) { // FIXME: secret handshake for closures ... args[3] = rop.ll.constant (TypeDesc(TypeDesc::UNKNOWN, Data.typespec().arraylength())); // We need a void ** here so the function can modify the closure args[4] = rop.llvm_void_ptr(Data); } else { args[3] = rop.ll.constant (Data.typespec().simpletype()); args[4] = rop.llvm_void_ptr (Data); } args[5] = rop.ll.constant ((int)Data.has_derivs()); args[6] = rop.ll.constant(rop.inst()->id()); args[7] = rop.ll.constant(op.sourcefile()); args[8] = rop.ll.constant(op.sourceline()); llvm::Value *r = rop.ll.call_function ("osl_getmessage", args); rop.llvm_store_value (r, Result); return true; } LLVMGEN (llvm_gen_setmessage) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 2); Symbol& Name = *rop.opargsym (op, 0); Symbol& Data = *rop.opargsym (op, 1); OSL_DASSERT(Name.typespec().is_string()); llvm::Value *args[7]; args[0] = rop.sg_void_ptr(); args[1] = rop.llvm_load_value (Name); if (Data.typespec().is_closure_based()) { // FIXME: secret handshake for closures ... args[2] = rop.ll.constant (TypeDesc(TypeDesc::UNKNOWN, Data.typespec().arraylength())); // We need a void ** here so the function can modify the closure args[3] = rop.llvm_void_ptr(Data); } else { args[2] = rop.ll.constant (Data.typespec().simpletype()); args[3] = rop.llvm_void_ptr (Data); } args[4] = rop.ll.constant(rop.inst()->id()); args[5] = rop.ll.constant(op.sourcefile()); args[6] = rop.ll.constant(op.sourceline()); rop.ll.call_function ("osl_setmessage", args); return true; } LLVMGEN (llvm_gen_get_simple_SG_field) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 1); Symbol& Result = *rop.opargsym (op, 0); int sg_index = rop.ShaderGlobalNameToIndex (op.opname()); OSL_DASSERT (sg_index >= 0); llvm::Value *sg_field = rop.ll.GEP (rop.sg_ptr(), 0, sg_index); llvm::Value* r = rop.ll.op_load(sg_field); rop.llvm_store_value (r, Result); return true; } LLVMGEN (llvm_gen_calculatenormal) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 2); Symbol& Result = *rop.opargsym (op, 0); Symbol& P = *rop.opargsym (op, 1); OSL_DASSERT(Result.typespec().is_triple() && P.typespec().is_triple()); if (! P.has_derivs()) { rop.llvm_assign_zero (Result); return true; } llvm::Value * args[] = { rop.llvm_void_ptr (Result), rop.sg_void_ptr(), rop.llvm_void_ptr (P), }; rop.ll.call_function ("osl_calculatenormal", args); if (Result.has_derivs()) rop.llvm_zero_derivs (Result); return true; } LLVMGEN (llvm_gen_area) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 2); Symbol& Result = *rop.opargsym (op, 0); Symbol& P = *rop.opargsym (op, 1); OSL_DASSERT(Result.typespec().is_float() && P.typespec().is_triple()); if (! P.has_derivs()) { rop.llvm_assign_zero (Result); return true; } llvm::Value *r = rop.ll.call_function ("osl_area", rop.llvm_void_ptr (P)); rop.llvm_store_value (r, Result); if (Result.has_derivs()) rop.llvm_zero_derivs (Result); return true; } LLVMGEN (llvm_gen_spline) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() >= 4 && op.nargs() <= 5); bool has_knot_count = (op.nargs() == 5); Symbol& Result = *rop.opargsym (op, 0); Symbol& Spline = *rop.opargsym (op, 1); Symbol& Value = *rop.opargsym (op, 2); Symbol& Knot_count = *rop.opargsym (op, 3); // might alias Knots Symbol& Knots = has_knot_count ? *rop.opargsym (op, 4) : *rop.opargsym (op, 3); OSL_DASSERT(!Result.typespec().is_closure_based() && Spline.typespec().is_string() && Value.typespec().is_float() && !Knots.typespec().is_closure_based() && Knots.typespec().is_array() && (!has_knot_count || (has_knot_count && Knot_count.typespec().is_int()))); std::string name = Strutil::sprintf("osl_%s_", op.opname()); // only use derivatives for result if: // result has derivs and (value || knots) have derivs bool result_derivs = Result.has_derivs() && (Value.has_derivs() || Knots.has_derivs()); if (result_derivs) name += "d"; if (Result.typespec().is_float()) name += "f"; else if (Result.typespec().is_triple()) name += "v"; if (result_derivs && Value.has_derivs()) name += "d"; if (Value.typespec().is_float()) name += "f"; else if (Value.typespec().is_triple()) name += "v"; if (result_derivs && Knots.has_derivs()) name += "d"; if (Knots.typespec().simpletype().elementtype() == TypeDesc::FLOAT) name += "f"; else if (Knots.typespec().simpletype().elementtype().aggregate == TypeDesc::VEC3) name += "v"; llvm::Value * args[] = { rop.llvm_void_ptr (Result), rop.llvm_load_string (Spline), rop.llvm_void_ptr (Value), // make things easy rop.llvm_void_ptr (Knots), has_knot_count ? rop.llvm_load_value (Knot_count) : rop.ll.constant ((int)Knots.typespec().arraylength()), rop.ll.constant ((int)Knots.typespec().arraylength()), }; rop.ll.call_function (name.c_str(), args); if (Result.has_derivs() && !result_derivs) rop.llvm_zero_derivs (Result); return true; } static void llvm_gen_keyword_fill(BackendLLVM &rop, Opcode &op, const ClosureRegistry::ClosureEntry *clentry, ustring clname, llvm::Value *mem_void_ptr, int argsoffset) { OSL_DASSERT(((op.nargs() - argsoffset) % 2) == 0); int Nattrs = (op.nargs() - argsoffset) / 2; for (int attr_i = 0; attr_i < Nattrs; ++attr_i) { int argno = attr_i * 2 + argsoffset; Symbol &Key = *rop.opargsym (op, argno); Symbol &Value = *rop.opargsym (op, argno + 1); OSL_DASSERT(Key.typespec().is_string()); OSL_ASSERT(Key.is_constant()); ustring key = Key.get_string(); TypeDesc ValueType = Value.typespec().simpletype(); bool legal = false; // Make sure there is some keyword arg that has the name and the type for (int t = 0; t < clentry->nkeyword; ++t) { const ClosureParam &p = clentry->params[clentry->nformal + t]; // strcmp might be too much, we could precompute the ustring for the param, // but in this part of the code is not a big deal if (equivalent(p.type,ValueType) && !strcmp(key.c_str(), p.key)) { // store data OSL_DASSERT(p.offset + p.field_size <= clentry->struct_size); llvm::Value* dst = rop.ll.offset_ptr (mem_void_ptr, p.offset); llvm::Value* src = rop.llvm_void_ptr (Value); rop.ll.op_memcpy (dst, src, (int)p.type.size(), 4 /* use 4 byte alignment for now */); legal = true; break; } } if (!legal) { rop.shadingcontext()->warningf("Unsupported closure keyword arg \"%s\" for %s (%s:%d)", key, clname, op.sourcefile(), op.sourceline()); } } } LLVMGEN (llvm_gen_closure) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT (op.nargs() >= 2); // at least the result and the ID Symbol &Result = *rop.opargsym (op, 0); int weighted = rop.opargsym(op,1)->typespec().is_string() ? 0 : 1; Symbol *weight = weighted ? rop.opargsym (op, 1) : NULL; Symbol &Id = *rop.opargsym (op, 1+weighted); OSL_DASSERT(Result.typespec().is_closure()); OSL_DASSERT(Id.typespec().is_string()); ustring closure_name = Id.get_string(); const ClosureRegistry::ClosureEntry * clentry = rop.shadingsys().find_closure(closure_name); if (!clentry) { rop.llvm_gen_error (Strutil::sprintf("Closure '%s' is not supported by the current renderer, called from %s:%d in shader \"%s\", layer %d \"%s\", group \"%s\"", closure_name, op.sourcefile(), op.sourceline(), rop.inst()->shadername(), rop.layer(), rop.inst()->layername(), rop.group().name())); return false; } OSL_DASSERT (op.nargs() >= (2 + weighted + clentry->nformal)); // Call osl_allocate_closure_component(closure, id, size). It returns // the memory for the closure parameter data. llvm::Value *render_ptr = rop.ll.constant_ptr(rop.shadingsys().renderer(), rop.ll.type_void_ptr()); llvm::Value *sg_ptr = rop.sg_void_ptr(); llvm::Value *id_int = rop.ll.constant(clentry->id); llvm::Value *size_int = rop.ll.constant(clentry->struct_size); llvm::Value *return_ptr = weighted ? rop.ll.call_function ("osl_allocate_weighted_closure_component", sg_ptr, id_int, size_int, rop.llvm_void_ptr(*weight)) : rop.ll.call_function ("osl_allocate_closure_component" , sg_ptr, id_int, size_int); llvm::Value *comp_void_ptr = return_ptr; // For the weighted closures, we need a surrounding "if" so that it's safe // for osl_allocate_weighted_closure_component to return NULL (unless we // know for sure that it's constant weighted and that the weight is // not zero). llvm::BasicBlock *next_block = NULL; if (weighted && ! (weight->is_constant() && !rop.is_zero(*weight))) { llvm::BasicBlock *notnull_block = rop.ll.new_basic_block ("non_null_closure"); next_block = rop.ll.new_basic_block (""); llvm::Value *cond = rop.ll.op_ne (return_ptr, rop.ll.void_ptr_null()); rop.ll.op_branch (cond, notnull_block, next_block); // new insert point is nonnull_block } llvm::Value *comp_ptr = rop.ll.ptr_cast(comp_void_ptr, rop.llvm_type_closure_component_ptr()); // Get the address of the primitive buffer, which is the 2nd field llvm::Value *mem_void_ptr = rop.ll.GEP (comp_ptr, 0, 2); mem_void_ptr = rop.ll.ptr_cast(mem_void_ptr, rop.ll.type_void_ptr()); // If the closure has a "prepare" method, call // prepare(renderer, id, memptr). If there is no prepare method, just // zero out the closure parameter memory. if (clentry->prepare) { // Call clentry->prepare(renderservices *, int id, void *mem) llvm::Value *funct_ptr = rop.ll.constant_ptr((void *)clentry->prepare, rop.llvm_type_prepare_closure_func()); llvm::Value *args[] = {render_ptr, id_int, mem_void_ptr}; rop.ll.call_function (funct_ptr, args); } else { rop.ll.op_memset (mem_void_ptr, 0, clentry->struct_size, 4 /*align*/); } // Here is where we fill the struct using the params for (int carg = 0; carg < clentry->nformal; ++carg) { const ClosureParam &p = clentry->params[carg]; if (p.key != NULL) break; OSL_DASSERT(p.offset + p.field_size <= clentry->struct_size); Symbol &sym = *rop.opargsym (op, carg + 2 + weighted); TypeDesc t = sym.typespec().simpletype(); if (rop.use_optix() && sym.typespec().is_string()) { llvm::Value* dst = rop.ll.offset_ptr (mem_void_ptr, p.offset); llvm::Value* src = rop.llvm_load_device_string (sym, /*follow*/ false); rop.ll.op_memcpy (dst, src, 8, 8); } else if (!sym.typespec().is_closure_array() && !sym.typespec().is_structure() && equivalent(t,p.type)) { llvm::Value* dst = rop.ll.offset_ptr (mem_void_ptr, p.offset); llvm::Value* src = rop.llvm_void_ptr (sym); rop.ll.op_memcpy (dst, src, (int)p.type.size(), 4 /* use 4 byte alignment for now */); } else { rop.shadingcontext()->errorf("Incompatible formal argument %d to '%s' closure (%s %s, expected %s). Prototypes don't match renderer registry (%s:%d).", carg + 1, closure_name, sym.typespec(), sym.unmangled(), p.type, op.sourcefile(), op.sourceline()); } } // If the closure has a "setup" method, call // setup(render_services, id, mem_ptr). if (clentry->setup) { // Call clentry->setup(renderservices *, int id, void *mem) llvm::Value *funct_ptr = rop.ll.constant_ptr((void *)clentry->setup, rop.llvm_type_setup_closure_func()); llvm::Value *args[] = {render_ptr, id_int, mem_void_ptr}; rop.ll.call_function (funct_ptr, args); } llvm_gen_keyword_fill(rop, op, clentry, closure_name, mem_void_ptr, 2 + weighted + clentry->nformal); if (next_block) rop.ll.op_branch (next_block); // Store result at the end, otherwise Ci = modifier(Ci) won't work rop.llvm_store_value (return_ptr, Result, 0, NULL, 0); return true; } LLVMGEN (llvm_gen_pointcloud_search) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() >= 5); Symbol& Result = *rop.opargsym (op, 0); Symbol& Filename = *rop.opargsym (op, 1); Symbol& Center = *rop.opargsym (op, 2); Symbol& Radius = *rop.opargsym (op, 3); Symbol& Max_points = *rop.opargsym (op, 4); OSL_DASSERT(Result.typespec().is_int() && Filename.typespec().is_string() && Center.typespec().is_triple() && Radius.typespec().is_float() && Max_points.typespec().is_int()); std::vector<Symbol *> clear_derivs_of; // arguments whose derivs we need to zero at the end int attr_arg_offset = 5; // where the opt attrs begin Symbol *Sort = NULL; if (op.nargs() > 5 && rop.opargsym(op,5)->typespec().is_int()) { Sort = rop.opargsym(op,5); ++attr_arg_offset; } int nattrs = (op.nargs() - attr_arg_offset) / 2; std::vector<llvm::Value *> args; args.push_back (rop.sg_void_ptr()); // 0 sg args.push_back (rop.llvm_load_value (Filename)); // 1 filename args.push_back (rop.llvm_void_ptr (Center)); // 2 center args.push_back (rop.llvm_load_value (Radius)); // 3 radius args.push_back (rop.llvm_load_value (Max_points)); // 4 max_points args.push_back (Sort ? rop.llvm_load_value(*Sort) // 5 sort : rop.ll.constant(0)); args.push_back (rop.ll.constant_ptr (NULL)); // 6 indices args.push_back (rop.ll.constant_ptr (NULL)); // 7 distances args.push_back (rop.ll.constant (0)); // 8 derivs_offset args.push_back (NULL); // 9 nattrs size_t capacity = 0x7FFFFFFF; // Lets put a 32 bit limit int extra_attrs = 0; // Extra query attrs to search // This loop does three things. 1) Look for the special attributes // "distance", "index" and grab the pointer. 2) Compute the minimmum // size of the provided output arrays to check against max_points // 3) push optional args to the arg list for (int i = 0; i < nattrs; ++i) { Symbol& Name = *rop.opargsym (op, attr_arg_offset + i*2); Symbol& Value = *rop.opargsym (op, attr_arg_offset + i*2 + 1); OSL_DASSERT (Name.typespec().is_string()); TypeDesc simpletype = Value.typespec().simpletype(); if (Name.is_constant() && Name.get_string() == u_index && simpletype.elementtype() == TypeDesc::INT) { args[6] = rop.llvm_void_ptr (Value); } else if (Name.is_constant() && Name.get_string() == u_distance && simpletype.elementtype() == TypeDesc::FLOAT) { args[7] = rop.llvm_void_ptr (Value); if (Value.has_derivs()) { if (Center.has_derivs()) // deriv offset is the size of the array args[8] = rop.ll.constant ((int)simpletype.numelements()); else clear_derivs_of.push_back(&Value); } } else { // It is a regular attribute, push it to the arg list args.push_back (rop.llvm_load_value (Name)); args.push_back (rop.ll.constant (simpletype)); args.push_back (rop.llvm_void_ptr (Value)); if (Value.has_derivs()) clear_derivs_of.push_back(&Value); extra_attrs++; } // minimum capacity of the output arrays capacity = std::min (simpletype.numelements(), capacity); } args[9] = rop.ll.constant (extra_attrs); // Compare capacity to the requested number of points. The available // space on the arrays is a constant, the requested number of // points is not, so runtime check. llvm::Value *sizeok = rop.ll.op_ge (rop.ll.constant((int)capacity), args[4]); // max_points llvm::BasicBlock* sizeok_block = rop.ll.new_basic_block ("then"); llvm::BasicBlock* badsize_block = rop.ll.new_basic_block ("else"); llvm::BasicBlock* after_block = rop.ll.new_basic_block (""); rop.ll.op_branch (sizeok, sizeok_block, badsize_block); // N.B. the op_branch sets sizeok_block as the new insert point // non-error code case llvm::Value *count = rop.ll.call_function ("osl_pointcloud_search", args); // Clear derivs if necessary for (size_t i = 0; i < clear_derivs_of.size(); ++i) rop.llvm_zero_derivs (*clear_derivs_of[i], count); // Store result rop.llvm_store_value (count, Result); rop.ll.op_branch (after_block); // error code case rop.ll.set_insert_point (badsize_block); args.clear(); static ustring errorfmt("Arrays too small for pointcloud lookup at (%s:%d)"); llvm::Value *err_args[] = { rop.sg_void_ptr(), rop.ll.constant_ptr ((void *)errorfmt.c_str()), rop.ll.constant_ptr ((void *)op.sourcefile().c_str()), rop.ll.constant (op.sourceline()), }; rop.ll.call_function ("osl_error", err_args); rop.ll.op_branch (after_block); return true; } LLVMGEN (llvm_gen_pointcloud_get) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() >= 6); Symbol& Result = *rop.opargsym (op, 0); Symbol& Filename = *rop.opargsym (op, 1); Symbol& Indices = *rop.opargsym (op, 2); Symbol& Count = *rop.opargsym (op, 3); Symbol& Attr_name = *rop.opargsym (op, 4); Symbol& Data = *rop.opargsym (op, 5); llvm::Value *count = rop.llvm_load_value (Count); int capacity = std::min ((int)Data.typespec().simpletype().numelements(), (int)Indices.typespec().simpletype().numelements()); // Check available space llvm::Value *sizeok = rop.ll.op_ge (rop.ll.constant(capacity), count); llvm::BasicBlock* sizeok_block = rop.ll.new_basic_block ("then"); llvm::BasicBlock* badsize_block = rop.ll.new_basic_block ("else"); llvm::BasicBlock* after_block = rop.ll.new_basic_block (""); rop.ll.op_branch (sizeok, sizeok_block, badsize_block); // N.B. sets insert point to true case // non-error code case // Convert 32bit indices to 64bit llvm::Value * args[] = { rop.sg_void_ptr(), rop.llvm_load_value (Filename), rop.llvm_void_ptr (Indices), count, rop.llvm_load_value (Attr_name), rop.ll.constant (Data.typespec().simpletype()), rop.llvm_void_ptr (Data), }; llvm::Value *found = rop.ll.call_function ("osl_pointcloud_get", args); rop.llvm_store_value (found, Result); if (Data.has_derivs()) rop.llvm_zero_derivs (Data, count); rop.ll.op_branch (after_block); // error code case rop.ll.set_insert_point (badsize_block); static ustring errorfmt("Arrays too small for pointcloud attribute get at (%s:%d)"); llvm::Value *err_args[] = { rop.sg_void_ptr(), rop.ll.constant_ptr ((void *)errorfmt.c_str()), rop.ll.constant_ptr ((void *)op.sourcefile().c_str()), rop.ll.constant (op.sourceline()), }; rop.ll.call_function ("osl_error", err_args); rop.ll.op_branch (after_block); return true; } LLVMGEN (llvm_gen_pointcloud_write) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() >= 3); Symbol& Result = *rop.opargsym (op, 0); Symbol& Filename = *rop.opargsym (op, 1); Symbol& Pos = *rop.opargsym (op, 2); OSL_DASSERT(Result.typespec().is_int() && Filename.typespec().is_string() && Pos.typespec().is_triple()); OSL_DASSERT((op.nargs() & 1) && "must have an even number of attribs"); int nattrs = (op.nargs() - 3) / 2; // Generate local space for the names/types/values arrays llvm::Value *names = rop.ll.op_alloca (rop.ll.type_string(), nattrs); llvm::Value *types = rop.ll.op_alloca (rop.ll.type_typedesc(), nattrs); llvm::Value *values = rop.ll.op_alloca (rop.ll.type_void_ptr(), nattrs); // Fill in the arrays with the params, use helper function because // it's a pain to offset things into the array ourselves. for (int i = 0; i < nattrs; ++i) { Symbol *namesym = rop.opargsym (op, 3+2*i); Symbol *valsym = rop.opargsym (op, 3+2*i+1); llvm::Value * args[] = { rop.ll.void_ptr (names), rop.ll.void_ptr (types), rop.ll.void_ptr (values), rop.ll.constant (i), rop.llvm_load_value (*namesym), // name[i] rop.ll.constant (valsym->typespec().simpletype()), // type[i] rop.llvm_void_ptr (*valsym) // value[i] }; rop.ll.call_function ("osl_pointcloud_write_helper", args); } llvm::Value * args[] = { rop.sg_void_ptr(), // shaderglobals pointer rop.llvm_load_value (Filename), // name rop.llvm_void_ptr (Pos), // position rop.ll.constant (nattrs), // number of attributes rop.ll.void_ptr (names), // attribute names array rop.ll.void_ptr (types), // attribute types array rop.ll.void_ptr (values) // attribute values array }; llvm::Value *ret = rop.ll.call_function ("osl_pointcloud_write", args); rop.llvm_store_value (ret, Result); return true; } LLVMGEN (llvm_gen_dict_find) { // OSL has two variants of this function: // dict_find (string dict, string query) // dict_find (int nodeID, string query) Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 3); Symbol& Result = *rop.opargsym (op, 0); Symbol& Source = *rop.opargsym (op, 1); Symbol& Query = *rop.opargsym (op, 2); OSL_DASSERT(Result.typespec().is_int() && Query.typespec().is_string() && (Source.typespec().is_int() || Source.typespec().is_string())); bool sourceint = Source.typespec().is_int(); // is it an int? llvm::Value *args[] = { rop.sg_void_ptr(), rop.llvm_load_value(Source), rop.llvm_load_value (Query) }; const char *func = sourceint ? "osl_dict_find_iis" : "osl_dict_find_iss"; llvm::Value *ret = rop.ll.call_function (func, args); rop.llvm_store_value (ret, Result); return true; } LLVMGEN (llvm_gen_dict_next) { // dict_net is very straightforward -- just insert sg ptr as first arg Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 2); Symbol& Result = *rop.opargsym (op, 0); Symbol& NodeID = *rop.opargsym (op, 1); OSL_DASSERT(Result.typespec().is_int() && NodeID.typespec().is_int()); llvm::Value *ret = rop.ll.call_function ("osl_dict_next", rop.sg_void_ptr(), rop.llvm_load_value(NodeID)); rop.llvm_store_value (ret, Result); return true; } LLVMGEN (llvm_gen_dict_value) { // int dict_value (int nodeID, string attribname, output TYPE value) Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 4); Symbol& Result = *rop.opargsym (op, 0); Symbol& NodeID = *rop.opargsym (op, 1); Symbol& Name = *rop.opargsym (op, 2); Symbol& Value = *rop.opargsym (op, 3); OSL_DASSERT(Result.typespec().is_int() && NodeID.typespec().is_int() && Name.typespec().is_string()); llvm::Value *args[] = { rop.sg_void_ptr(), // arg 0: shaderglobals ptr rop.llvm_load_value(NodeID), // arg 1: nodeID rop.llvm_load_value(Name), // arg 2: attribute name rop.ll.constant(Value.typespec().simpletype()), // arg 3: encoded type of Value rop.llvm_void_ptr(Value), // arg 4: pointer to Value }; llvm::Value *ret = rop.ll.call_function ("osl_dict_value", args); rop.llvm_store_value (ret, Result); return true; } LLVMGEN (llvm_gen_split) { // int split (string str, output string result[], string sep, int maxsplit) Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() >= 3 && op.nargs() <= 5); Symbol& R = *rop.opargsym (op, 0); Symbol& Str = *rop.opargsym (op, 1); Symbol& Results = *rop.opargsym (op, 2); OSL_DASSERT(R.typespec().is_int() && Str.typespec().is_string() && Results.typespec().is_array() && Results.typespec().is_string_based()); llvm::Value *args[5]; args[0] = rop.llvm_load_value (Str); args[1] = rop.llvm_void_ptr (Results); if (op.nargs() >= 4) { Symbol& Sep = *rop.opargsym (op, 3); OSL_DASSERT(Sep.typespec().is_string()); args[2] = rop.llvm_load_value (Sep); } else { args[2] = rop.ll.constant (""); } if (op.nargs() >= 5) { Symbol& Maxsplit = *rop.opargsym (op, 4); OSL_DASSERT(Maxsplit.typespec().is_int()); args[3] = rop.llvm_load_value (Maxsplit); } else { args[3] = rop.ll.constant (Results.typespec().arraylength()); } args[4] = rop.ll.constant (Results.typespec().arraylength()); llvm::Value *ret = rop.ll.call_function ("osl_split", args); rop.llvm_store_value (ret, R); return true; } LLVMGEN (llvm_gen_raytype) { // int raytype (string name) Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT(op.nargs() == 2); Symbol& Result = *rop.opargsym (op, 0); Symbol& Name = *rop.opargsym (op, 1); llvm::Value *args[2] = { rop.sg_void_ptr(), NULL }; const char *func = NULL; if (Name.is_constant()) { // We can statically determine the bit pattern ustring name = Name.get_string(); args[1] = rop.ll.constant (rop.shadingsys().raytype_bit (name)); func = "osl_raytype_bit"; } else { // No way to know which name is being asked for args[1] = rop.llvm_get_pointer (Name); func = "osl_raytype_name"; } llvm::Value *ret = rop.ll.call_function (func, args); rop.llvm_store_value (ret, Result); return true; } // color blackbody (float temperatureK) // color wavelength_color (float wavelength_nm) // same function signature LLVMGEN (llvm_gen_blackbody) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT (op.nargs() == 2); Symbol &Result (*rop.opargsym (op, 0)); Symbol &Temperature (*rop.opargsym (op, 1)); OSL_DASSERT (Result.typespec().is_triple() && Temperature.typespec().is_float()); llvm::Value* args[] = { rop.sg_void_ptr(), rop.llvm_void_ptr(Result), rop.llvm_load_value(Temperature) }; rop.ll.call_function (Strutil::sprintf("osl_%s_vf",op.opname()).c_str(), args); // Punt, zero out derivs. // FIXME -- only of some day, someone truly needs blackbody() to // correctly return derivs with spatially-varying temperature. if (Result.has_derivs()) rop.llvm_zero_derivs (Result); return true; } // float luminance (color c) LLVMGEN (llvm_gen_luminance) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT (op.nargs() == 2); Symbol &Result (*rop.opargsym (op, 0)); Symbol &C (*rop.opargsym (op, 1)); OSL_DASSERT (Result.typespec().is_float() && C.typespec().is_triple()); bool deriv = C.has_derivs() && Result.has_derivs(); llvm::Value* args[] = { rop.sg_void_ptr(), rop.llvm_void_ptr(Result), rop.llvm_void_ptr(C) }; rop.ll.call_function (deriv ? "osl_luminance_dfdv" : "osl_luminance_fv", args); if (Result.has_derivs() && !C.has_derivs()) rop.llvm_zero_derivs (Result); return true; } LLVMGEN (llvm_gen_isconstant) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT (op.nargs() == 2); Symbol &Result (*rop.opargsym (op, 0)); OSL_DASSERT (Result.typespec().is_int()); Symbol &A (*rop.opargsym (op, 1)); rop.llvm_store_value (rop.ll.constant(A.is_constant() ? 1 : 0), Result); return true; } LLVMGEN (llvm_gen_functioncall) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT (op.nargs() == 1); llvm::BasicBlock* after_block = rop.ll.push_function (); unsigned int op_num_function_starts_at = opnum+1; unsigned int op_num_function_ends_at = op.jump(0); if (rop.ll.debug_is_enabled()) { Symbol &functionNameSymbol(*rop.opargsym (op, 0)); OSL_DASSERT(functionNameSymbol.is_constant()); OSL_DASSERT(functionNameSymbol.typespec().is_string()); ustring functionName = functionNameSymbol.get_string(); ustring file_name = rop.inst()->op(op_num_function_starts_at).sourcefile(); unsigned int method_line = rop.inst()->op(op_num_function_starts_at).sourceline(); rop.ll.debug_push_inlined_function(functionName, file_name, method_line); } // Generate the code for the body of the function rop.build_llvm_code (op_num_function_starts_at, op_num_function_ends_at); rop.ll.op_branch (after_block); // Continue on with the previous flow if (rop.ll.debug_is_enabled()) { rop.ll.debug_pop_inlined_function(); } rop.ll.pop_function (); return true; } LLVMGEN (llvm_gen_functioncall_nr) { OSL_ASSERT(rop.ll.debug_is_enabled() && "no return version should only exist when debug is enabled"); Opcode &op (rop.inst()->ops()[opnum]); OSL_ASSERT (op.nargs() == 1); Symbol &functionNameSymbol(*rop.opargsym (op, 0)); OSL_ASSERT(functionNameSymbol.is_constant()); OSL_ASSERT(functionNameSymbol.typespec().is_string()); ustring functionName = functionNameSymbol.get_string(); int op_num_function_starts_at = opnum+1; int op_num_function_ends_at = op.jump(0); OSL_ASSERT(op.farthest_jump() == op_num_function_ends_at && "As we are not doing any branching, we should ensure that the inlined function truly ends at the farthest jump"); const Opcode& startop(rop.inst()->op(op_num_function_starts_at)); rop.ll.debug_push_inlined_function(functionName, startop.sourcefile(), startop.sourceline()); // Generate the code for the body of the function rop.build_llvm_code (op_num_function_starts_at, op_num_function_ends_at); // Continue on with the previous flow rop.ll.debug_pop_inlined_function(); return true; } LLVMGEN (llvm_gen_return) { Opcode &op (rop.inst()->ops()[opnum]); OSL_DASSERT (op.nargs() == 0); if (op.opname() == Strings::op_exit) { // If it's a real "exit", totally jump out of the shader instance. // The exit instance block will be created if it doesn't yet exist. rop.ll.op_branch (rop.llvm_exit_instance_block()); } else { // If it's a "return", jump to the exit point of the function. rop.ll.op_branch (rop.ll.return_block()); } llvm::BasicBlock* next_block = rop.ll.new_basic_block (""); rop.ll.set_insert_point (next_block); return true; } OSL_PRAGMA_WARNING_PUSH OSL_GCC_PRAGMA(GCC diagnostic ignored "-Wunused-parameter") LLVMGEN (llvm_gen_end) { // Dummy routine needed only for the op_descriptor table return false; } OSL_PRAGMA_WARNING_POP }; // namespace pvt OSL_NAMESPACE_EXIT
6c80207f8c3606eeccafbd57bd7d7d6572b6f094
8898322737a937d5bddd808f098393b3a58e9758
/C++/file.cpp
bb58c624578e2af2691f62a4888984163c0e28ae
[]
no_license
drycota/C
d692011d08a124b3f74370793a711ea4490a5137
d416779b95ed712eca3bd8d68550a12df89a0f1f
refs/heads/master
2020-04-22T04:41:10.404206
2019-02-11T13:27:38
2019-02-11T13:27:38
170,131,478
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
49,072
cpp
file.cpp
#include "pch.h" #include "file.h" // Функции библиотеки stdio.h /* Функции библиотеки stdio.h -------------------------------------------------------------------------------- FILE *fopen(const char *filename, const char *mode) Функция открывает файл. filename - путь к файлу mode - тип доступа r - чтение, если файла нет, то данная функция генерирует ошибку (возвращает 0) w - запись, если файла нет, то файл создаётся, если есть исходное содержимое удаляется a - добавление в конец, если файла нет, то он создаётся r+ чтение и запись (файл должен существовать) w+ - чтение и запись (принцип работы как у w) a+ - добавление и чтение (принцип работы как у a) Примечание: Все вышеописанные режимы предназначены для текстового открытия файла. Для двоичного открытия перед режимом достаточно добавить букву b. Например, br. Если функция отработала успешно, из неё возвращается указатель на открытый файл, в противном случае - нуль. Примечание: Указатель на открытый файл принято хранить в типе данных FILE*. -------------------------------------------------------------------------------- int fclose( FILE *stream ) Функция закрывает файл. stream - указатель на закрываемый файл. Если всё проходит успешно, то данная функция возвращает 0, или EOF в случае ошибки. Примечание: EOF (End Of File) - обозначение конца файла. -------------------------------------------------------------------------------- char *fgets( char *string, int n, FILE *stream ) Считывает строку начиная с текущей позиции. Считывание останавливается: ...если был найден символ перехода на новую строчку ( он помещается в строку ) ...если достигнут конец файла ...если считано n-1 символов. string - cтрока, в которую попадают считанные данные n - количество элементов в string stream - указатель на открытый файл Если всё прошло успешно функция возвращает считанную строку, если произошла ошибка или достигнут конец файла возвращается 0. -------------------------------------------------------------------------------- int fputs( const char *string, FILE *stream ) Записывает строку в файл, начиная с текущей позиции. string - строка для записи stream - указатель на открытый файл, куда производиться запись Если функция отрабатывает успешно из неё возвращается неотрицательное значение. При ошибке возвращается EOF. -------------------------------------------------------------------------------- size_t fread( void *buffer, size_t size, size_t count, FILE *stream ) Функция считывает данные из файла в буфер. buffer - адрес массива, куда запишутся данные size - размер элемента массива в байтах count - максимальное количество элементов для считывания stream - указатель на открытый файл. Функция возвращает количество считанных байт. Примечание: Тип данных size_t определен в библиотеке stdio.h следующим образом: typedef unsigned int size_t;. Другими словами, это обычный беззнаковый int. -------------------------------------------------------------------------------- size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream ) Функция записывает массив данных в файл. buffer - адрес массива, где содержатся данные size - размер элемента массива в байтах count - максимальное количество элементов для записи в файл stream - указатель на открытый файл. Функция возвращает количество записанных байт. -------------------------------------------------------------------------------- int feof( FILE *stream ) Функция проверяет достигнут ли конец файла. stream - указатель на открытый файл Функция возвращает ненулевое значение, если достигнут конец файла, нуль возвращается в противном случае. -------------------------------------------------------------------------------- int _fileno( FILE *stream ) Данная функция возвращает дескриптор файла. stream - указатель на открытый файл. -------------------------------------------------------------------------------- int fseek ( FILE *stream, int offset [, int whence] ) Устанавливает смещение в файле stream - указатель на открытый файл offset - смещение, измеряемое в байтах от начала файла whence - точка, от которой производится смещение SEEK_SET (0) - начало файла SEEK_CUR (1) - позиция текущего указателя файла SEEK_END (2) - конец файла (EOF) Функция возвращает значение 0, если указатель файла успешно перемещен, и ненулевое значение в случае неудачного завершения. -------------------------------------------------------------------------------- */ // Набор функций для работы с файлами /* stdio.h - переименование и удаление файлов. -------------------------------------------------------------------------------- rename (char * oldname, char * newname) Переименовывает файл. oldname - путь и текущее имя файла newname - путь и новое имя файла Функция возвращает 0, если имя файла было успешно изменено, и ненулевое значение, если замена не произошла. Примечание: Кстати!!! Если указать не только новое имя, но и новый путь - файл будет не только переименован, но и перенесён. -------------------------------------------------------------------------------- int remove(const char * filename) Удаляет файл. filename - путь и имя файла Функция возвращает 0, если имя файл был успешно удален, и ненулевое значение, если удаление не произошло. Примечание: Помните!!! В момент удаления файл должен быть закрыт. Кроме того, не забывайте, что удаление необратимо. -------------------------------------------------------------------------------- io.h - поиск файлов. -------------------------------------------------------------------------------- _findfirst(char * path, _finddata_t * fileinfo) Находит файлы по указанному пути, соответсвтующие маске. Примечание: Маска - строка, критерий поиска, содержащая символы * (любая последовательность любых символов) и ? (любой один символ) path - строка, в которой содержится комбинация пути и маски. fileinfo - указатель на объект структуры, в который запишется информация о найденном файле. Структура содержит следующие поля: unsigned attrib - содержит информацию об атрибутах файла. _A_NORMAL - Обычный файл без запретов на чтение или запись. _A_RDONLY - Файл только для чтения. _A_HIDDEN - Скрытый файл. _A_SYSTEM - Системный файл. _A_SUBDIR - Директория. _A_ARCH - Архивный файл. time_t time_create - время/дата создания файла (равно -1 для FAT систем). time_t time_access - время/дата последнего открытия файла (равно -1 для FAT систем). time_t time_write - время/дата последнего редактирования файла _fsize_t size - размер файла char name[260] - имя файла Если всё пройдет успешно, информация о первом найденном файле запишется в объект структуры _finddata_t. При этом в оперативной памяти сформируется "список", обладающий внутренним указателем, который изначально будет установлен на первом найденном файле. В этом случае функция вернет уникальный номер, связанный с полученной группой файлов. Если поиск завершится неудачей, функция вернет -1. -------------------------------------------------------------------------------- _findnext(long done, _finddata_t * fileinfo) Функция осуществляет переход на следующий найденный файл в группе. done - уникальный номер группы файлов в памяти. fileinfo - указатель на объект структуры, в который запишется информация о следующем найденном файле. Если достигнут конец списка файлов, функция вернет -1. -------------------------------------------------------------------------------- _findclose(long done) Функция очищает память от группы найденных файлов. done - уникальный номер группы файлов в памяти. */ // Функции библиотеки io.h /* int _access( const char *path, int mode ) Функция определяет разрешения файла или директории. path - путь к файлу или директории mode - флаги для проверки 00 - проверка на существование 02 - проверка на разрешение на запись 04 - проверка на разрешение на чтение 06 - проверка на чтение и запись Если разрешение есть, функция возвращает ноль, в случае отсутствия -1. Примечание: Директории можно проверять только на существование. -------------------------------------------------------------------------------- long _filelength( int handle ) Возвращает размер файла в байтах. handle - дескриптор файла. В случае ошибки функция возвращает -1. -------------------------------------------------------------------------------- int _locking( int handle, int mode, long nbytes ) Блокирует или разблокирует байты файла начиная с текущей позиции в файле. handle - дескриптор файла mode - тип блокировки _LK_LOCK - блокирует байты, если заблокировать байты не получается попытка повторяется через 1 секунду.Если после 10 попыток байты не заблокируются функция генерирует ошибку и возвращает -1 _LK_NBLCK - блокирует байты, если заблокировать байты не получается функция генерирует ошибку и возвращает -1 _LK_NBRLCK - то же самое, что и _LK_NBLCK _LK_RLCK - то же самое, что и _LK_LOCK _LK_UNLCK - разблокировка байт, которые были до этого заблокированы nbytes - количество байт для блокировки Функция locking возвращает -1, если происходит ошибка и 0 в случае успеха. Примечание: Для работы этой функции кроме io.h, нужно подключить sys/locking.h */ // Операции по работе с директориями /* Библиотека direct.h -------------------------------------------------------------------------------- int _mkdir( const char *dirname ) Создает директорию по указанному пути. dirname - Путь и имя для создаваемой директории. -------------------------------------------------------------------------------- int _rmdir( const char *dirname ) Удаляет директорию по указанному пути. dirname - Путь и имя для удаляемой директории. -------------------------------------------------------------------------------- Обе функции возвращают -1 в случае ошибки. -------------------------------------------------------------------------------- Примечание: Кстати!!! Для переименования директории можно использовать функцию rename из библиотеки stdio.h. Внимание!!! Удалить и переименовать можно только пустую директорию!!! */ // Копирование файлов /* #include <iostream> #include <windows.h> #include <io.h> #include <stdio.h> using namespace std; // Функция, выводящая на экран строку void RussianMessage(char *str){ char message[100]; //перевод строки из кодировки Windows //в кодировку MS DOS CharToOem(str,message); cout<<message; } // Функция копирования файла bool CopyFile(char *source,char *destination){ const int size=65536; FILE *src,*dest; // Открытие Файла if(!(src=fopen(source,"rb"))){ return false; } // Получение дескриптора файла int handle=_fileno(src); // выделение памяти под буффер char *data=new char[size]; if(!data){ return false; } // Открытие файла, куда будет производиться копирование if(!(dest=fopen(destination,"wb"))){ delete []data; return false; } int realsize; while (!feof(src)){ // Чтение данных из файла realsize=fread(data,sizeof(char),size,src); // Запись данных в файл fwrite(data,sizeof(char),realsize,dest); } // Закрытие файлов fclose(src); fclose(dest); return true; } void main(){ // __MAX_PATH - Константа, определяющая максимальный размер пути. // Даная константа содержится в stdlib.h char source[_MAX_PATH]; char destination[_MAX_PATH]; char answer[20]; RussianMessage("\nВведите путь и название копируемого файлу:\n"); // Получение пути к первому файлу cin.getline(source,_MAX_PATH); // Проверка Существует ли файл if(_access(source,00)==-1){ RussianMessage("\nУказан неверный путь или название файла\n"); return; } RussianMessage("\nВведите путь и название нового файла:\n"); // Получение пути к второму файлу cin.getline(destination,_MAX_PATH); // Проверка на существование файла if(_access(destination,00)==0){ RussianMessage("\nТакой Файл уже существует перезаписать его(1 - Да /2 - Нет)?\n"); cin.getline(answer,20); if(!strcmp(answer,"2")){ RussianMessage("\nОперация отменена\n"); return; } else if(strcmp(answer,"1")){ RussianMessage("\nНеправильный ввод\n"); return; } if(_access(destination,02)==-1){ RussianMessage("\nНет доступа к записи.\n"); return; } } // Копирование файла if(!CopyFile(source,destination)){ RussianMessage("\nОшибка при работе с файлом\n"); } } */ // Пример программы. Игра "Виселица". /* // Смысл игры состоит в том, что пользователь за некоторое количество попыток должен отгадать слово, в нашем случае английское. // В папку с проектом, в котором вы будете компилировать данный код, необходимо положить файл words.txt. Этот файл должен содержать // несколько английских слов, расположенных в столбик (одно под другим). #include <windows.h> #include <iostream> #include <stdio.h> #include <io.h> #include <stdlib.h> #include <time.h< #include <sys\locking.h> #include <string.h> #include <ctype.h> using namespace std; // Максимальная длина слова #define MAX_WORD_LENGTH 21 // Кол-во попыток int Tries = 10; // Кол-во угаданных слов int CountWords = 0; // Загрузка слова bool LoadWord(FILE * file, char * word) { int i = 0; char s[MAX_WORD_LENGTH] = {0}; // Кол-во слов в файле static int count = -1; if(count == -1) { // Подсчет количества слов while(!feof(file)) { fgets(s, MAX_WORD_LENGTH, file); count++; } // Слов нет? if(count == 0) return false; // Возврат файлового указателя в начало файла fseek(file, 0, 0); } // Случайное слово int n = rand() % count; // Поиск слова while(i <= n) { fgets(s, MAX_WORD_LENGTH, file); i++; } // Определяем длину слова int wordlen = strlen(s); // Минимальная длина слова 2 буквы if(wordlen <= 1) return false; // Убираем Enter (в DOS'е 2 байта 13 10) if(s[wordlen - 1] == 10) s[wordlen - 2] = 0; else if(s[wordlen - 1] == 13) s[wordlen - 1] = 0; // Копируем слово strcpy(word, s); // Получаем дескриптор файла int hFile = _fileno(file); // Вычисляем размер файла int size = _filelength(hFile); // Блокировка файла fseek(file, 0, 0); _locking(hFile, _LK_NBLCK, size); return true; } // Игра void Game(char * word) { // Перевод в большие буквы strupr(word); int len = strlen(word); // Строка-копия char * copy = new char[len + 1]; memset(copy, '*', len); copy[len] = 0; // Алфавит + пробелы char letters[52]; int i, j = 0; for(i = 0; i < 26; i++) { letters[j++] = i + 'A'; letters[j++] = ' '; } // Замыкающий ноль letters[51] = 0; // Буква char letter; char * pos; bool replace = false; do { // Очистка экрана system("cls"); cout << copy << endl << endl; cout << letters << endl << endl; cout << "Count of tries: " << Tries << endl << endl; cout << "Input any letter:\t"; cin >> letter; // Звуковой сигнал Beep(500, 200); // if(letter >= 'A' && letter <= 'Z' // || letter >= 'a' && letter <= 'z') // Буква? if(!isalpha(letter)) { cout << "It's not a letter" << endl; // Задержка на 1 секунду Sleep(1000); continue; } // Перевод буквы в большую letter = toupper(letter); // Поиск буквы в алфавите pos = strchr(letters, letter); // Такая буква уже была if(pos == 0) { cout << "This letter have been already pressed" << endl; Sleep(1000); continue; } else { // Убираем букву из алфавита pos[0] = ' '; } // Поиск буквы в слове for(i = 0; i < len; i++) { if(word[i] == letter) { copy[i] = letter; replace = true; } } if(replace == false) Tries--; else replace = false; // Условие победы if(strcmp(word, copy) == 0) { system("cls"); cout << copy << endl << endl; cout << letters << endl << endl; cout << "Count of tries: " << Tries << endl << endl; cout << "Congratulation !!!" << endl; CountWords++; break; } } while(Tries != 0); delete [] copy; } void main() { // Открываем файл на чтение в двоичном режиме FILE * f = fopen("words.txt", "rb"); // Если файл не открылся if(f == 0) { // Ошибка perror("Open"); return; } srand(time(0)); char Word[20]; // Пытаемся загрузить слово if(!LoadWord(f, Word)) { // Если неудачно cout << "Error !!!" << endl; fclose(f); return; } char answer; // Играем, пока не надоест do { Game(Word); // Если попыток не осталось, то выход if(Tries == 0) { cout << "Count of words: " << CountWords << endl; cout << "Bye-bye" << endl; break; } // Если остались cout << "Continue ??? (Y/N)\t"; cin >> answer; // Еще играем? if(answer == 'Y' || answer == 'y') if(!LoadWord(f, Word)) { cout << "Error !!!" << endl; fclose(f); return; } }while(answer == 'Y' || answer == 'y'); // получаем дескриптор int hFile = _fileno(f); // Разблокировка файла int size = _filelength(hFile); fseek(f, 0, 0); _locking(hFile, _LK_UNLCK, size); fclose(f); } */ // Cохранение объектов структуры в файл /* #include <iostream> #include <string.h> #include <stdio.h> using namespace std; // структура, хранящая // информацию о человеке struct Man{ //Имя char name[255]; //Возраст int age; }; void main() { //Создание объектов структуры Man A,B; //Запись в объект A //информации, полученной //с клавиатуры cout<<"\nEnter name:\n"; cin>>A.name; cout<<"\nEnter age:\n"; cin>>A.age; //открытие файла на запись FILE*f=fopen("Test.txt","w+"); if(!f) exit(0); //запись объекта А в файл fwrite(&A,sizeof(Man),1,f); fclose(f); //открытие файла на чтение f=fopen("Test.txt","r+"); if(!f) exit(0); //считывание содержимого файла //в объект B fread(&B,sizeof(Man),1,f); //открытие файла на запись fclose(f); //показ результата на экран cout<<"\nName - "<<B.name<<"\n\nAge - "<<B.age<<"\n\n"; } */ // Пример программы на работу с файлами /* // Здесь находятся функции переименования и удаления #include <stdio.h> // Здесь находятся функции для поиска файлов #include <io.h> #include <string.h> #include <iostream> using namespace std; // для функции AnsiToOem #include <windows.h> // Переименовать существующий файл void RenameFile(); // Удалить существующий файл void RemoveFile(); // Поиск файлов в каталоге void Dir(); void main() { // предлагаем выбрать пункт меню для выполнения cout << "Please, select preffer number...\n"; //выбор пользователя char ch; do{ // Переименовать cout << "\n1 - Rename\n"; // Удалить cout << "2 - Remove\n"; // Просмотреть некоторую папку(каталог) cout << "3 - View some folder\n"; // Выход cout << "0 - Exit\n\n"; cin >> ch; // анализируем и вызываем // соответствующую функцию switch(ch) { case '1': RenameFile(); break; case '2': RemoveFile(); break; case '3': Dir(); break; } } while(ch != '0'); // Выход из программы } // Переименовать существующий файл void RenameFile() { char oldName[50], newName[50]; // В одной переменной запомним существующее имя (oldName), cout << "Enter old name:"; cin >> oldName; // А в другой новое имя(newName) cout << "Enter new name:"; cin >> newName; // Произведем переименование и проверку результата if (rename(oldName, newName) != 0) cout << "Error!\n Couldn't rename file. Check old and new filename...\n\n"; else cout << "Ok...\n\n"; } // Удалить существующий файл void RemoveFile() { char Name[50]; // Получаем имя и путь к удаляемому файлу cout << "Enter name:"; cin >> Name; //Удаляем файл и проверяем результат if (remove(Name) != 0) cout << "Error!\n Couldn't remove file. Check filename...\n"; else cout << "Ok...\n" ; } // Поиск файлов в каталоге void Dir() { // Запросим ПУТЬ (например, папка Temp на диске C, запишется // таким вот образом: c:\temp\) char path[70]; cout << "\nEnter full path (for example, C:\\):"; cin >> path; // Запросим маску файлов char mask[15]; cout << "\nEnter mask (for example, *.* or *.txt):"; cin >> mask; // Соединив две строки, мы получим результат // т.е. что хочет найти пользователь и где strcat(path, mask); // Объявление указателя fileinfo на структуру _finddata_t // и создание динамического объекта структуры _finddata_t _finddata_t *fileinfo=new _finddata_t; // Начинаем поиск long done = _findfirst(path,fileinfo); // если done будет равняться -1, // то поиск вести бесмысленно int MayWeWork = done; // Счетчик, содержит информацию о количестве найденых файлов. int count = 0; while (MayWeWork!=-1) { count++; // перекодировали имя найденного файла // на случай, если оно кириллическое AnsiToOem(fileinfo->name,fileinfo->name); // Распечатали имя найденного файла cout << fileinfo->name << "\n\n"; // Пытаемся найти следующий файл из группы MayWeWork = _findnext(done, fileinfo); } // Вывод сообщения о количестве найденных файлов. cout << "\nInformation: was found " << count; cout << " file(s) in folder..." << path << "\n\n"; // Очистка памяти _findclose(done); delete fileinfo; } */ // Пример на работу с директориями /* #include <iostream> #include <direct.h> #include <stdio.h> using namespace std; // Переименовать существующую директорию void RenameDirectory(); // Удалить существующую директорию void RemoveDirectory(); // создать директорию void CreateDirectory(); void main() { // предлагаем выбрать пункт меню для выполнения cout << "Please, select preffer number...\n"; //выбор пользователя char ch; do{ // Переименовать cout << "\n1 - Rename\n"; // Удалить cout << "2 - Remove\n"; // Создать cout << "3 - Create\n"; // Выход cout << "0 - Exit\n\n"; cin >> ch; // анализируем и вызываем // соответствующую функцию switch(ch) { case '1': RenameDirectory(); break; case '2': RemoveDirectory(); break; case '3': CreateDirectory(); break; } } while(ch != '0'); // Выход из программы } // Переименовать существующую директорию void RenameDirectory() { char oldName[50], newName[50]; // В одной переменной запомним существующее имя (oldName), cout << "Enter old name:"; cin >> oldName; // А в другой новое имя(newName) cout << "Enter new name:"; cin >> newName; // Произведем переименование и проверку результата if (rename(oldName, newName) != 0) cout << "Error!\n Couldn't rename directory.\n\n"; else cout << "Ok...\n\n"; } // Удалить существующую директорию void RemoveDirectory() { char Name[50]; // Получаем имя и путь к удаляемой директории cout << "Enter name:"; cin >> Name; //Удаляем директорию и проверяем результат if (_rmdir(Name) == -1) cout << "Error!\n Couldn't remove directory.\n"; else cout << "Ok...\n" ; } // Создать директорию void CreateDirectory() { char Name[50]; // Получаем имя и путь к создаваемой директории cout << "Enter name:"; cin >> Name; //Создаем директорию и проверяем результат if (_mkdir(Name) == -1) cout << "Error!\n Couldn't create directory.\n"; else cout << "Ok...\n" ; } */ // Показ содержимого директории /* #include <iostream> #include <windows.h> #include <io.h> #include <stdio.h> using namespace std; const int size=255; // Функция, которая убирает лишние слеши и пробелы справа void RemoveRSpacesAndRSlashes(char *str){ int index=strlen(str)-1; while(str[index]=='\\'||str[index]==' '){ index--; } strncpy(str,str,index); str[index+1]='\0'; } // Функция для показа текущей директории void ShowCurrentDir(char path[],char temp[]){ CharToOem(path,temp); printf("%s>",temp); } // Функция перевода из кодировки // Windows в кодировку DOS // Для корректного отображения // кирилицы void RussianMessage(char path[]){ CharToOem(path,path); } // Показ на экран содержимого папки bool ShowDir(char path[]){ // Показ содержимого текущей директории _finddata_t find; char pathfind[MAX_PATH]; strcpy(pathfind,path); strcat(pathfind,"\\*.*"); char info[MAX_PATH]; // Начало Поиска int result=_findfirst(pathfind,&find); // Очистка экрана system("cls"); int flag=result; if (flag==-1) { strcpy(info,"Такой Директории Нет"); RussianMessage(info); printf("%s\n",info); return false; } while(flag!=-1){ if(strcmp(find.name,".")&&strcmp(find.name,"..")){ // Проверяем Директория или Нет find.attrib&_A_SUBDIR?strcpy(info," Каталог "):strcpy(info," Файл "); RussianMessage(info); RussianMessage(find.name); printf("%30s %10s\n",find.name,info); } // Продолжаем Поиск flag=_findnext(result,&find); } ShowCurrentDir(path,info); // Очищаем ресурсы, выделенные под поиск _findclose(result); return true; } void main(){ // В данной переменной будет храниться путь к Директории char path[MAX_PATH]; // В данной переменной будет команда, введенная пользователем char action[size]; // Временная переменная char temp[MAX_PATH]; // Получаем Путь к текущей Директории GetCurrentDirectory(sizeof(path),path); bool flag=true; // Показ содержимого текущей директории ShowDir(path); do{ // Ввод команды пользователя cin.getline(action,size); // Убираем пробелы и слэши справа RemoveRSpacesAndRSlashes(action); // Переход в корневой каталог if(!strcmpi(action,"root")){ path[2]='\0'; ShowDir(path); } // Проверка на желание пользователя выйти else if(!strcmpi(action,"exit")){ flag=false; } // Проверка на команду cd else if(!strnicmp(action,"cd",2)){ // Показ содержимого текущей директории if((!strcmpi(action,"cd"))){ // Показ Директории ShowDir(path); } // Команда cd была дана с параметрами else if(!strnicmp(action,"cd ",3)){ // Находим индекс параметра int index=strspn(action+2," "); if(index){ // Проверка на полный путь к Директории if(strchr(action+index+2,':')){ // Попытка отобразить содержимое Директории if(ShowDir(action+index+2)){ strcpy(path,action+index+2); } else{ // Произошла Ошибка ShowCurrentDir(path,temp); } } // Поднимаемся в родительский каталог else if(!strcmp(action+index+2,"..")){ char *result=strrchr(path,'\\'); if(result){ int delta=result-path; strncpy(temp,path,delta); temp[delta]='\0'; } else{ strcpy(temp,path); } if(ShowDir(temp)){ strcpy(path,temp); } else{ // Произошла Ошибка ShowCurrentDir(path,temp); } } // Показ Директории else if(!strcmp(action+index+2,".")){ ShowDir(path); } else if(!strcmp(action+index+2,"/")){ ShowDir(path); } else{ // Был Дан неполный путь strcpy(temp,path); strcat(temp,"\\"); strcat(temp,action+index+2); // Попытка отобразить содержимое Директории if(ShowDir(temp)){ strcpy(path,temp); } else{ // Произошла Ошибка ShowCurrentDir(path,temp); } } } else{ // Показ Директории ShowDir(path); } } else{ // Показ Директории ShowDir(path); } } else{ // Показ Директории ShowDir(path); } }while(flag); } */ // Пример программы, которая создает HTML-документ и окрашивает его фон цветом переданным из командной строки в качестве параметра. (cmd: www.exe ff0000) /* #include <iostream> #include <string.h> #include <stdio.h> using namespace std; void main(int argc, char * argv[]) { //Задаем по умолчанию черный цвет char str[7]="000000"; //формируем начало HTML - документа char filehtml[256]="<html><head><title>New file!!!</title></head><body bgcolor = \'#"; //Открываем файл на запись с созданием FILE*f=fopen("C:\\1.html","w+"); //Если не получилось - останавливаемся if(!f) exit(0); //Если параметр цвета передан - используем его if(argc==2){ strcpy(str,argv[1]); } //Присоединяем цвет к документу strcat(filehtml,str); //Присоединяем окончание к документу strcat(filehtml,"\'></body></html>"); //Сохраняем в файл fputs(filehtml,f); //Закрываем Файл fclose(f); cout<<"\nOK.....\n"; } */ // Пример, который, используя средства языка С++, реализует возможность просмотра файла в шестнадцатиричном виде /* #include <iostream> #include <fstream> #include <iomanip> #include <string.h> #include <conio.h> using namespace std; // Максимальная длина пути к файлу #define MAX_PATH 260 // Количество столбцов на экране #define NUM_COLS 18 // Количество строк на экране #define NUM_ROWS 24 void main() { char path[MAX_PATH]; // Запрашиваем путь к файлу cout << "Input path to file: "; cin.getline(path, MAX_PATH); int counter = 0, i = 0, j = 0; char text[NUM_COLS]; // Открытие файла в двоичном режиме ifstream input(path, ios::in | ios::binary); if (!input) { cout << "Cannot open file for display!" << endl; return; } // Режим отображения в верхнем регистре для шестнадцатиричного вывода cout.setf(ios::uppercase); // Пока не конец файла, читаем из него данные // и производим форматированный вывод на экран while (!input.eof()) { // Посимвольное чтение for (i = 0; (i < NUM_COLS && !input.eof()); i++) input.get(text[i]); if (i < NUM_COLS) i--; for (j = 0; j < i; j++) if((unsigned)text[j] < 0x10) // Количество символов для отображения числа меньше двух? cout << setw(2) << 0 << hex << (unsigned) text[j]; else cout << setw(3) << hex << (unsigned) text[j]; // Выравнивание для незавершенной строки for (; j < NUM_COLS; j++) cout << " "; cout << "\t"; for (j = 0; j < i; j++) // Символ не является управляющим? if(text[j] > 31 && text[j] <= 255) cout << text[j]; else cout << "."; cout << "\n"; // Если экран уже заполнен, производим остановку if (++counter == NUM_ROWS) { counter = 0; cout << "Press any key to continue..." << flush; // Ожидаем нажатия любой клавиши getch(); cout << "\n"; } } // Закрываем файл input.close(); } */ // Практический пример. Ввод/вывод массива в/из файл(-а). /* #include <windows.h> #include <fstream> #include <iostream> #include <iomanip> using namespace std; void main() { char Answer; const int MessageCount = 8; int i, j; // Подсказки enum {CHOICE = 3, INPUT_FILENAME, INPUT_DIMENSIONS, INPUT_ELEMENTS, FILE_ERROR}; // Сообщения char Msg[MessageCount][50] = { "1. Вывести данные из текстового файла\n", "2. Записать данные в текстовый файл\n", "3. Выход из программы\n", "\nВаш выбор: ", "Введите имя обрабатываемого файла: ", "Введите размерности матрицы:\n", "Введите элементы матрицы:\n", "Невозможно открыть файл\n" }; // Русификация сообщений и вывод меню на экран for(i = 0; i < MessageCount; i++) AnsiToOem(Msg[i], Msg[i]); do { for(int i = 0; i < 4; i++) cout << Msg[i]; cin >> Answer; } while (Answer < '1' || Answer > '3'); if(Answer == '3') return; // Переменная для имени файла char FileName[80]; // Размерности матрицы int M, N; int num; cout << "\n" << Msg[INPUT_FILENAME]; cin >> FileName; // Если выбран первый пункт меню, // то выводим данные из текстового файла на экран if(Answer == '1') { // Если файл с указанным именем не существует, // выводим сообщение об ошибке ifstream inF(FileName, ios::in | ios::_Nocreate); if (!inF) { cout << endl << Msg[FILE_ERROR]; return; } // Считываем размерность массива inF >> M; inF >> N; // Считываем элементы массива из файла и выводим их сразу на экран for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { inF >> num; cout << setw(6) << num; } cout << endl; } inF.close(); } // Если выбран второй пункт меню, то запрашиваем // у пользователя данные и выводим их в текстовый файл else { // Открываем файл для записи. // Если файл с указанным именем не существует, // то программа создает его ofstream outF(FileName, ios::out); if (!outF) { cout << "\n" << Msg[FILE_ERROR]; return; } // Запрашиваем размерность матрицы и записываем данные в файл cout << Msg[INPUT_DIMENSIONS]; cout << "M: "; cin >> M; cout << "N: "; cin >> N; outF << M << ' ' << N << "\n"; cout << Msg[INPUT_ELEMENTS]; // Запрашиваем элементы массива и записываем их в файл for (i = 0; i < M; i++) { for(j = 0; j < N; j++) { cout << "A[" << i << "][" << j << "] = "; cin >> num; outF << num << " "; } outF << "\n"; } outF.close(); } } */ // Практический пример записи объекта класса в файл. /* #include <iostream> #include <fstream> #include <string.h> #include <windows.h> using namespace std; void RussianMessage(char *message){ char rmessage[256]; AnsiToOem(message,rmessage); cout<<rmessage; } int RussianMenu(){ RussianMessage("\nВведите 1 для добавления новой структуры в файл\n"); RussianMessage("Введите 2 для показа всех структур из файла\n"); RussianMessage("Введите 3 для выхода\n"); int choice; cin>>choice; return choice; } class Man{ // переменная для возраста int age; // переменная для имени char *name; // переменная для фамилии char *surname; public: // конструктор с параметрами Man(char *n,char *s,int a); // конструктор Man(); // деструктор ~Man(); public: // функция ввода данных void Put(); // функция показа данных void Show(); // функция сохранения в файл void SaveToFile(); // функция показа содержимого файла static void ShowFromFile(); }; // конструктор Man::Man(){ name=0; surname=0; age=0; } // конструктор с параметрами Man::Man(char *n,char *s,int a){ name=new char[strlen(n)+1]; if(!name){ RussianMessage("Ошибка при выделении памяти !!!"); exit(1); } strcpy(name,n); surname=new char[strlen(s)+1]; if(!surname){ RussianMessage("Ошибка при выделении памяти !!!"); exit(1); } strcpy(surname,s); age=a; } // деструктор Man::~Man(){ delete[] name; delete[] surname; } // функция ввода данных void Man::Put(){ char temp[1024]; RussianMessage("\nВведите имя:\n"); cin>>temp; if(name) delete[] name; name=new char[strlen(temp)+1]; if(!name){ RussianMessage("Ошибка при выделении памяти !!!"); exit(1); } strcpy(name,temp); RussianMessage("\nВведите фамилию:\n"); cin>>temp; if(surname) delete[] surname; surname=new char[strlen(temp)+1]; if(!surname){ RussianMessage("Ошибка при выделении памяти !!!"); exit(1); } strcpy(surname,temp); RussianMessage("\nВведите возраст\n"); cin>>age; } // функция показа данных void Man::Show(){ RussianMessage("\nИмя:\n"); cout<<name; RussianMessage("\nФамилия:\n"); cout<<surname; RussianMessage("\nВозраст:\n"); cout<<age<<"\n"; } // функция сохранения в файл void Man::SaveToFile(){ int size; fstream f("men.txt",ios::out|ios::binary|ios::app); if(!f){ RussianMessage("Файл не открылся для записи !!!"); exit(1); } // Записываем возраст f.write((char*)&age,sizeof(age)); size=strlen(name); // Записываем количество символов в имени f.write((char*)&size,sizeof(int)); // Записываем имя f.write((char*)name,size*sizeof(char)); size=strlen(surname); // Записываем количество символов в фамилии f.write((char*)&size,sizeof(int)); // Записываем фамилию f.write((char*)surname,size*sizeof(char)); f.close(); } // функция показа содержимого файла void Man::ShowFromFile(){ fstream f("men.txt",ios::in|ios::binary); if(!f){ RussianMessage("Файл не открылся для чтения !!!"); exit(1); } char *n,*s; int a; int temp; // В цикле зачитываем содержимое файла while (f.read((char*)&a,sizeof(int))){ RussianMessage("\nИмя:\n"); f.read((char*)&temp,sizeof(int)); n=new char[temp+1]; if(!n){ RussianMessage("Ошибка при выделении памяти !!!"); exit(1); } f.read((char*)n,temp*sizeof(char)); n[temp]='\0'; cout<<n; RussianMessage("\nФамилия:\n"); f.read((char*)&temp,sizeof(int)); s=new char[temp+1]; if(!s){ RussianMessage("Ошибка при выделении памяти !!!"); exit(1); } f.read((char*)s,temp*sizeof(char)); s[temp]='\0'; cout<<s; RussianMessage("\nВозраст:\n"); cout<<a<<"\n"; delete []n; delete []s; } } void main(){ Man *a; // Основной цикл программы do{ switch(RussianMenu()){ case 1: // Добавление записи a=new Man; a->Put(); a->SaveToFile(); delete a; break; case 2: // Показ всех записей Man::ShowFromFile(); break; case 3:// Прощание с пользователем RussianMessage("До Свидания\n"); return; default: // Неправильный ввод RussianMessage("Неверный Ввод\n"); } }while(1); } */
5ccf7c6995cdf999cd99f7006d23839e1c142fd5
29868bf4aa31c1ca8b8c86e5b5b07cc3509caf64
/Perrin/Perrin/funciones.hpp
6ebc159bf9277bff3b4022d1405383bee01ee485
[]
no_license
Laura-Mora/PC-2016-03
a137746a8c1939235a5176a0ecc2d8234ee87348
0cf0826bdb8a3be89c9da0e70a6726388c6ba0c6
refs/heads/master
2023-07-20T15:16:07.676365
2019-12-30T01:52:28
2019-12-30T01:52:28
222,524,088
0
0
null
null
null
null
UTF-8
C++
false
false
372
hpp
funciones.hpp
// // funciones.hpp // Perrin // // Created by Laura Juliana Mora on 3/08/16. // Copyright © 2016 Laura Juliana Mora. All rights reserved. // #ifndef funciones_hpp #define funciones_hpp void datos(int *,int); void imprimir(int *,int); int primos(int *,int ); int menu(); void imprimir2(int **p,int n); void primos2(int *p,int n,int cant); #endif /* funciones_hpp */
203987f881e1909062341f5e6514dc9eeaa7ad9f
26fb880c20da5949f6c202ffd3e16269a904f7ef
/src/kernel_bi_clustering.cpp
6157c901ca6754fda697d16a1bb31e165722f632
[ "MIT" ]
permissive
anonymousclustering/biclustering
1d08953b89faaab93109a4ce41d7216e4c22319e
0ca08d9b2cd1a781bb0e87a0285d4a1beb971099
refs/heads/main
2023-02-28T06:48:09.023526
2021-02-05T00:23:55
2021-02-05T00:23:55
336,115,715
0
0
null
null
null
null
UTF-8
C++
false
false
2,954
cpp
kernel_bi_clustering.cpp
#include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] #include <omp.h> // [[Rcpp::plugins(openmp)]] #include "InitializationMethod.h" #include "RandomInitialization.h" #include "KppInitialization.h" #include "KernelFactory.h" #include "RBFFactory.h" #include "EnergyFactory.h" #include "BiClustering.h" #include "LloydBiClustering.h" #include "HartiganBiClustering.h" //' Weighted version of kernel k-means algorithm to find local solutions to the optimization problem. //' //' @param X The data points matrix. //' @param w A vector of weights associated to data points. //' @param k The number of clusters. //' @param iterations The number of iterations. //' @param restarts The number of re-starts. //' @param init_method The initialization method: "random" or "kpp". //' @param method_name The optimization method: "lloyd" or "hardigan". //' @export // [[Rcpp::export]] Rcpp::List kernel_biclustering( const arma::mat X, const arma::uword k = 3, const arma::uword iterations = 10, const arma::uword restarts = 1, const std::string init_method = "random", const std::string method_name = "hartigan", const std::string kernel_name = "rbf") { kkg::InitializationMethod *init; if (init_method == "random") init = new kkg::RandomInitialization(); else if (init_method == "kpp") init = new kkg::KppInitialization(); else throw invalid_argument("No such initialization method: Use 'random' or 'kpp'" ); kbc::KernelFactory *factory; if (kernel_name == "rbf") factory = new kbc::RBFFactory(); else if (kernel_name == "energy") factory = new kbc::EnergyFactory(); else throw invalid_argument("No such kernel method: Use 'rbf' or 'energy'" ); kbc::BiClusteringMethod *biclustering; if (method_name == "hartigan") biclustering = new kbc::HartiganBiClustering(); else if (method_name == "lloyd") biclustering = new kbc::LloydBiClustering(); else throw invalid_argument("No such method: Use 'hartigan' or 'lloyd'" ); // auto started = std::chrono::high_resolution_clock::now(); // kbc::BiClustering result = biclustering -> doClustering(sigma_r, sigma_c, X, k, iterations, restarts, *init, *factory); kbc::BiClustering result = biclustering -> doClustering(X, k, iterations, restarts, *init, *factory); // auto done = std::chrono::high_resolution_clock::now(); // cout << "Execution time: " << std::chrono::duration_cast<std::chrono::milliseconds>(done-started).count() << " ms" << endl; // cout << "Row labels: " << ss(result.row_labels) << endl; // cout << "Col labels: " << ss(result.col_labels) << endl; return Rcpp::List::create( Rcpp::_["row_labels"] = result.row_labels.t()+1, Rcpp::_["col_labels"] = result.col_labels.t()+1, Rcpp::_["k"] = k, Rcpp::_["iterations"] = iterations, Rcpp::_["restarts"] = restarts, Rcpp::_["cost"] = result.row_cost // Rcpp::_["col_cost"] = result.col_cost ); }
b9e1cf2597e36c0a40fbff877355ea257f5c06e8
11c9c278b5758dc2e5ef42c06bf69a362fb1319d
/functions/return_functions.cpp
8a3e4f2bf6ef8aba158262542c833664bc1cdb0a
[]
no_license
cjdarcy/cppSandbox
4048f72636819f5e7c4b586dc83833e4f7a3b8c7
c0ff423d89268074ca2dea00e6be017f479df151
refs/heads/master
2020-03-14T03:42:09.794701
2018-11-17T13:42:41
2018-11-17T13:42:41
131,425,656
0
0
null
null
null
null
UTF-8
C++
false
false
294
cpp
return_functions.cpp
#include <iostream> #include <cmath> using namespace std; double area(double radius) { return acos(-1.0) * radius * radius; } double absoluteValue(double x) { if (x < 0) { return -x; } else if (x > 0) { return x; } else if (x == 0) { return 0; } }
e4a94f4f808192f26e610d0b11054be9a121eb46
c0cb4ffb337dc5e392d3bbafeb418f7580c05000
/500/507.cpp
c9058edb8ca4d73f136b6588f12cdebe9f71091c
[]
no_license
ghj0504520/UVA
b3a7d6b6ba308916681fd8a6e25932a55f7455b3
8e49a1424538e907f4bdbe5543cc6966d4ea5a4e
refs/heads/master
2023-05-01T07:49:18.162394
2023-04-24T07:48:11
2023-04-24T07:48:11
38,348,555
1
0
null
null
null
null
UTF-8
C++
false
false
665
cpp
507.cpp
#include <iostream> using namespace std; int main() { int b, r, s; cin>>b; for(int t=1 ; t<=b ; t++) { cin>>r; int curSum=0,curI=-1,curJ=-1; int maxSum=0,maxI=-1,maxJ=-1; for(int it=0 ; it<r-1 ; it++) { cin>>s; curJ=it+1; if(curI==-1)curI=curJ; curSum+=s; if((curSum>maxSum) || (curSum==maxSum&& curJ-curI>maxJ-maxI)) { maxSum = curSum; maxI=curI; maxJ=curJ; } if(curSum<0) { curSum = 0; curI = -1; } } if (maxSum>0) cout<<"The nicest part of route "<<t<<" is between stops "<<maxI<<" and "<<maxJ+1<<"\n"; else cout<<"Route "<<t<<" has no nice parts\n"; } return 0; }
acb25fae1d75117e8b7a94d5d2ac0fbbf06430f7
4eb58b82b857edde83e8ed99dc10f59e8ea2c71f
/01185/01185.cpp
36679fa798e944faca7293468aa6427f2d754ae7
[]
no_license
RezaMokaram/Solutions-to-UVAonlinejudge-problems
18be6d1d7ca302c233e077546d7ad4bffa9f1448
e4117ed247ff3f707cd71e84df662835affb1077
refs/heads/master
2023-06-11T06:47:05.602555
2023-06-03T01:59:10
2023-06-03T01:59:10
248,146,437
0
0
null
null
null
null
UTF-8
C++
false
false
824
cpp
01185.cpp
//#include <bits/stdc++.h> #include <iostream> #include <fstream> #include <string> #include <cstdio> #include <cstring> #include <cmath> #include <stdio.h> #include <vector> #include <iomanip> #include <queue> #include <algorithm> #include <set> #include <stack> #include <functional> #include <map> #include <set> using namespace std; // typedef long long int ll; typedef long long unsigned int llu; typedef vector<pair<llu, ll>> vii; typedef pair<llu, ll> pii; typedef vector<int> vi; const ll MAX = 2 * 100000 + 11; const llu llm = 9999999999 + 1; typedef pair<ll, pair<int, int>> edg; // const int mx = 10000002; double arr[mx]; int main() { arr[0] = arr[1] = 1; for (int i = 2; i < mx; i++) arr[i] = arr[i-1]+log10(i); int tc; cin >> tc; while (tc--) { int n; cin >> n; cout << (int)arr[n] << endl; } }
129d2ddc5984f803fe92ac6036a90360f6100d53
be5f4d79910e4a93201664270916dcea51d3b9ee
/rovers/fastdownward/src/search/merge_and_shrink/merge_selector_score_based_filtering.cc
14af30cd5bea0faa8ea447f37acdfccc79e85907
[ "MIT", "GPL-1.0-or-later", "GPL-3.0-or-later" ]
permissive
mehrdadzakershahrak/Online-Explanation-Generation
17c3ab727c2a4a60381402ff44e95c0d5fd0e283
e41ad9b5a390abdaf271562a56105c191e33b74d
refs/heads/master
2022-12-09T15:49:45.709080
2019-12-04T10:23:23
2019-12-04T10:23:23
184,834,004
0
0
MIT
2022-12-08T17:42:50
2019-05-04T00:04:59
Python
UTF-8
C++
false
false
4,273
cc
merge_selector_score_based_filtering.cc
#include "merge_selector_score_based_filtering.h" #include "factored_transition_system.h" #include "merge_scoring_function.h" #include "../options/option_parser.h" #include "../options/options.h" #include "../options/plugin.h" #include <cassert> using namespace std; namespace merge_and_shrink { MergeSelectorScoreBasedFiltering::MergeSelectorScoreBasedFiltering( const options::Options &options) : merge_scoring_functions( options.get_list<shared_ptr<MergeScoringFunction>>( "scoring_functions")) { } MergeSelectorScoreBasedFiltering::MergeSelectorScoreBasedFiltering( vector<shared_ptr<MergeScoringFunction>> scoring_functions) : merge_scoring_functions(move(scoring_functions)) { } vector<pair<int, int>> MergeSelectorScoreBasedFiltering::get_remaining_candidates( const vector<pair<int, int>> &merge_candidates, const vector<double> &scores) const { assert(merge_candidates.size() == scores.size()); double best_score = INF; for (double score : scores) { if (score < best_score) { best_score = score; } } vector<pair<int, int>> result; for (size_t i = 0; i < scores.size(); ++i) { if (scores[i] == best_score) { result.push_back(merge_candidates[i]); } } return result; } pair<int, int> MergeSelectorScoreBasedFiltering::select_merge( const FactoredTransitionSystem &fts, const vector<int> &indices_subset) const { vector<pair<int, int>> merge_candidates = compute_merge_candidates(fts, indices_subset); for (const shared_ptr<MergeScoringFunction> &scoring_function : merge_scoring_functions) { vector<double> scores = scoring_function->compute_scores( fts, merge_candidates); merge_candidates = get_remaining_candidates(merge_candidates, scores); if (merge_candidates.size() == 1) { break; } } if (merge_candidates.size() > 1) { cerr << "More than one merge candidate remained after computing all " "scores! Did you forget to include a uniquely tie-breaking " "scoring function, e.g. total_order or single_random?" << endl; utils::exit_with(utils::ExitCode::CRITICAL_ERROR); } return merge_candidates.front(); } void MergeSelectorScoreBasedFiltering::initialize(const TaskProxy &task_proxy) { for (shared_ptr<MergeScoringFunction> &scoring_function : merge_scoring_functions) { scoring_function->initialize(task_proxy); } } string MergeSelectorScoreBasedFiltering::name() const { return "score based filtering"; } void MergeSelectorScoreBasedFiltering::dump_specific_options() const { for (const shared_ptr<MergeScoringFunction> &scoring_function : merge_scoring_functions) { scoring_function->dump_options(); } } bool MergeSelectorScoreBasedFiltering::requires_init_distances() const { for (const shared_ptr<MergeScoringFunction> &scoring_function : merge_scoring_functions) { if (scoring_function->requires_init_distances()) { return true; } } return false; } bool MergeSelectorScoreBasedFiltering::requires_goal_distances() const { for (const shared_ptr<MergeScoringFunction> &scoring_function : merge_scoring_functions) { if (scoring_function->requires_goal_distances()) { return true; } } return false; } static shared_ptr<MergeSelector>_parse(options::OptionParser &parser) { parser.document_synopsis( "Score based filtering merge selector", "This merge selector has a list of scoring functions, which are used " "iteratively to compute scores for merge candidates, keeping the best " "ones (with minimal scores) until only one is left."); parser.add_list_option<shared_ptr<MergeScoringFunction>>( "scoring_functions", "The list of scoring functions used to compute scores for candidates."); options::Options opts = parser.parse(); if (parser.dry_run()) return nullptr; else return make_shared<MergeSelectorScoreBasedFiltering>(opts); } static options::PluginShared<MergeSelector> _plugin("score_based_filtering", _parse); }
0173dfee54ab0b0a26431a4455fdd1b512f904c8
3fc3a211e934adbad2d7326fd4aa64c220eb596e
/ForFudan/f2.cpp
97d0f0ce2bf26a752f9550d9eb0430ded05b7bbd
[]
no_license
ejacky/c-plus-plus-primer
86abd40dc7705092ee8b5d750eded0a9cb126188
6ee0bbaa0bc515eb637d32d441bb14a8f8b09630
refs/heads/master
2021-01-19T08:35:04.632777
2017-11-11T15:13:54
2017-11-11T15:13:54
100,654,175
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
752
cpp
f2.cpp
#include <iostream> using namespace std; void e1() { double *p; p = new double[3]; for (int i = 0; i < 3; i++) cin >> *(p+i); for (int i = 0; i < 3; i++) cout << *(p+i) << " "; delete p; } template <class T> void max(T m1, T m2, T m3) { T temp; temp = m1; if (m1 > m2) { temp = m1; m1 = m2; m2 = temp; } if (m2 > m3) { temp = m2; m2 = m3; m3 = temp; } cout << m1 << "," << m2 << "," << m3; } void e2() { max("abf", "abz", "aba"); cout << endl; max(18,9 ,24); cout << endl; max(2.01, 2.28, 2.23); cout << endl; } #include "f2_e3.h" void e3() { Point a; Point b(7.8, 9.8), c(34.5, 67.8); a = c; // what ? cout << "Á½µã¾àÀ룺" << a.Distance(b) << endl; } int main() { //e1(); //e2(); e3(); }
e3568a415f219f65a2d5d11a2ed70c4926242863
92c4eb7b4e66e82fda6684d7c98a6a66203d930a
/src/DS/containers/rb_tree.h
0dbbc8e827fc9efef0f0bebebc90082877b2303f
[]
no_license
grouptheory/SEAN
5ea2ab3606898d842b36d5c4941a5685cda529d9
6aa7d7a81a6f71a5f2a4f52f15d8e50b863f05b4
refs/heads/master
2020-03-16T23:15:51.392537
2018-05-11T17:49:18
2018-05-11T17:49:18
133,071,079
0
0
null
null
null
null
UTF-8
C++
false
false
4,885
h
rb_tree.h
// -*- C++ -*- // +++++++++++++++ // S E A N --- Signalling Entity for ATM Networks --- // +++++++++++++++ // Version: 1.0.1 // // Copyright (c) 1998 // Naval Research Laboratory (NRL/CCS) // and the // Defense Advanced Research Projects Agency (DARPA) // // All Rights Reserved. // // Permission to use, copy, and modify this software and its // documentation is hereby granted, provided that both the copyright notice and // this permission notice appear in all copies of the software, derivative // works or modified versions, and any portions thereof, and that both notices // appear in supporting documentation. // // NRL AND DARPA ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION AND // DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM // THE USE OF THIS SOFTWARE. // // NRL and DARPA request users of this software to return modifications, // improvements or extensions that they make to: // // sean-dev@cmf.nrl.navy.mil // -or- // Naval Research Laboratory, Code 5590 // Center for Computation Science // Washington, D.C. 20375 // // and grant NRL and DARPA the rights to redistribute these changes in // future upgrades. // // -*- C++ -*- #ifndef __RB_TREE_H__ #define __RB_TREE_H__ #ifndef LINT static char const _rb_tree_h_rcsid_[] = "$Id: rb_tree.h,v 1.29 1999/01/26 22:22:50 mountcas Exp $"; #endif #include <assert.h> class rb_node; extern rb_node * rb_null; class rb_node { public: rb_node(void) : _data(0), _parent( rb_null ), _left( rb_null ), _right( rb_null ), _leftmost( rb_null ), _rightmost( rb_null ), _red(false), _size(1) { if (rb_null==0) { _parent = _left = _right = _leftmost = _rightmost = this; } } rb_node(void * data, bool red = true, rb_node * parent = rb_null, rb_node * left = rb_null, rb_node * right = rb_null) : _data(data), _left( left ), _right( right ), _leftmost( rb_null ), _rightmost( rb_null ), _red(red), _size(1), _parent( parent ) { if (rb_null == 0) { _parent = _left = _right = _leftmost = _rightmost = this; _size = 0; } else { assert( _parent != this ); } } ~rb_node( ) { } rb_node * parent(void) { return _parent; } rb_node * left(void) { return _left; } rb_node * right(void) { return _right; } rb_node * leftmost(void) { return _leftmost; } rb_node * rightmost(void) { return _rightmost; } bool red(void) const { return _red; } void * data(void) const { return _data; } int size(void) { return _size; } void parent(rb_node * n) { assert( n != this ); _parent = n; } void left(rb_node * n) { _left = n; } void right(rb_node * n) { _right = n; } void red(bool r) { _red = r; } void size(int s) { _size = s; } rb_node & operator = (const rb_node & rhs) { _data = rhs._data; // _left = rhs._left; // _right = rhs._right; // _parent = rhs._parent; // _red = rhs._red; } private: void * _data; rb_node * _left; rb_node * _right; rb_node * _parent; rb_node * _leftmost; rb_node * _rightmost; int _size; bool _red; }; typedef rb_node * rb_item; #ifndef forall_items #define forall_items(x, y) \ for ( (x) = (y).first(); (x); (x) = (y).next(x) ) #endif template <class T> class rb_tree { public: rb_tree(void); rb_tree(const rb_tree & rhs); virtual ~rb_tree(); rb_tree & operator = (const rb_tree & rhs); int length(void) const; bool empty(void) const; T & inf(rb_item it) const; const T & operator [] (rb_item it) const; rb_item lookup(const T item) const; rb_item search(const T item) const; rb_item first(void) const; rb_item last(void) const; rb_item next(rb_item it) const; rb_item succ(rb_item it) const; rb_item prev(rb_item it) const; rb_item pred(rb_item it) const; rb_item insert(T item); T del_item(rb_item ri); T del(const T & item); void clear(void); void set_compare( int (*_func)(const T &, const T &) ); int rank( const T & ) const; int rank( rb_item ri ) const; private: rb_item _first(void) const; rb_item _last(void) const; rb_item _next(rb_item it) const; rb_item _prev(rb_item it) const; rb_item _lookup(const T item) const; void left_rotate(rb_item it); void right_rotate(rb_item it); void delete_fixup(rb_item it); void tree_insert(rb_item it); // Locates the min of the tree rooted at it rb_item tree_min(rb_item it) const; // Locates the max of the tree rooted at it rb_item tree_max(rb_item it) const; // --------- data --------- int (*_cmp_ptr)(const T &, const T &); rb_item _root; int _length; }; #endif
4284554de44a2aecd822f5700fb54ffaebf7d722
0028c740dab82658b67c0ee21d474b455c2104c6
/ants/lib/antsRegistration4DFloat.h
88fed6e6cd7b942e74c7aa5c75defa010a6be965
[ "Apache-2.0" ]
permissive
ncullen93/ANTsPy
3ecdf7af1a3c67c6fa1ed171c609d25c1104fccd
a4c990dcd5b7445a45ce7b366ee018c7350e7d9f
refs/heads/master
2021-01-20T21:35:11.910867
2017-08-29T14:30:48
2017-08-29T14:30:48
101,770,979
3
1
null
2017-08-29T14:33:06
2017-08-29T14:33:06
null
UTF-8
C++
false
false
300
h
antsRegistration4DFloat.h
#include "antsRegistrationTemplateHeader.h" #include "antsCommandLineParser.h" #include "antsCommandLineOption.h" namespace ants { //Instantiate the 4DFloat version int antsRegistration4DFloat(ParserType::Pointer & parser) { return DoRegistration<float, 4>( parser ); } } //end namespace ants