blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 986
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 145
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 122
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6e748a4bac879b8556c6e0a38c0850fda02b680d | 230883cb8e249a526c94c860f30aed3f023561b5 | /sse_sort.cpp | 13f4da06aa211608fc8d22c225e270d72ebacfe4 | [] | no_license | starkantoden/Hybrid_Sort | 787d3893b6e90209c597c81398073059feb23732 | 29721e695a50212754559876b9a0e1588167e68b | refs/heads/master | 2021-01-01T18:20:07.835468 | 2017-07-30T06:25:09 | 2017-07-30T06:25:09 | 98,308,119 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,396 | cpp | #include "sse_sort.h"
// data length must be 32, this function will produce 8 sorted sequence of
// length 4
void simdOddEvenSort(__m128 *rData)
{ // odd even sort lanes, then transpose them
const int pairSize = rArrayLen >> 1;
__m128 temp[pairSize];
for (int i = 0; i < pairSize; ++i) temp[i] = rData[2 * i];
for (int i = 0; i < rArrayLen; i += 2)
rData[i] = _mm_min_ps(rData[i], rData[i + 1]);
for (int i = 1; i < rArrayLen; i += 2)
rData[i] = _mm_max_ps(rData[i], temp[i >> 1]);
for (int i = 0; i < pairSize; i += 2)
{
temp[i] = rData[i * 2];
temp[i + 1] = rData[i * 2 + 1];
}
for (int i = 0; i < rArrayLen; i += 4)
{
rData[i] = _mm_min_ps(rData[i], rData[i + 2]);
rData[i + 1] = _mm_min_ps(rData[i + 1], rData[i + 3]);
}
for (int i = 2; i < rArrayLen; i += 4)
{
rData[i] = _mm_max_ps(rData[i], temp[(i >> 1) - 1]);
rData[i + 1] = _mm_max_ps(rData[i + 1], temp[i >> 1]);
}
// TODO:portability?
for (int i = 0; i < rArrayLen >> 2; ++i) temp[i] = rData[i * 4 + 1];
for (int i = 1; i < rArrayLen; i += 4)
rData[i] = _mm_min_ps(rData[i], rData[i + 1]);
for (int i = 2; i < rArrayLen; i += 4)
rData[i] = _mm_max_ps(rData[i], temp[i >> 2]);
// temp,0,1,2,3
for (int i = 0; i < rArrayLen; i += 2)
temp[i >> 1] = _mm_shuffle_ps(rData[i], rData[i + 1], 0x44);
//rdata,1,3,5,7
for (int i = 1; i < rArrayLen; i += 2)
rData[i] = _mm_shuffle_ps(rData[i], rData[i - 1], 0xee);
//rdata,0,4
for (int i = 0; i < pairSize; i += 2)
rData[i * 2] = _mm_shuffle_ps(temp[i], temp[i + 1], 0x88);
//rdata,2,6,depend,1,3,5,7
for (int i = 2; i < rArrayLen; i += 4)
rData[i] = _mm_shuffle_ps(rData[i - 1], rData[i + 1], 0x22);
//rdata,3,7,depend,1,5
for (int i = 3; i < rArrayLen; i += 4)
rData[i] = _mm_shuffle_ps(rData[i - 2], rData[i], 0x77);
//rdata,1,5
for (int i = 0; i < pairSize; i += 2)
rData[i * 2 + 1] = _mm_shuffle_ps(temp[i], temp[i + 1], 0xdd);
}
void sortInRegister(float *data)
{
__m128 rData[rArrayLen];
loadData(data, rData, rArrayLen);
simdOddEvenSort(rData);
bitonicSort428<4>(rData, true);
bitonicSort8216<2>(rData, true);
bitonicSort16232(rData);
storeData(data, rData, rArrayLen);
}
| [
"[email protected]"
] | |
3cb9979bd59cdbd28429ef6d2b72a88a1ede8f04 | a05f3e3bcc9f1161f5890f98eaf1a4a7129846ce | /c++/VirtualClassCreater/ViratualFunctionArgumentName.cpp | 66f3fee181b73ce790ea55289c9aaee10b963fcf | [] | no_license | sosflyyi/laboratory | 17d3d0e13a62674c244a3bcd7bdca8803fe89f32 | 9a3f47c99279e328d2719d21dfd13cd212fab5b6 | refs/heads/master | 2023-04-09T23:20:02.592346 | 2016-05-09T13:27:16 | 2016-05-09T13:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | cpp |
#include <iostream>
class Base {
public:
virtual void out(int name) = 0;
};
class Child : public Base {
public:
void out(int ID) {
std::cout << ID << std::endl;
}
};
int main() {
Child child;
child.out(3);
return 0;
}
| [
"[email protected]"
] | |
24bc62f5d4f59c1d86a28d101a88b0bf9ae1fbaa | d4fd235e20b25d7792a154ec6885ff7155085c0f | /full_v4_GP_with_button/full_v4_GP_with_button.ino | 7db648eb9ef7abf8433f2f1d240549be660e7c5c | [] | no_license | RyanJuraidini/FAU-Hackathon-2019 | 44cc5cb0f866eedc3097104b2236fc7bbb2380fe | b23e0460d49a18a3259c0ac87810da423f4f6770 | refs/heads/master | 2020-08-08T10:07:23.990716 | 2019-02-21T13:59:18 | 2019-02-21T13:59:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,367 | ino | /* This code is to read raw distance signal from a ultrasonic sensor and change the
* color or a Neo Pixel RGB accordinly to a pre-defined distance range
*/
//libraries
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#include <ArduinoJson.h>
#include <PubSubClient.h> //for MQTT connection
#include "WiFi.h"
#include <WiFiUdp.h>
//Watson IoT connection details
#define MQTT_HOST "x5ri6x.messaging.internetofthings.ibmcloud.com" //First 6 characters found at (IBM Watson IoT Platform->Settings->Identity
#define MQTT_PORT 1883
#define MQTT_DEVICEID "d:x5ri6x:ESP32S:dev01"
// ^ ^ ^---------|
// org identity device type device id
#define MQTT_USER "use-token-auth"
#define MQTT_TOKEN "WATSONINMYASS" //auth token :)
#define MQTT_TOPIC "iot-2/evt/status/fmt/json"
#define MQTT_TOPIC_DISPLAY "iot-2/cmd/display/fmt/json"
//int status = WL_IDLE_STATUS;
//GO PRO
char ssid_GP[] = "learygopro"; // your network SSID (name) FOR GOPRO
char pass_GP[] = "vuvuzela"; // your network password FOR GOPRO
//FAU NETWORK
char ssid_FAU[] = "fau"; // your network SSID (name) FOR FAU NETWORK
char pass_FAU[] = ""; // your network password FOR FAU NETWORK
int localPort = 7;
byte broadCastIp[] = { 10,5,5,9 };
//!!!!!!!!!!!!!!!!!!!!!!!!!!!
//ENTER YOUR MAC ADDRESS HERE
//!!!!!!!!!!!!!!!!!!!!!!!!!!!
byte remote_MAC_ADD[] = { 0xd4, 0xd9, 0x19, 0x8e, 0x55, 0x67 };
int wolPort = 9;
//int switch_wifi = 0;
WiFiUDP Udp;
WiFiClient client;
const char* host = "10.5.5.9";
const int httpPort = 80;
bool WIFI = false;
char connection = 'N';
// END WIFI SETUP
//**********************************************************************
//Define variables for BPM
int x=0;
int lastx=0;
int lasty=0;
int LastTime=0;
int ThisTime;
bool BPMTiming=false;
bool BeatComplete=false;
int BPM=0;
#define UpperThreshold 2730
#define LowerThreshold 2710
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET 22 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define NUMFLAKES 10 // Number of snowflakes in the animation example
#define LOGO_HEIGHT 16
#define LOGO_WIDTH 16
//DHT
#define DHTTYPE DHT11
#define DHT_PIN 4
#define BUTTON_PIN 39 //Menu switch button
#define REC_BUTTON_PIN 35 //Button to stop GoPro recording
// RANGE SETTINGS - SONAR
#define CLOSE 0
#define FAR 200
#define CENTER 50
//PIR MOTION
int sonarInputPin = 5; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int sonarValue = digitalRead(sonarInputPin); // read input value
// variables to hold data for JSON
StaticJsonBuffer<200> jsonBuffer;
JsonObject& payload = jsonBuffer.createObject();
JsonObject& status = payload.createNestedObject("d");
static char msg[200];
//JSON delimiter global variable declaration b: BPM m: Motion
int b = 0;
int m = 0;
unsigned long startTime; //timer to determine when to send data
/*
static const unsigned char PROGMEM logo_bmp[] =
{ B00000000, B11000000,
B00000001, B11000000,
B00000001, B11000000,
B00000011, B11100000,
B11110011, B11100000,
B11111110, B11111000,
B01111110, B11111111,
B00110011, B10011111,
B00011111, B11111100,
B00001101, B01110000,
B00011011, B10100000,
B00111111, B11100000,
B00111111, B11110000,
B01111100, B11110000,
B01110000, B01110000,
B00000000, B00110000 };
*/
// defines pins numbers for HC SR04 Sensor
const int trigPin = 23; // TRIGGER PIN
const int echoPin = 19; // ECHO PIN
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
int recordingButton = 0; // button state for recording
int recButtonState = 0; // current state of recording button
int lastRecButtonState = 0; // previous state of recording button
int recButtonPushCounter = 0; // counter to determine button has been pushed
int flag = 0; // semaphore used to turn off recording. Happens once.
int d = 0.0; // distance
// defines variables for sonar
long duration;
int distance;
//variables for dht
DHT dht(DHT_PIN, DHTTYPE);
float h = 0.0; // humidity
float t = 0.0; // temperature
// MQTT objects
void callback(char* topic, byte* payload, unsigned int length);
WiFiClient wifiClient;
PubSubClient mqtt(MQTT_HOST, MQTT_PORT, callback, wifiClient);
// callback for payload
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] : ");
payload[length] = 0; // ensure valid content is zero terminated so can treat as c-string
Serial.println((char *)payload);
}
//**********************************************************************************
//SETUP
//**********************************************************************************
void setup() {
//Timer code to post data to Watson
startTime = millis();
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(sonarInputPin, INPUT); // declare sensor as input
Serial.begin(115200); // Starts the serial communication
Wire.begin();
display.begin(SSD1306_SWITCHCAPVCC, 0x3c);
dht.begin();
pinMode(BUTTON_PIN, INPUT); //initialize pushbutton pin as an input
pinMode(REC_BUTTON_PIN, INPUT); //initialize pushbutton pin for recording as an input
ConnectToWifi(ssid_GP, pass_GP);
CameraInitiate();
StartRecording();
//delay(10000);
//StopRecording();
delay(1000);
WiFi.disconnect(true); //hopefully?
delay(5000);
//WiFi.begin(ssid_FAU, pass_FAU);
ConnectToWifi(ssid_FAU, pass_FAU);
//delay(10000);
//StartMQTT();
/*mqtt.loop();
if(WiFi.SSID() != ssid_GP){
while (!mqtt.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqtt.connect(MQTT_DEVICEID, MQTT_USER, MQTT_TOKEN)) {
Serial.println("MQTT Connected");
mqtt.subscribe(MQTT_TOPIC_DISPLAY);
mqtt.loop();
} else {
Serial.println("MQTT Failed to connect!");
delay(5000);
}
}
}
*/
}
// BEGIN MAIN LOOP
//*********************************************************************************
//*********************************************************************************
void loop() {
sonarValue = digitalRead(sonarInputPin); // read input value - Sonar
//-----------------------------------------------------------------------
// Push button for menu toggle
//-----------------------------------------------------------------------
// read the pushbutton input pin:
buttonState = digitalRead(BUTTON_PIN);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button went from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
} else {
// if the current state is LOW then the button went from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
//delay(50); Comment out to speed up
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
//-----------------------------------------------------------------------
// Push button for GoPro stop recording
//-----------------------------------------------------------------------
recButtonState = digitalRead(REC_BUTTON_PIN);
// compare the buttonState to its previous state
if (recButtonState != lastRecButtonState) {
// if the state has changed, increment the counter
if (recButtonState == HIGH) {
// if the current state is HIGH then the button went from off to on:
recButtonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(recButtonPushCounter);
} else {
// if the current state is LOW then the button went from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
//delay(50); Comment out to speed up
}
// save the current state as the last state, for next time through the loop
lastRecButtonState = recButtonState;
//-----------------------------------------------------------------------
if(recButtonPushCounter > 0){
recButtonPushCounter = 0;
WiFi.disconnect(true);
delay(1000);
ConnectToWifi(ssid_GP, pass_GP);
//delay(1000);Comment out to speed up. Halved on next line
delay(500);
StopRecording();
//delay(1000);Comment out to speed up. Halved on next line
delay(500);
WiFi.disconnect(true);
//delay(1000); Comment out to speed up. Halved on next line
delay(500);
ConnectToWifi(ssid_FAU, pass_FAU);
}
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
d = distance;
h = dht.readHumidity();
t = dht.readTemperature(true);
//Begin BPM calc
//****************************************************************
b = BPM;
if(x>127)
{
//oled.clearDisplay();
x=0;
lastx=x;
}
ThisTime=millis();
int value=analogRead(A0);
//oled.setTextColor(WHITE);
int y=(value/32)-60;
//oled.writeLine(lastx,lasty,x,y,WHITE);
lasty=y;
lastx=x;
// calc bpm
//Serial.println((String)"BPM: " + BPM);
if(value>UpperThreshold)
{
if(BeatComplete)
{
BPM=ThisTime-LastTime;
BPM=int(60/(float(BPM)/1000));
BPMTiming=false;
BeatComplete=false;
//tone(8,1000,250);
}
if(BPMTiming==false)
{
LastTime=millis();
BPMTiming=true;
}
}
if((value<LowerThreshold)&(BPMTiming))
BeatComplete=true;
//Serial.println((String)"BPM: " + BPM);
x++;
//****************************************************************
// End BPM calc
//Display to OLED
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1.8);
display.setCursor(0,0);
if(buttonPushCounter == 0){
display.setTextSize(7);
display.setTextColor(WHITE);
display.setCursor(0,10);
display.print("P10");
}
if(buttonPushCounter%2 == 1){
PrintDistance(d);
PrintTemp();
PrintBPM(BPM);
ShowWifiStatus(WIFI);
PrintMotion();
}
if(buttonPushCounter%2 == 0 && buttonPushCounter > 1){
display.setTextSize(2);
display.setTextColor(WHITE);
display.writeLine(lastx,lasty,x,y,WHITE);
display.writeFillRect(0,50,128,16,BLACK);
display.setCursor(0,50);
display.print(BPM);
display.print(" BPM");
PrintMotion();
delay(20);
}
display.display();
// Prints the distance on the Serial Monitor
//Serial.print("Distance: ");
//Serial.println(distance);
delay(100);
//SEND JSON
if(millis() - startTime >= 5000){
StartMQTTLoop();
startTime = millis();
}
//delay(100); Comment out to speed up
if (h > 80) {
WiFi.disconnect(true);
//delay(5000);
delay(1000);
ConnectToWifi(ssid_GP, pass_GP);
//delay(1000);Comment out to speed up. Halved on next line
delay(500);
StopRecording();
//delay(1000);Comment out to speed up. Halved on next line
delay(500);
WiFi.disconnect(true);
//delay(1000); Comment out to speed up. Halved on next line
delay(500);
ConnectToWifi(ssid_FAU, pass_FAU);
}
}
// END MAIN LOOP
//*********************************************************************************
//*********************************************************************************
//Function Definitions
void StartMQTTLoop() {
mqtt.loop();
while (!mqtt.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqtt.connect(MQTT_DEVICEID, MQTT_USER, MQTT_TOKEN)) {
Serial.println("MQTT Connected");
mqtt.subscribe(MQTT_TOPIC_DISPLAY);
mqtt.loop();
} else {
Serial.println("MQTT Failed to connect!");
delay(5000);
}
}
mqtt.loop(); // moved from line 416
// Print Message to console in JSON format
status["temp"] = t;
status["humidity"] = h;
status["distance"] = d;
status["pulse"] = b;
status["motion"] = m;
//status["test"] = "test";
payload.printTo(msg, 200);
Serial.println(msg);
if (!mqtt.publish(MQTT_TOPIC, msg)) {
Serial.println("MQTT Publish failed");
}
// Pause - but keep polling MQTT for incoming messages
/*
for(int i = 0; i < 1; i++) {
//mqtt.loop();
delay(250);
}
//mqtt.loop();
*/
}
void PrintTemp() {
display.print((String)"\n\nTemp: " + t + " F" + "\n\nHum: " + h + " %");
}
void PrintMotion() {
if (sonarValue == HIGH) {
if (pirState == LOW) {
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(2);
display.setCursor(0,0);
display.print("\nMotion \ndetected!");
m = 1;
delay(1000);
}
}
else {
if (pirState == HIGH) {
display.print("\nMotion ended!");
pirState = LOW;
}
m = 0;
}
}
void PrintDistance(int d) {
display.print("Target Distance: ");
display.print(d);
}
void PrintBPM(int BPM){
display.print("\n\nBPM: ");
display.print(BPM);
}
void ConnectToWifi(char ssid[], char pass[]) {
// attempt to connect to Wifi network:
while ( WiFi.status() != WL_CONNECTED) {
WIFI = false;
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
WiFi.begin(ssid, pass);
// wait 8 seconds for connection:
delay(8000);
}
Serial.println("Connected to wifi");
WIFI = true;
printWifiStatus();
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
void SendMagicPacket(){
//Create a 102 byte array
byte magicPacket[102];
// Variables for cycling through the array
int Cycle = 0, CycleMacAdd = 0, IndexArray = 0;
// This for loop cycles through the array
for( Cycle = 0; Cycle < 6; Cycle++){
// The first 6 bytes of the array are set to the value 0xFF
magicPacket[IndexArray] = 0xFF;
// Increment the array index
IndexArray++;
}
// Now we cycle through the array to add the GoPro address
for( Cycle = 0; Cycle < 16; Cycle++ ){
//eseguo un Cycle per memorizzare i 6 byte del
//mac address
for( CycleMacAdd = 0; CycleMacAdd < 6; CycleMacAdd++){
magicPacket[IndexArray] = remote_MAC_ADD[CycleMacAdd];
// Increment the array index
IndexArray++;
}
}
//The magic packet is now broadcast to the GoPro IP address and port
Udp.beginPacket(broadCastIp, wolPort);
Udp.write(magicPacket, sizeof magicPacket);
Udp.endPacket();
}
void StartRecording(){
Serial.print("connecting to ");
Serial.println(host);
if (!client.connect("10.5.5.9", httpPort)) {
Serial.println("connection failed");
return;
}
//Command for starting recording
String StartUrl = "/gp/gpControl/command/shutter?p=1";
Serial.print("Requesting URL: ");
Serial.println(StartUrl);
client.print(String("GET ") + StartUrl + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Recording");
}
void StopRecording(){
Serial.print("connecting to ");
Serial.println(host);
if (!client.connect("10.5.5.9", httpPort)) {
Serial.println("connection failed");
return;
}
//Command for stopping recording
String StopUrl = "/gp/gpControl/command/shutter?p=0";
Serial.print("Requesting URL: ");
Serial.println(StopUrl);
client.print(String("GET ") + StopUrl + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Stopped");
}
void BootPhotoMode(){
//Starts up photo mode
Serial.print("connecting to ");
Serial.println(host);
if (!client.connect("10.5.5.9", httpPort)) {
Serial.println("connection failed");
return;
}
String BootUrl = "/gp/gpControl/command/sub_mode?mode=1&sub_mode=0";
Serial.print("Requesting URL: ");
Serial.println(BootUrl);
client.print(String("GET ") + BootUrl + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Photo Mode!");
}
void TakeAPic() {
Serial.print("connecting to ");
Serial.println(host);
if (!client.connect("10.5.5.9", httpPort)) {
Serial.println("connection failed");
return;
}
//Command to take a pic
String StopUrl = "/gp/gpControl/command/shutter?p=1";
Serial.print("Requesting URL: ");
Serial.println(StopUrl);
client.print(String("GET ") + StopUrl + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Pic Taken!");
}
// FUNCTION TO WAKE UP THE CAMERA
void CameraInitiate(){
//Begin UDP communication
Udp.begin(localPort);
//Send the magic packet to wake up the GoPro out of sleep
delay(2000);
SendMagicPacket();
delay(5000);
// Absolutely necessary to flush port of UDP junk for Wifi client communication
Udp.flush();
delay(1000);
//Stop UDP communication
Udp.stop();
delay(1000);
}
void ShowWifiStatus(bool WIFI){
if(WIFI == true)
connection = 'Y';
else
connection = 'N';
display.print(" WIFI: ");
display.print(connection);
}
| [
"[email protected]"
] | |
13b8dab42d9a63dbb87a498387aa8ccc58a6222c | b2f3850ec31186f0b342aa8c538e7970635ea53e | /SummerSchool - C++/7_Napis/Napis.cpp | 876a1e1ad6895c4f5016e7b63f97b6ebdf1545ce | [] | no_license | kubaa91pl/MyProjects | 51db5120496bf066a7ff70b2b6d1490efad194db | 9bbfe81ecd9660d1acbf4a7e9a558acf010f97a3 | refs/heads/master | 2021-05-04T11:37:07.792389 | 2016-08-22T10:36:58 | 2016-08-22T10:36:58 | 54,124,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,524 | cpp | //
// Created by Admin on 2016-08-03.
//
#include <iostream>
#include "Napis.h"
Napis::Napis(const char *text) {
this->length = this->getTextLength(text);
this-> napis = new char[length];
this-> napis= text;
};
Napis::~Napis(){
delete napis;
};
void Napis::test(){
Napis::test(Napis::getTextLength(this->napis));
};
void Napis::test(int length) {
std::cout << "This is the original text: " << std::endl << std::endl;
for(int i=0; i<length; i++){
std::cout<< napis[i];
}
};
int Napis::getTextLength(const char* text){
int length = 0;
while(text[length]!='\0'){
length++;
}
return length;
};
void Napis::getComments(){
int i=0;
std::cout << "Comments: " << std::endl << std::endl;
while(napis[i+1]!='\0'){
if(napis[i]=='/'&& napis[i+1]=='/'){
std::cout<<std::endl;
i=i+2;
while(napis[i]!='\n'){
std::cout<<napis[i];
i++;
}
std::cout << std::endl;
}
if(napis[i]=='/'&& napis[i+1]=='*'){
std::cout<<std::endl;
i=i+2;
while( (!(napis[i]=='*'&&napis[i+1]=='/')&& i !=length) ){
if(napis[i]=='\n'){
std::cout<<std::endl;
}
std::cout<<napis[i];
i++;
}
std::cout << std::endl;
}
i++;
}
};
| [
"[email protected]"
] | |
bc939f0290962f6bb10070feaabf52e5da02a548 | 266b899315cfdde3823ba405cedbb8ff553f97af | /src/Model/CtecList.cpp | 8b33c531b7a38e7ffc675217626239df3189c0b2 | [] | no_license | abro5723/NodeProjectC- | 992df24ca670fab2368f53495d9897b8203f1345 | ccb9c4d3c026c0bf703a1ca62b7fa618c69d12fe | refs/heads/master | 2021-04-26T16:43:55.789687 | 2016-03-18T14:38:41 | 2016-03-18T14:38:41 | 50,522,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,921 | cpp | /*
* CtecList.cpp
*
* Created on: Feb 22, 2016
* Author: abro5723
*/
#include "CtecList.h"
template <class Type>
CtecList<Type>::CtecList()
{
this -> size = 0;
this->head = nullptr;
this->end = nullptr;
}
template <class Type>
CtecList<Type>::~CtecList()
{
}
template <class Type>
Type CtecList<Type> :: removeFromFront()
{
//Incase we require that which we remove
Type returnValue;
assert(this->size > 0);
//Find the next spot
ArrayNode<Type> * newHead = new ArrayNode<Type>();
newHead = this->head->getNext();
//Get what was the head node!
returnValue = this->head->getValue();
//Remove head
delete this -> head;
//Move head to next
this->head = newHead;
this->calculatedSize();
return returnValue;
}
template <class Type>
Type CtecList<Type> :: removeFromIndex(int index)
{
Type returnedValue;
Type thingToRemove;
assert(this->size > 0);
assert(size > 0 && index >= 0 && index < size);
ArrayNode<Type> * previous, deleteMe, newNext;
if(index == 0)
{
thingToRemove = removeFromFront();
}
else if(index == size-1)
{
thingToRemove = removeFromEnd();
}
else
{
for(int spot=0; spot < index+1; spot++)
{
}
}
this->calculatedSize();
return thingToRemove;
}
template <class Type>
void CtecList<Type> :: calculatedSize()
{
assert(size >= 0);
ArrayNode<Type> * counterPointer = head;
int count = 0;
if(counterPointer == nullptr)
{
this->size = 0;
return;
}
else
{
count++;
while(counterPointer->getNext() != nullptr)
{
counterPointer = counterPointer->getNext();
count++;
}
this->size = count;
}
}
template <class Type>
Type CtecList<Type> :: removeFromEnd()
{
Type valueToRemove;
assert(size > 0);
if(size == 1)
{
valueToRemove = removeFromFront();
end = nullptr;
head = nullptr;
calculatedSize();
return valueToRemove;
}
else
{
ArrayNode<Type> * current = head;
for(int spot = 0; spot<size-1; spot++)
{
current = current ->getNext();
}
valueToRemove = current->getNext()->getValue();
end = current;
delete current->getNext();
}
this->calculatedSize();
return valueToRemove;
}
template <class Type>
void CtecList<Type> :: addToEnd(Type value)
{
ArrayNode<Type> * newStuff = new ArrayNode<Type>(value);
end->setNext(newStuff);
end = newStuff;
calculatedSize();
}
template <class Type>
void CtecList<Type> :: addToFront(const Type& value)
{
ArrayNode<Type> * newStuff = new ArrayNode<Type>(value, head);
head = newStuff;
}
template <class Type>
void CtecList<Type> :: addAtIndex(int index, Type value)
{
}
template <class Type>
Type CtecList<Type> :: getFront()
{
Type returnValue;
Type thingToGet;
thingToGet = returnValue = head->getValue();
}
template <class Type>
Type CtecList<Type> :: getEnd()
{
}
template <class Type>
Type CtecList<Type> :: getFromIndex(int index)
{
}
template <class Type>
Type CtecList<Type> :: set(int index, Type value)
{
}
| [
"[email protected]"
] | |
8a6408969f555bdc250502cbcb77d9617048b56a | 951e2c14f6af1002a3ed35f8a9f921c23c2bb988 | /src/coord.cpp | 4fc89b25604d5b5c53d5f2792f78f07790a6b41c | [] | no_license | umfranzw/gol-pi | 23f4a66bc95aeeeb0f414d4f3023b0d4b7e62799 | f5ef13e897d511b90ce01258a8ffe369ba396d48 | refs/heads/master | 2022-11-18T02:08:19.676759 | 2020-07-02T17:54:27 | 2020-07-02T17:54:27 | 276,711,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 213 | cpp | #include "coord.hpp"
#include "constants.hpp"
Coord::Coord(int x, int y) {
this->x = x;
this->y = y;
}
bool Coord::operator==(const Coord &rhs) const {
return this->x == rhs.x && this->y == rhs.y;
}
| [
"[email protected]"
] | |
002a0b4a5cf67ee12edba93e34afdac5583fee01 | 6fa96823c5188a6bf9d156ef5e6871e2393d5950 | /src/runtime/base/taint/taint_observer.h | da16265a5e81c9f1ad3ce2c73201933dded43c5b | [
"Zend-2.0",
"PHP-3.01",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | thaingo/hiphop-php | 97387f875806e658e25205cd5ffb349e125fb14f | 565445134b073530686583bf14e53dbcb80aecdf | refs/heads/master | 2021-01-15T21:19:36.991824 | 2011-03-15T16:26:57 | 2011-03-16T19:00:49 | 1,503,470 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,411 | h | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef __HPHP_TAINT_OBSERVER_H__
#define __HPHP_TAINT_OBSERVER_H__
#ifdef TAINTED
/**
* The purpose of this class is to keep track of which strings are getting
* "read" and which strings are getting created. This allows us to
* taint strings by modifying the idl, and saves us from having taint related
* code spread all over the hphp codebase.
*
* This code is meant to be created in the stack. You can therefore not
* try to do things like new TaintObserver().
*/
#include <runtime/base/taint/taint_data.h>
#include <util/thread_local.h>
namespace HPHP {
class StringData;
class StringBuffer;
class TaintObserver {
public:
/**
* set_mask controls which bits get set for all new strings
* clear_mask controls which bits will be cleared for all new strings
* if set_mask and clear_mask are both set to 0, then we propagate
* using the input strings.
*/
TaintObserver(bitstring set_mask = 0, bitstring clear_mask = 0);
~TaintObserver();
/**
* This functions needs to be called whenever data inside strings is accessed.
*/
static void RegisterAccessed(const StringData *string_data);
static void RegisterAccessed(const StringBuffer *string_buffer);
/**
* This function needs to be called whenever a string is created or mutated.
*/
static void RegisterMutated(StringData *string_data);
static void RegisterMutated(StringBuffer *string_buffer);
private:
bitstring m_set_mask;
bitstring m_clear_mask;
TaintObserver* m_previous;
static DECLARE_THREAD_LOCAL(TaintObserver*, instance);
// Disallow new, copy constructor and assignment operator
void* operator new(long unsigned int size);
TaintObserver(TaintObserver const&);
TaintObserver& operator=(TaintObserver const&);
TaintData m_current_taint;
};
}
// Helper macro. If you use TAINT_OBSERVER, you don't need to
// wrap things in #ifdef TAINTED ... #endif
#define TAINT_OBSERVER(set, clear) \
TaintObserver taint_observer((set), (clear))
#define TAINT_OBSERVER_REGISTER_ACCESSED(obj) \
TaintObserver::RegisterAccessed((obj))
#define TAINT_OBSERVER_REGISTER_MUTATED(obj) \
TaintObserver::RegisterMutated((obj))
#else
#define TAINT_OBSERVER(set, clear) /* do nothing (note: not ; friendly) */
#define TAINT_OBSERVER_REGISTER_ACCESSED(obj) /* do nothing */
#define TAINT_OBSERVER_REGISTER_MUTATED(obj) /* do nothing */
#endif // TAINTED
#endif // __HPHP_TAINT_OBSERVER_H__
| [
"[email protected]"
] | |
e6fc17e0b8c6df2e38fdfa40eff2c778e96f4c33 | 35c04ea32351dc95bc18d46e5c70dda9c1e08668 | /Examples/CodeWarrior/TWR-K60F120M/TWR-K60F120M_FatFS_UFFS/Sources/Kinetis_NFC.h | 1cc82b131014a63c3cd163bb3b399c910c1bb48c | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | ErichStyger/mcuoneclipse | 0f8e7a2056a26ed79d9d4a0afd64777ff0b2b2fe | 04ad311b11860ae5f8285316010961a87fa06d0c | refs/heads/master | 2023-08-28T22:54:08.501719 | 2023-08-25T15:11:44 | 2023-08-25T15:11:44 | 7,446,094 | 620 | 1,191 | NOASSERTION | 2020-10-16T03:13:28 | 2013-01-04T19:38:12 | Batchfile | UTF-8 | C++ | false | false | 4,910 | h | /**
* @file Kinetis_NFC.h
*
* Created on: Mar 6, 2014
* Author: Marc Lindahl
* NAND Flash access routines for Kinetis
* Relies on Init_NFC ProcessorExpert component.
*
* Some code lifted from KINETIS_120MHZ_SC nfc.
*
* Simple driver, does one block/sector at a time, with no overlap.
*
* Does not need or use interrupts.
*
* Also not thread safe - you'll need to add locks or other ways to serialize access.
*
* Supports two chip selects... both memories must be identical, and have R/B common.
*
*/
#ifndef KINETIS_NFC_H_
#define KINETIS_NFC_H_
#include <cstdint>
#include "NFC.h"
#include "NFC_PDD.h"
#include "FRTOS1.h"
// processor expert settings - Init_NFC doesn't create defines for these, please duplicate your settings
#define NFC_DATA_SIZE 0x400 ///< size of page data size. Must be multiple of 256.
#define NFC_SPARE_SIZE 0x10 ///< size of user spare data (not incuding ECC). Must be multple of 8.
#define NFC_ECC_SIZE 0x10 ///< size of ECC area used by NFC. Must be multple of 8.
#define NFC_BADBLOCK_IDX 0x400 ///< index of back block marker
#define NFC_ECCINFO_IDX (0x800+4) ///< address in buffer of ECC info (note in Init_NFC val is shifted left 3) plus offset (see https://community.freescale.com/thread/316862)
#define NFC_SPARE_IDX NFC_DATA_SIZE ///< spare area right after data area
#define NFC_IDCNT 5 ///< almost always 5 bytes of ReadID
#define NFC_16BIT 1 ///< ==1 if NAND chips are 16bit or ==0 for 8bit
#define NFC_BLOCKSIZE 64 ///< pages per block
#define NFC_BLOCKSHIFT 6 ///< 2^NFC_BLOCKSHIFT == NFC_BLOCKSIZE
#define NFC_NBLOCKS 2048 ///< number of blocks in the NAND
#define NFC_NCHIPS 1 ///< number of NAND chips. Assumed connection is individual CE to each chip, common R/nB
#define NFC_BUF 0 ///< default buffer to use (within NFC)
#define NFC_READID_MFG 0 ///< manufacturer ID info command
#define NFC_READID_ONFI 0x20 ///< should return ascii "ONFI" in first 4 bytes
#define OS_YIELD() FRTOS1_taskYIELD() ///< if there's an OS and you want to yield during wait loops
//derived defines
#define NFC_PAGEMASK ((1<<NFC_BLOCKSHIFT)-1)
#define NFC_BUFADDR ((uint8_t*)((uint8_t*)NFC_DEVICE+(0x1000 * NFC_BUF)))
#define NFC_SIMPLECACHE ///< if defined, then checks if the last access was the same, and doesn't re-do it (i.e. read same page twice)
/**
* initialize NFC peripheral and reset NAND chip(s)
*/
void nand_init(void);
/**
* reset a NAND chip
* @param chipselect = 0 or 1
*/
void nfc_reset_cmd(uint8_t chipselect);
/**
* read ID of selected chip
* @param chipselect = 0 or 1
* @param ID address NFC_READID_MFG or NFC_READID_ONFI. See NAND data sheet for details of return
* ID values will be in NFC_SR1 and NFC_SR2 upon success.
*/
void nfc_read_flash_id(uint8_t chipselect, uint8_t addr);
/**
* erase block of selected chip
* @param chipselect = 0 or 1
* @param block block address (up to 24 bytes)
*/
void nfc_block_erase(uint8_t chipselect, uint32_t block);
/**
* program page with data from buffer and optionally spare data from spare buffer.
* data or spare can be NULL, in which case the NFC buffer contents won't be touched in that area.
* @param chipselect = 0 or 1
* @param block block address
* @param page page address (within block)
* @param data data buffer pointer. If NULL no DMA will occur. Must be aligned on 8-byte boundary.
* @param datalen length of data. Note: if data is less than NFC_DATA_SIZE
* (or NFC_DATA_SIZE+NFC_SPARE_SIZE if spare==NULL) then the remainder will be stuffed with 0xFF before programming.
* MUST BE MULTIPLE OF 8!
* @param spare spare data buffer pointer. If NULL no DMA will occur. Must be aligned on 8-byte boundary.
* @param sparelen length of spare data. If NULL no DMA will occur. MUST BE MULTIPLE OF 8!
*/
void nfc_page_program(uint8_t chipselect, uint32_t block, uint16_t page, uint8_t *data, uint16_t datalen, uint8_t *spare, uint16_t sparelen);
/**
* read page to data buffer and optionally spare data to spare buffer.
* data or spare can be NULL, in which case the NFC buffer contents won't be transferred.
* Transfer uses DMA channel 0 for data and channel 1 for spare.
* @param chipselect = 0 or 1
* @param block block address
* @param page page address (within block)
* @param data data buffer pointer. If NULL no DMA will occur. Must be aligned on 8-byte boundary.
* @param datalen length of data. MUST BE MULTIPLE OF 8!
* @param spare spare data buffer pointer. Must be aligned on 8-byte boundary.
* @param sparelen length of spare data. If NULL no DMA will occur. MUST BE MULTIPLE OF 8!
* @return ECC result. If result <128, ECC is successful, >=128 failed.
*/
uint8_t nfc_page_read(uint8_t chipselect, uint32_t block, uint16_t page, uint8_t *data, uint16_t datalen, uint8_t *spare, uint16_t sparelen);
#endif /* KINETIS_NFC_H_ */
| [
"[email protected]"
] | |
acdeff8b8791ec41bb69d87579f4d3bdb729a6c7 | 4e22d261d7dcf5fe2731d77ba3cfb47c5568977c | /Source/Editor/NodeGraph/NodeManager.cpp | b9ee0b855e884a1e10e5550df466eea332885df3 | [] | no_license | SeraphinaMJ/Reformed | 2d7424d6d38d1cfaf8d385fade474a27c02103a5 | 8563d35ab2b80ca403b3b57ad80db1173504cf55 | refs/heads/master | 2023-04-06T00:40:34.223840 | 2021-05-06T11:25:51 | 2021-05-06T11:25:51 | 364,884,928 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 23,037 | cpp | /*!***************************************************************************************
\file NodeManager.cpp
\author Ryan Booth
\date 9/12/2019
\copyright All content © 2018-2019 DigiPen (USA) Corporation, all rights reserved.
\par
\brief
*****************************************************************************************/
#include <fstream>
#include <sstream>
//#include <objbase.h>
#include "NodeManager.hpp"
#include "../BehaviorSystem/BehaviorInterpreter.hpp"
#include "../EngineController.hpp"
#include <EngineRunner.hpp>
#include <Engine.hpp>
#include "../EditorLogger.hpp"
#ifdef max
#undef max // fuck you microsoft
#endif
//RapidJSON
#include <rapidjson.h>
#include "document.h"
#include "stringbuffer.h"
#include "writer.h"
#include "prettywriter.h"
#include "istreamwrapper.h"
#include "filereadstream.h"
NodeManager::NodeManager(Editor::engineController * p_engine_controller, Editor::EditorLogger & p_logger) : m_num_nodes(0), m_num_active_nodes(0), m_node_selected(-1), m_nodes(new std::unordered_map<int, EditorNode*>()), m_engine_controller(p_engine_controller), m_logger(p_logger)
{
}
NodeManager::~NodeManager()
{
reset();
delete m_nodes;
}
void NodeManager::reset()
{
//Delete all the nodes
for (auto i_node = m_nodes->begin(); i_node != m_nodes->end(); ++i_node)
{
delete i_node->second;
}
m_nodes->clear();
m_num_nodes = 0;
m_num_active_nodes = 0;
m_node_selected = -1;
m_logger.AddLog("[NOTICE] Resetting Node Manager.\n");
}
void NodeManager::addNode(EditorNode * p_node, int p_id)
{
//Generate id for // node SHOULD BE GUID
//GUID l_gidReference;
//HRESULT hCreateGuid = CoCreateGuid(&l_gidReference);
//int l_new_id = 0;
//if(p_id != 0)
//{
// l_new_id = m_num_nodes;
//}
//else
//{
// l_new_id = p_id;
//}
//Make sure a node with given id doesn't already exist
if (m_nodes->find(p_id/*l_new_id*/) == m_nodes->end())
{
p_node->setId(/*l_new_id*/p_id);
bool l_result = m_nodes->insert(std::make_pair(p_id/*l_new_id*/, p_node)).second;
if (!l_result)
{
m_logger.AddLog("[ERROR] Failed to insert node with id: %i into manager.\n", p_id/*l_new_id*/);
}
else
{
m_num_nodes += 1;
m_num_active_nodes += 1;
}
}
else
{
m_logger.AddLog("[ERROR] Node with given id: %i already exists!\n", p_id/*l_new_id*/);
}
}
void NodeManager::setSelectedNodeId(int p_node_id)
{
//Validate node with given id exists
if (m_nodes->find(p_node_id) != m_nodes->end())
{
m_node_selected = p_node_id;
}
else if(p_node_id == -1)
{
m_node_selected = -1;
}
else
{
m_logger.AddLog("[ERROR] No node can be selected with id: %i.\n", p_node_id);
m_node_selected = -1;
}
}
const std::unordered_map<std::string, std::vector<std::pair<std::string, std::string>>>& NodeManager::getNodeDefinitions()
{
return m_node_factory_list;
}
EditorNode * NodeManager::createEditorNodeFromScratch(const std::string & p_type_name,
const std::pair<std::string, std::string> & p_node_type_name)
{
EditorNode * l_new_node = new EditorNode();
if(l_new_node != nullptr)
{
l_new_node->setName(p_node_type_name.second);
l_new_node->setClassName(p_node_type_name.first);
l_new_node->setTypeName(p_type_name);
//node manipulator ask for typeRT
auto Node_Manipulator = m_engine_controller->getEngineRunner()->getEngine()->getNodeManipulator().lock();
typeRT l_data = BehaviorInterpreter::GetInstance().GetDefaultTypeRT(p_node_type_name.first);
l_new_node->setRenderData(l_data);
return l_new_node;
}
m_logger.AddLog("[ERROR] Failed to create node!\n");
return nullptr;
}
EditorNode * NodeManager::createEditorNodeJSON(const std::string & p_type_name,
std::pair<std::string, std::string> p_node_type_name, const rapidjson::Value & json_data)
{
EditorNode * l_new_node = new EditorNode();
if (l_new_node != nullptr)
{
l_new_node->setName(p_node_type_name.second);
l_new_node->setClassName(p_node_type_name.first);
l_new_node->setTypeName(p_type_name);
//node manipulator ask for typeRT
auto Node_Manipulator = m_engine_controller->getEngineRunner()->getEngine()->getNodeManipulator().lock();
typeRT specializedData;
BehaviorInterpreter::GetInstance().FillTypeRT(specializedData, p_node_type_name.first, json_data);
l_new_node->setRenderData(specializedData);
return l_new_node;
}
m_logger.AddLog("[ERROR] Failed to create node!\n");
return nullptr;
}
void NodeManager::removeNode(int p_node_id)
{
//Validate node with given id exists
auto i_node = m_nodes->find(p_node_id);
if (i_node != m_nodes->end())
{
//Delete node links associated with this node
for(auto i_node_linked = m_nodes->begin(); i_node_linked != m_nodes->end(); ++i_node_linked)
{
std::vector<NodeLink> l_links = i_node_linked->second->getNodeLinks();
for(auto i_node_link = l_links.begin(); i_node_link != l_links.end(); ++i_node_link)
{
if(i_node_link->OutputIdx == p_node_id || i_node_link->InputIdx == p_node_id)
{
i_node_linked->second->removeNodeLink(*i_node_link);
}
}
}
delete i_node->second;
m_nodes->erase(i_node);
m_num_active_nodes -= 1;
}
else
{
m_logger.AddLog("[ERROR] Can not delete node with given id: %i.\n", p_node_id);
}
}
void NodeManager::retrieveNodeFactoryList()
{
//Get the types of nodes we can create
m_node_factory_list = m_engine_controller->getEngineRunner()->getEngine()->getNodeManipulator().lock()->getNodeDefinitions();
}
void NodeManager::setActiveNodeData()
{
//Retrieve the data of only the active node and constantly update its data from the engine
}
void NodeManager::linkNodes(int p_output_id, int p_input_id, int p_output_slot, int p_input_slot)
{
if(p_input_id != p_output_id)
{
EditorNode * l_input_node = getNode(p_input_id);
EditorNode * l_output_node = getNode(p_output_id);
if(l_input_node != nullptr && l_output_node != nullptr)
{
//Check if this link already exists
if(linkAlreadyExists(p_output_id, p_input_id))
{
return;
}
//TODO: Is this necessary anymore?
//Remove old link if it exists
//removeLink(p_output_id, p_input_id);
//Set Link slot
int l_output_slot = p_output_slot;
int l_input_slot = p_input_slot;
//Check if the output slot and input slot is open
if(checkOutputSlotTaken(p_output_id, p_output_slot) || checkInputSlotTaken(p_input_id, p_input_slot))
{
findFreeLinkSlots(p_output_id, p_input_id, l_output_slot, l_input_slot);
}
//Add new link
NodeLink l_new_link(p_input_id, l_input_slot, p_output_id, l_output_slot);
l_output_node->addNodeLink(l_new_link);
l_input_node->addNodeLink(l_new_link);
//Only do this if all slots will be full after adding
//Add extra output / input slot
if(l_output_slot == l_output_node->getOutputs() - 1)
{
l_output_node->setOutputs(l_output_node->getOutputs() + 1);
}
if (l_input_slot == l_input_node->getInputs() - 1)
{
l_input_node->setIntputs(l_input_node->getInputs() + 1);
}
}
}
else
{
m_logger.AddLog("[ERROR] Can not link the same node ids.\n");
}
}
void NodeManager::removeLink(int p_output_id, int p_input_id)
{
EditorNode * l_output_node = getNode(p_output_id);
EditorNode * l_input_node = getNode(p_input_id);
if(l_output_node != nullptr && l_input_node != nullptr)
{
//input/output slot don't matter, only compare ids
NodeLink l_temp_link(p_input_id, 0, p_output_id, 0);
l_output_node->removeNodeLink(l_temp_link);
l_input_node->removeNodeLink(l_temp_link);
}
else
{
m_logger.AddLog("[ERROR] Can not remove link. One of the node ids is invalid.\n");
}
}
bool NodeManager::removeLinkFromOutputSlot(int p_output_id, int p_output_slot)
{
EditorNode * l_output_node = getNode(p_output_id);
if(l_output_node != nullptr)
{
std::vector<NodeLink> l_node_links = l_output_node->getNodeLinks();
for(auto i_link = l_node_links.begin(); i_link != l_node_links.end(); ++i_link)
{
if(i_link->OutputIdx == p_output_id && i_link->OutputSlot == p_output_slot)
{
int l_input_id = i_link->InputIdx;
EditorNode * l_input_node = getNode(l_input_id);
if(l_input_node != nullptr)
{
//input/output slot don't matter, only compare ids
NodeLink l_temp_link(l_input_id, 0, p_output_id, 0);
l_output_node->removeNodeLink(l_temp_link);
l_input_node->removeNodeLink(l_temp_link);
return true;
}
}
}
}
return false;
}
bool NodeManager::removeLinkFromInputSlot(int p_input_id, int p_input_slot)
{
EditorNode * l_input_node = getNode(p_input_id);
if (l_input_node != nullptr)
{
std::vector<NodeLink> l_node_links = l_input_node->getNodeLinks();
for (auto i_link = l_node_links.begin(); i_link != l_node_links.end(); ++i_link)
{
if (i_link->InputIdx == p_input_id && i_link->InputSlot == p_input_slot)
{
int l_output_id = i_link->OutputIdx;
EditorNode * l_output_node = getNode(l_output_id);
if (l_output_node != nullptr)
{
//input/output slot don't matter, only compare ids
NodeLink l_temp_link(p_input_id, 0, l_output_id, 0);
l_output_node->removeNodeLink(l_temp_link);
l_input_node->removeNodeLink(l_temp_link);
return true;
}
}
}
}
return false;
}
EditorNode* NodeManager::getNode(int p_node_id)
{
//Validate node with given id exists
auto i_node = m_nodes->find(p_node_id);
if (i_node != m_nodes->end())
{
return i_node->second;
}
m_logger.AddLog("[ERROR] Can not retrieve node with given id: %i.\n", p_node_id);
return nullptr;
}
bool NodeManager::linkAlreadyExists(int p_output_id, int p_input_id)
{
EditorNode * l_output_node = getNode(p_output_id);
if(l_output_node != nullptr)
{
std::vector<NodeLink> l_node_links = l_output_node->getNodeLinks();
for(size_t i = 0; i < l_node_links.size(); ++i)
{
if(l_node_links[i].InputIdx == p_input_id && l_node_links[i].OutputIdx == p_output_id)
{
return true;
}
}
}
return false;
}
void NodeManager::findFreeLinkSlots(int p_output_id, int p_input_id, int & p_output_slot, int & p_input_slot)
{
EditorNode * l_output_node = getNode(p_output_id);
EditorNode * l_input_node = getNode(p_input_id);
if(l_output_node != nullptr && l_input_node != nullptr)
{
//Find free output slot
std::vector<NodeLink> l_output_links = l_output_node->getNodeLinks();
int l_max_output_slot = -1;
int l_max_input_slot = -1;
for(size_t i = 0; i < l_output_links.size(); ++i)
{
if(l_output_links[i].OutputIdx == p_output_id)
{
if(l_max_output_slot < l_output_links[i].OutputSlot)
{
l_max_output_slot = l_output_links[i].OutputSlot;
}
}
}
p_output_slot = l_max_output_slot + 1;
//Find free output slot
std::vector<NodeLink> l_input_links = l_input_node->getNodeLinks();
for (size_t j = 0; j < l_input_links.size(); ++j)
{
if (l_input_links[j].InputIdx == p_input_id)
{
if (l_max_input_slot < l_input_links[j].InputSlot)
{
l_max_input_slot = l_input_links[j].InputSlot;
}
}
}
p_input_slot = l_max_input_slot + 1;
}
}
bool NodeManager::checkOutputSlotTaken(int p_output_id, int p_output_slot)
{
EditorNode * l_output_node = getNode(p_output_id);
if (l_output_node != nullptr)
{
//Find free output slot
std::vector<NodeLink> l_output_links = l_output_node->getNodeLinks();
for (size_t i = 0; i < l_output_links.size(); ++i)
{
if (l_output_links[i].OutputIdx == p_output_id)
{
if(l_output_links[i].OutputSlot == p_output_slot)
{
return true;
}
}
}
return false;
}
return true;
}
bool NodeManager::checkInputSlotTaken(int p_input_id, int p_input_slot)
{
EditorNode * l_input_node = getNode(p_input_id);
if (l_input_node != nullptr)
{
//Find free input slot
std::vector<NodeLink> l_input_links = l_input_node->getNodeLinks();
for (size_t i = 0; i < l_input_links.size(); ++i)
{
if (l_input_links[i].InputIdx == p_input_id)
{
if (l_input_links[i].InputSlot == p_input_slot)
{
return true;
}
}
}
return false;
}
return true;
}
rapidjson::Value nodeLinkToStream(NodeLink p_node_link, rapidjson::Document::AllocatorType& p_allocator)
{
rapidjson::Value l_result(rapidjson::kArrayType);
rapidjson::Value l_output_id;
l_output_id.SetInt(p_node_link.OutputIdx);
rapidjson::Value l_input_id;
l_input_id.SetInt(p_node_link.InputIdx);
rapidjson::Value l_output_slot;
l_output_slot.SetInt(p_node_link.OutputSlot);
rapidjson::Value l_input_slot;
l_input_slot.SetInt(p_node_link.InputSlot);
l_result.PushBack(l_input_id, p_allocator);
l_result.PushBack(l_input_slot, p_allocator);
l_result.PushBack(l_output_id, p_allocator);
l_result.PushBack(l_output_slot, p_allocator);
return l_result;
}
//the thread has exited with code 0xc000007b
//http://rapidjson.org/md_doc_tutorial.html
bool NodeManager::serializeNodes(const std::string & p_path, const std::string & p_graph_name)
{
if(!m_nodes->empty())
{
rapidjson::Document l_document;
l_document.SetObject();
rapidjson::Document::AllocatorType & l_allocator = l_document.GetAllocator();
rapidjson::Value l_graph(rapidjson::kArrayType);
for(auto i_node = m_nodes->begin(); i_node != m_nodes->end(); ++i_node)
{
const char* EditorNodeName = i_node->second->getName().c_str();
rapidjson::Document l_node;
l_node.SetObject();
//Type Name
rapidjson::Value l_type_name;
l_type_name.SetString(i_node->second->getTypeName().c_str(), l_allocator);
l_node.AddMember("type name", l_type_name, l_allocator);
//Class Name
rapidjson::Value l_class_name;
l_class_name.SetString(i_node->second->getClassName().c_str(), l_allocator);
l_node.AddMember("class name", l_class_name, l_allocator);
//Name
rapidjson::Value l_name;
l_name.SetString(i_node->second->getName().c_str(), l_allocator);
l_node.AddMember("name", l_name, l_allocator);
//Id
rapidjson::Value l_id;
l_id.SetInt(i_node->second->getId());
l_node.AddMember("id", l_id, l_allocator);
//Position
ImVec2 l_node_position = i_node->second->getPosition();
rapidjson::Value l_position(rapidjson::kArrayType);
l_position.PushBack(l_node_position.x, l_allocator);
l_position.PushBack(l_node_position.y, l_allocator);
l_node.AddMember("position", l_position, l_allocator);
//Create each node link (output only)
std::vector<NodeLink> l_node_links = i_node->second->getNodeLinks();
rapidjson::Value l_node_output_links_array(rapidjson::kArrayType);
rapidjson::Value l_node_input_links_array(rapidjson::kArrayType);
for(auto i_node_link = l_node_links.begin(); i_node_link != l_node_links.end(); ++i_node_link)
{
if(i_node_link->OutputIdx == i_node->second->getId())
{
l_node_output_links_array.PushBack(nodeLinkToStream(*i_node_link, l_allocator), l_allocator);
}
else if(i_node_link->InputIdx == i_node->second->getId())
{
l_node_input_links_array.PushBack(nodeLinkToStream(*i_node_link, l_allocator), l_allocator);
}
}
l_node.AddMember("node output links", l_node_output_links_array, l_allocator);
l_node.AddMember("node input links", l_node_input_links_array, l_allocator);
// add on specialized data
auto interpreter = BehaviorInterpreter::GetInstance();
//auto visitor = BehaviorVisitor::GetInstance();
if (interpreter.IsSpecialized(i_node->second->getName()))
{
interpreter.FillJSON( i_node->second->m_render_data.member("Node Render Data"), i_node->second->getName(), l_node);
}
// end of specialized data
l_graph.PushBack(l_node, l_allocator);
}
l_document.AddMember("graph", l_graph, l_allocator);
rapidjson::StringBuffer l_buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(l_buffer);
l_document.Accept(writer);
//Combine path
std::string p_file = p_path + "/Assets/graphs/" + p_graph_name;
//Create file
std::ofstream l_file(p_file.c_str());
if(l_file.is_open())
{
l_file << l_buffer.GetString();
l_file.close();
m_logger.AddLog("[NOTICE] Successfully saved graph: %s. \n", p_file.c_str());
return true;
}
else
{
m_logger.AddLog("[ERROR] Failed to create file: %s.\n", p_file.c_str());
return false;
}
}
return true;
}
void NodeManager::readFromFile(const std::string & p_file_name)
{
std::ifstream l_if_stream(p_file_name);
if(l_if_stream.is_open())
{
std::string file_as_string((std::istreambuf_iterator<char>(l_if_stream)), std::istreambuf_iterator<char>());
rapidjson::Document l_document;
l_document.Parse(file_as_string.c_str());
if(l_document.HasMember("graph"))
{
const rapidjson::Value & l_graph = l_document["graph"];
for(rapidjson::SizeType i = 0; i < l_graph.Size(); ++i)
{
const rapidjson::Value & l_node = l_graph[i];
if(l_node.IsObject())
{
std::string l_type_name = "";
std::string l_class_name = "";
std::string l_name = "";
int l_id = 0;
ImVec2 l_position(0.0f, 0.0f);
//Type Name
if (l_node.HasMember("type name"))
{
l_type_name = l_node["type name"].GetString();
}
//Class Name
if (l_node.HasMember("class name"))
{
l_class_name = l_node["class name"].GetString();
}
//Name
if(l_node.HasMember("name"))
{
l_name = l_node["name"].GetString();
}
//Id
if(l_node.HasMember("id"))
{
l_id = l_node["id"].GetInt();
}
//Position
if(l_node.HasMember("position"))
{
l_position.x = l_node["position"][0].GetFloat();
l_position.y = l_node["position"][1].GetFloat();
}
EditorNode * l_new_node;
if (BehaviorInterpreter::GetInstance().IsSpecialized(l_name))
{
l_new_node = createEditorNodeJSON(l_type_name,
std::pair<std::string, std::string>(l_class_name, l_name), l_node);
}
else
{
l_new_node = createEditorNodeFromScratch(l_type_name,
std::pair<std::string, std::string>(l_class_name, l_name));
}
//Failed to create node
if(l_new_node != nullptr)
{
if (l_node.HasMember("node output links"))
{
const rapidjson::Value & l_node_output_links = l_node["node output links"];
for (size_t j = 0; j < l_node_output_links.Size(); ++j)
{
NodeLink l_new_link(l_node_output_links[j][0].GetInt(), l_node_output_links[j][1].GetInt(), l_node_output_links[j][2].GetInt(), l_node_output_links[j][3].GetInt());
l_new_node->addNodeLink(l_new_link);
}
}
if(l_node.HasMember("node input links"))
{
const rapidjson::Value & l_node_input_links = l_node["node input links"];
for (size_t j = 0; j < l_node_input_links.Size(); ++j)
{
NodeLink l_new_link(l_node_input_links[j][0].GetInt(), l_node_input_links[j][1].GetInt(), l_node_input_links[j][2].GetInt(), l_node_input_links[j][3].GetInt());
l_new_node->addNodeLink(l_new_link);
}
}
//For old graphs that haven't followed the new saving format
if (l_node.HasMember("node links"))
{
const rapidjson::Value & l_node_links = l_node["node links"];
for (size_t j = 0; j < l_node_links.Size(); ++j)
{
NodeLink l_new_link(l_node_links[j][0].GetInt(), l_node_links[j][1].GetInt(), l_node_links[j][2].GetInt(), l_node_links[j][3].GetInt());
l_new_node->addNodeLink(l_new_link);
}
}
addNode(l_new_node, l_id);
l_new_node->setPosition(l_position);
}
}
}
m_logger.AddLog("[NOTICE] Successfully read graph: %s. \n", p_file_name.c_str());
}
l_if_stream.close();
}
else
{
m_logger.AddLog("[ERROR] Failed to open file to read: %s. \n", p_file_name.c_str());
}
}
int NodeManager::createUniqueID() const
{
int uniqueID = 0;
while (this->m_nodes->find(uniqueID) != m_nodes->end())
{
uniqueID++;
}
return uniqueID;
}
bool NodeManager::validateGraph()
{
int l_num_roots = 0;
//Loop over each node
for(auto i_node = m_nodes->begin(); i_node != m_nodes->end(); ++i_node)
{
//TODO: Call the validate function
//auto l_result = i_node->second->validate();
//if(!l_result.first)
//{
// m_logger.AddLog("[ERROR] %s.\n", l_result.second.c_str());
// return false;
//}
//Loop over all the node links
std::vector<NodeLink> l_node_links = i_node->second->getNodeLinks();
int l_num_input_links = 0;
for(auto i_link = l_node_links.begin(); i_link != l_node_links.end(); ++i_link)
{
//This node is an input node (so it has a parent)
if(i_node->first == i_link->InputIdx)
{
l_num_input_links += 1;
}
}
//This node has no inputs so it is a root
if(l_num_input_links == 0)
{
l_num_roots += 1;
}
}
if(l_num_roots > 1)
{
m_logger.AddLog("[ERROR] Graph can not have more than 1 root node.\n");
return false;
}
m_logger.AddLog("[NOTICE] Graph validated successfully.\n");
return true;
}
void NodeManager::setEditorNodesScale(float p_scalar, float p_difference)
{
for (auto i_node = m_nodes->begin(); i_node != m_nodes->end(); ++i_node)
{
i_node->second->setZoomScale(p_scalar);
//Change position based off of new scale
ImVec2 l_new_position = i_node->second->getPosition();
//l_new_position.x += l_new_position.x * (p_difference);
//l_new_position.y += l_new_position.y * (p_difference);
ImVec2 l_scale = i_node->second->getScaleAfterZoom();
l_new_position.x += (l_scale.x / 2.0f) * (p_difference);
l_new_position.y += (l_scale.y / 2.0f) * (p_difference);
i_node->second->setPosition(l_new_position);
}
}
| [
"[email protected]"
] | |
ae758790f3d37caa2b35ee583e9e1915b9ec0599 | a1dd3b3da0deb35af6ce415690aad0e3d3088b08 | /Frojengine/CameraControl.cpp | 4f3c82a0926a35ac97d0f78dbfdb0a928e3215f3 | [] | no_license | Frojer/Frojengine | 1afc867a63363413875b25c0950f6bf130fc8e53 | 6be84e9effb23e20b1ad5671133c4421c32eba59 | refs/heads/master | 2021-01-19T22:10:24.369313 | 2018-09-13T12:34:19 | 2018-09-13T12:34:19 | 105,982,062 | 3 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,954 | cpp | #include "CameraControl.h"
#include "FJMath.h"
void CameraControl::Initialize()
{
}
void CameraControl::Update()
{
CObject* pObj = GetMyObject();
// À̵¿
if (IsKeyDown(VK_UP)) pObj->m_pTransform->SetPositionLocal(pObj->m_pTransform->GetPositionLocal() + (pObj->m_pTransform->GetLookAt() * 10.0f * FJSystemEngine::GetInstance()->m_fDeltaTime));
if (IsKeyDown(VK_DOWN)) pObj->m_pTransform->SetPositionLocal(pObj->m_pTransform->GetPositionLocal() + (pObj->m_pTransform->GetLookAt() * -10.0f * FJSystemEngine::GetInstance()->m_fDeltaTime));
if (IsKeyDown(VK_LEFT)) pObj->m_pTransform->SetPositionLocal(pObj->m_pTransform->GetPositionLocal() + (pObj->m_pTransform->GetRightVector() * -10.0f * FJSystemEngine::GetInstance()->m_fDeltaTime));
if (IsKeyDown(VK_RIGHT)) pObj->m_pTransform->SetPositionLocal(pObj->m_pTransform->GetPositionLocal() + (pObj->m_pTransform->GetRightVector() * 10.0f * FJSystemEngine::GetInstance()->m_fDeltaTime));
// ȸÀü
if (IsKeyDown(VK_NUMPAD8)) pObj->m_pTransform->Rotate(VECTOR3(-45.0f, 0.0f, 0.0f) * FJSystemEngine::GetInstance()->m_fDeltaTime);
if (IsKeyDown(VK_NUMPAD5)) pObj->m_pTransform->Rotate(VECTOR3(45.0f, 0.0f, 0.0f) * FJSystemEngine::GetInstance()->m_fDeltaTime);
if (IsKeyDown(VK_NUMPAD4)) pObj->m_pTransform->Rotate(VECTOR3(0.0f, -45.0f, 0.0f) * FJSystemEngine::GetInstance()->m_fDeltaTime);
if (IsKeyDown(VK_NUMPAD6)) pObj->m_pTransform->Rotate(VECTOR3(0.0f, +45.0f, 0.0f) * FJSystemEngine::GetInstance()->m_fDeltaTime);
//if (IsKeyDown('W')) pObj->m_pTransform->m_vRot.x -= XM_PI * 0.25f * FJSystemEngine::GetInstance()->m_fDeltaTime;
//if (IsKeyDown('S')) pObj->m_pTransform->m_vRot.x += XM_PI * 0.25f * FJSystemEngine::GetInstance()->m_fDeltaTime;
//if (IsKeyDown('A')) pObj->m_pTransform->m_vRot.y -= XM_PI * 0.25f * FJSystemEngine::GetInstance()->m_fDeltaTime;
//if (IsKeyDown('D')) pObj->m_pTransform->m_vRot.y += XM_PI * 0.25f * FJSystemEngine::GetInstance()->m_fDeltaTime;
} | [
"[email protected]"
] | |
309a8df232425f1645203ce714145d5f47eacdfd | 2e10a55bcc27421c2ce00bac67d62ca3ae7a43be | /gcommon/source/gguivisitor.h | b4df37eaf7973f1d291fa50a7c6cecf38c6ef61b | [
"Unlicense"
] | permissive | DavidCoenFish/ancient-code-0 | 2f72b8e20406b9877daa032f9e9fb8343da62340 | 243fb47b9302a77f9b9392b6e3f90bba2ef3c228 | refs/heads/master | 2020-03-21T10:18:30.613722 | 2018-06-24T01:18:30 | 2018-06-24T01:18:30 | 138,444,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,207 | h | //
// GGuiVisitor.h
//
// Created by David Coen on 2011 04 14
// Copyright 2010 Pleasure seeking morons. All rights reserved.
//
#ifndef _GGuiVisitor_h_
#define _GGuiVisitor_h_
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <vector>
#include "GGui.h"
class GGuiManager;
class GRender;
class GGuiNode;
class GGuiVisitorNodeName : public boost::noncopyable
{
//typedef
private:
typedef boost::shared_ptr<GGuiNode> TPointerGuiNode;
typedef boost::weak_ptr<GGuiNode> TWeakGuiNode;
//public static methods
public:
static TWeakGuiNode FindNode(
GGui& inout_Gui,
const std::string& in_nodeName
);
//constructor
private:
GGuiVisitorNodeName(
TWeakGuiNode& inout_node,
const std::string& in_nodeName
);
~GGuiVisitorNodeName();
//public methods
public:
void QuerySubmitNode(
TPointerGuiNode& inout_node
);
//private members
private:
TWeakGuiNode& mNode;
const std::string mNodeName;
};
//gather array of components of type
template <typename IN_TYPE>
class GGuiVisitor : public boost::noncopyable
{
//typedef
private:
typedef boost::shared_ptr<GGuiNode> TPointerGuiNode;
typedef boost::shared_ptr<IN_TYPE> TPointerType;
typedef boost::weak_ptr<IN_TYPE> TWeakType;
typedef std::vector<TWeakType> TArrayWeakType;
//public static methods
public:
static void Run(
GGui& inout_Gui,
TArrayWeakType& out_arrayType
)
{
GGuiVisitor visitor(out_arrayType);
inout_Gui.QueryAll(visitor, IN_TYPE::GetComponentFlag());
return;
}
//constructor
private:
GGuiVisitor(TArrayWeakType& out_arrayType)
: mArrayType(out_arrayType)
{
return;
}
~GGuiVisitor()
{
return;
}
//public methods
public:
//contract with GSceneNode query
void QuerySubmitNode(
TPointerGuiNode& inout_node
)
{
GGuiNode& node = *inout_node;
const int componentCount = node.GetComponentCount();
for (int index = 0; index < componentCount; ++index)
{
TPointerType pComponent = node.GetComponentPointer<IN_TYPE>(index);
if (!pComponent)
{
continue;
}
TWeakType weakComponent(pComponent);
mArrayType.push_back(weakComponent);
}
return;
}
private:
TArrayWeakType& mArrayType;
};
#endif | [
"[email protected]"
] | |
4431ff5497a19e456f82f403abc1d4734e132e79 | 3670f2ca6f5609e14cce8c31cb1348052d0b6358 | /xacro/ros_comm/rosbag/src/record.cpp | 2632f4890d76cdba2fa9f11579b4c43f4ce07698 | [] | no_license | jincheng-ai/ros-melodic-python3-opencv4 | b0f4d3860ab7ae3d683ade8aa03e74341eff7fcf | 47c74188560c2274b8304647722d0c9763299a4b | refs/heads/main | 2023-05-28T17:37:34.345164 | 2021-06-17T09:59:25 | 2021-06-17T09:59:25 | 377,856,153 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,923 | cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
********************************************************************/
#include "rosbag/recorder.h"
#include "rosbag/exceptions.h"
#include "boost/program_options.hpp"
#include <signal.h>
#include <string>
#include <sstream>
namespace po = boost::program_options;
//! Parse the command-line arguments for recorder options
rosbag::RecorderOptions parseOptions(int argc, char** argv) {
rosbag::RecorderOptions opts;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("all,a", "record all topics")
("regex,e", "match topics using regular expressions")
("exclude,x", po::value<std::string>(), "exclude topics matching regular expressions")
("quiet,q", "suppress console output")
("publish,p", "Publish a msg when the record begin")
("output-prefix,o", po::value<std::string>(), "prepend PREFIX to beginning of bag name")
("output-name,O", po::value<std::string>(), "record bagnamed NAME.bag")
("buffsize,b", po::value<int>()->default_value(256), "Use an internal buffer of SIZE MB (Default: 256)")
("chunksize", po::value<int>()->default_value(768), "Set chunk size of message data, in KB (Default: 768. Advanced)")
("limit,l", po::value<int>()->default_value(0), "Only record NUM messages on each topic")
("min-space,L", po::value<std::string>()->default_value("1G"), "Minimum allowed space on recording device (use G,M,k multipliers)")
("bz2,j", "use BZ2 compression")
("lz4", "use LZ4 compression")
("split", po::value<int>()->implicit_value(0), "Split the bag file and continue recording when maximum size or maximum duration reached.")
("max-splits", po::value<int>(), "Keep a maximum of N bag files, when reaching the maximum erase the oldest one to keep a constant number of files.")
("topic", po::value< std::vector<std::string> >(), "topic to record")
("size", po::value<uint64_t>(), "The maximum size of the bag to record in MB.")
("duration", po::value<std::string>(), "Record a bag of maximum duration in seconds, unless 'm', or 'h' is appended.")
("node", po::value<std::string>(), "Record all topics subscribed to by a specific node.")
("tcpnodelay", "Use the TCP_NODELAY transport hint when subscribing to topics.")
("udp", "Use the UDP transport hint when subscribing to topics.");
po::positional_options_description p;
p.add("topic", -1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
} catch (const boost::program_options::invalid_command_line_syntax& e)
{
throw ros::Exception(e.what());
} catch (const boost::program_options::unknown_option& e)
{
throw ros::Exception(e.what());
}
if (vm.count("help")) {
std::cout << desc << std::endl;
exit(0);
}
if (vm.count("all"))
opts.record_all = true;
if (vm.count("regex"))
opts.regex = true;
if (vm.count("exclude"))
{
opts.do_exclude = true;
opts.exclude_regex = vm["exclude"].as<std::string>();
}
if (vm.count("quiet"))
opts.quiet = true;
if (vm.count("publish"))
opts.publish = true;
if (vm.count("output-prefix"))
{
opts.prefix = vm["output-prefix"].as<std::string>();
opts.append_date = true;
}
if (vm.count("output-name"))
{
opts.prefix = vm["output-name"].as<std::string>();
opts.append_date = false;
}
if (vm.count("split"))
{
opts.split = true;
int S = vm["split"].as<int>();
if (S != 0)
{
ROS_WARN("Use of \"--split <MAX_SIZE>\" has been deprecated. Please use --split --size <MAX_SIZE> or --split --duration <MAX_DURATION>");
if (S < 0)
throw ros::Exception("Split size must be 0 or positive");
opts.max_size = 1048576 * static_cast<uint64_t>(S);
}
}
if(vm.count("max-splits"))
{
if(!opts.split)
{
ROS_WARN("--max-splits is ignored without --split");
}
else
{
opts.max_splits = vm["max-splits"].as<int>();
}
}
if (vm.count("buffsize"))
{
int m = vm["buffsize"].as<int>();
if (m < 0)
throw ros::Exception("Buffer size must be 0 or positive");
opts.buffer_size = 1048576 * m;
}
if (vm.count("chunksize"))
{
int chnk_sz = vm["chunksize"].as<int>();
if (chnk_sz < 0)
throw ros::Exception("Chunk size must be 0 or positive");
opts.chunk_size = 1024 * chnk_sz;
}
if (vm.count("limit"))
{
opts.limit = vm["limit"].as<int>();
}
if (vm.count("min-space"))
{
std::string ms = vm["min-space"].as<std::string>();
long long int value = 1073741824ull;
char mul = 0;
// Sane default values, just in case
opts.min_space_str = "1G";
opts.min_space = value;
if (sscanf(ms.c_str(), " %lld%c", &value, &mul) > 0) {
opts.min_space_str = ms;
switch (mul) {
case 'G':
case 'g':
opts.min_space = value * 1073741824ull;
break;
case 'M':
case 'm':
opts.min_space = value * 1048576ull;
break;
case 'K':
case 'k':
opts.min_space = value * 1024ull;
break;
default:
opts.min_space = value;
break;
}
}
ROS_DEBUG("Rosbag using minimum space of %lld bytes, or %s", opts.min_space, opts.min_space_str.c_str());
}
if (vm.count("bz2") && vm.count("lz4"))
{
throw ros::Exception("Can only use one type of compression");
}
if (vm.count("bz2"))
{
opts.compression = rosbag::compression::BZ2;
}
if (vm.count("lz4"))
{
opts.compression = rosbag::compression::LZ4;
}
if (vm.count("duration"))
{
std::string duration_str = vm["duration"].as<std::string>();
double duration;
double multiplier = 1.0;
std::string unit("");
std::istringstream iss(duration_str);
if ((iss >> duration).fail())
throw ros::Exception("Duration must start with a floating point number.");
if ( (!iss.eof() && ((iss >> unit).fail())) )
{
throw ros::Exception("Duration unit must be s, m, or h");
}
if (unit == std::string(""))
multiplier = 1.0;
else if (unit == std::string("s"))
multiplier = 1.0;
else if (unit == std::string("m"))
multiplier = 60.0;
else if (unit == std::string("h"))
multiplier = 3600.0;
else
throw ros::Exception("Duration unit must be s, m, or h");
opts.max_duration = ros::Duration(duration * multiplier);
if (opts.max_duration <= ros::Duration(0))
throw ros::Exception("Duration must be positive.");
}
if (vm.count("size"))
{
opts.max_size = vm["size"].as<uint64_t>() * 1048576;
if (opts.max_size <= 0)
throw ros::Exception("Split size must be 0 or positive");
}
if (vm.count("node"))
{
opts.node = vm["node"].as<std::string>();
std::cout << "Recording from: " << opts.node << std::endl;
}
if (vm.count("tcpnodelay"))
{
opts.transport_hints.tcpNoDelay();
}
if (vm.count("udp"))
{
opts.transport_hints.udp();
}
// Every non-option argument is assumed to be a topic
if (vm.count("topic"))
{
std::vector<std::string> bags = vm["topic"].as< std::vector<std::string> >();
std::sort(bags.begin(), bags.end());
bags.erase(std::unique(bags.begin(), bags.end()), bags.end());
for (std::vector<std::string>::iterator i = bags.begin();
i != bags.end();
i++)
opts.topics.push_back(*i);
}
// check that argument combinations make sense
if(opts.exclude_regex.size() > 0 &&
!(opts.record_all || opts.regex)) {
fprintf(stderr, "Warning: Exclusion regex given, but no topics to subscribe to.\n"
"Adding implicit 'record all'.");
opts.record_all = true;
}
return opts;
}
/**
* Handle SIGTERM to allow the recorder to cleanup by requesting a shutdown.
* \param signal
*/
void signal_handler(int signal)
{
(void) signal;
ros::requestShutdown();
}
int main(int argc, char** argv) {
ros::init(argc, argv, "record", ros::init_options::AnonymousName);
// handle SIGTERM signals
signal(SIGTERM, signal_handler);
// Parse the command-line options
rosbag::RecorderOptions opts;
try {
opts = parseOptions(argc, argv);
}
catch (const ros::Exception& ex) {
ROS_ERROR("Error reading options: %s", ex.what());
return 1;
}
catch(const boost::regex_error& ex) {
ROS_ERROR("Error reading options: %s\n", ex.what());
return 1;
}
// Run the recorder
rosbag::Recorder recorder(opts);
int result = recorder.run();
return result;
}
| [
"[email protected]"
] | |
ceb285b6dd49f42f56cec67482045b91aefa9f57 | 8aa5cd4de3323f6f3518834406ed51a27eed2c31 | /src/meta/noise.conv.h | 44cd7413e9bcf9004bdfcbe870403f1ae9157118 | [
"Zlib"
] | permissive | raptoravis/two | c07b0583ee643c2375323a74802850c3449ac610 | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | refs/heads/master | 2020-07-24T12:32:48.848094 | 2019-09-12T00:51:43 | 2019-09-12T00:51:43 | 207,928,784 | 0 | 0 | Zlib | 2019-09-12T00:09:58 | 2019-09-12T00:09:58 | null | UTF-8 | C++ | false | false | 1,932 | h | #pragma once
#include <noise/Types.h>
#if !defined TWO_MODULES || defined TWO_TYPE_LIB
#include <refl/Meta.h>
#include <refl/Enum.h>
#include <infra/StringOps.h>
#endif
namespace two
{
export_ template <> inline void to_value(const string& str, two::Noise::NoiseType& val) { val = two::Noise::NoiseType(enu<two::Noise::NoiseType>().value(str.c_str())); };
export_ template <> inline void to_string(const two::Noise::NoiseType& val, string& str) { str = enu<two::Noise::NoiseType>().name(uint32_t(val)); };
export_ template <> inline void to_value(const string& str, two::Noise::Interp& val) { val = two::Noise::Interp(enu<two::Noise::Interp>().value(str.c_str())); };
export_ template <> inline void to_string(const two::Noise::Interp& val, string& str) { str = enu<two::Noise::Interp>().name(uint32_t(val)); };
export_ template <> inline void to_value(const string& str, two::Noise::FractalType& val) { val = two::Noise::FractalType(enu<two::Noise::FractalType>().value(str.c_str())); };
export_ template <> inline void to_string(const two::Noise::FractalType& val, string& str) { str = enu<two::Noise::FractalType>().name(uint32_t(val)); };
export_ template <> inline void to_value(const string& str, two::Noise::CellularDistanceFunction& val) { val = two::Noise::CellularDistanceFunction(enu<two::Noise::CellularDistanceFunction>().value(str.c_str())); };
export_ template <> inline void to_string(const two::Noise::CellularDistanceFunction& val, string& str) { str = enu<two::Noise::CellularDistanceFunction>().name(uint32_t(val)); };
export_ template <> inline void to_value(const string& str, two::Noise::CellularReturnType& val) { val = two::Noise::CellularReturnType(enu<two::Noise::CellularReturnType>().value(str.c_str())); };
export_ template <> inline void to_string(const two::Noise::CellularReturnType& val, string& str) { str = enu<two::Noise::CellularReturnType>().name(uint32_t(val)); };
}
| [
"[email protected]"
] | |
55a8af6a6096efc976032696bc2b82ad477304e9 | 14ffe62f3b9bdd863de286648f423df9d267e456 | /Algorithms/Optimization/gradient_descent.cpp | 9e0bc16891f66139530baadb706897aafaee90f0 | [] | no_license | kaissie/til | 56ccdb29ee0dbc3f10024046d595ecbacbec9b91 | 6e884e9ea522868af53ccdd3cd4ac2a0eb65ff7e | refs/heads/master | 2020-09-01T06:17:21.255132 | 2020-04-18T14:22:02 | 2020-04-18T14:22:02 | 218,897,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 863 | cpp | #include <iostream>
#include <cmath>
#include <random>
long long int getRandom(long long int s, long long int e){
std::random_device seed_gen;
std::mt19937 engine(seed_gen());
std::uniform_int_distribution<> dist(s, e);
return dist(engine);
}
double f(double x, double y) {
return x*x + y*y + x*y - 2*x;
}
double dfx(double x, double y) {
return 2*x + y - 2;
}
double dfy(double x, double y) {
return 2*y + x;
}
int main(int argc, char const *argv[]) {
double alpha = 0.0001;
double x = 1.0;
double y = 1.0;
double eps = 1.e-10;
std::cout << "Value of f(x, y) at Step 0 is " << f(x, y) << '\n';
while (f(x,y) > eps) {
x = x - alpha * dfx (x, y);
y = y - alpha * dfy (x, y);
}
std::cout << "Value of f(x, y) is " << f(x, y) << '\n';
std::cout << "Result (x, y) = " <<"(" << x << ", " << y << ")" << '\n';
return 0;
}
| [
"[email protected]"
] | |
9ca37e7bbcbe5e1ced0312aa394985b947dd94f7 | 6f9a3105e1170c2c70c6c2a14d5d16ec8135ce76 | /frameworks/runtime-src/Classes/reader/animation/Bezier.h | bdce38b3cf5d38320d4e82f810364bb636919b07 | [
"MIT"
] | permissive | Kuovane/cocos2dx-swf | c8b1304d391d1954c76595a48cd2c3ef0af846a9 | 72e4c8ee6bb0f4ab601deba5ab760a2b716f838c | refs/heads/master | 2022-12-16T10:58:01.644871 | 2020-09-08T09:39:52 | 2020-09-08T09:39:52 | 274,286,916 | 0 | 0 | MIT | 2020-06-23T02:11:49 | 2020-06-23T02:11:49 | null | UTF-8 | C++ | false | false | 1,490 | h | /****************************************************************************
Copyright (c) 2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "Macros.h"
#include <vector>
NS_CCR_BEGIN
namespace Bazier
{
float computeBezier(const std::vector<float>& controlPoints, float ratio);
}
NS_CCR_END
| [
"[email protected]"
] | |
934bce65d4383b969f7fd61672331848390aafc4 | 700f02da203f3a267b6a34095df56cf521981883 | /TaskMgrCore/settinghlp.cpp | dcf0e0ac070ffff80796f9c94aa890d4f4af2a98 | [
"MIT"
] | permissive | fengjixuchui/PCMgr | 04d747e14f869062a19eb3c8c3b958b2746c90b6 | 00a576f33221baec273a9f543c8429daa1fe605f | refs/heads/master | 2021-07-14T22:15:35.272843 | 2021-06-23T08:41:34 | 2021-06-23T08:41:34 | 211,074,547 | 0 | 1 | null | 2021-06-23T08:41:35 | 2019-09-26T11:37:52 | null | UTF-8 | C++ | false | false | 753 | cpp | #include "stdafx.h"
#include "settinghlp.h"
#include "mapphlp.h"
#include "PathHelper.h"
#include "StringHlp.h"
WCHAR iniPath[MAX_PATH];
M_CAPI(LPWSTR) M_CFG_GetCfgFilePath() {
return iniPath;
}
M_CAPI(BOOL) M_CFG_GetConfigBOOL(LPWSTR configkey, LPWSTR configSection, BOOL defaultValue)
{
BOOL rs = defaultValue;
WCHAR temp[32];
if (GetPrivateProfileString(configSection, configkey, defaultValue ? L"TRUE" : L"FALSE", temp, 32, iniPath) > 0)
defaultValue = StrEqual(temp, L"1") || StrEqual(temp, L"TRUE") || StrEqual(temp, L"True");
return defaultValue;
}
M_CAPI(BOOL) M_CFG_SetConfigBOOL(LPWSTR configkey, LPWSTR configSection, BOOL value)
{
return WritePrivateProfileStringW(configSection, configkey, value ? L"TRUE" : L"FALSE", iniPath);
} | [
"[email protected]"
] | |
694dcc167dc7c80b47563de5f018cd8279f836ee | 3f07e67d521968f84927cd41418f0ce9bdf9433d | /common/source/IllustratorSDK.cpp | 61e75335de8fb941ca5f56d6a22409055961fe59 | [] | no_license | azer89/IllustratorSimplePlugin | 825b8e53c484e2e9e82d8a1cbb0e64443dac673a | a2a24ac9da6f2c1fd7f84bc7c1e55ab8463386ab | refs/heads/master | 2021-01-10T13:22:01.087479 | 2016-03-26T11:39:28 | 2016-03-26T11:39:28 | 51,016,320 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 731 | cpp | //========================================================================================
//
// $File: //ai/cs6/devtech/sdk/public/samplecode/common/source/IllustratorSDK.cpp $
//
// $Revision: #2 $
//
// Copyright 1987 Adobe Systems Incorporated. All rights reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
// with the terms of the Adobe license agreement accompanying it. If you have received
// this file from a source other than Adobe, then your use, modification, or
// distribution of it requires the prior written permission of Adobe.
//
//========================================================================================
#include "IllustratorSDK.h"
| [
"[email protected]"
] | |
3fe8fe4bf36f9833706afcef2068c1983566979d | 9e6b99c75369e765dd65bab48d0c28101f8faab1 | /0_cpp101/0_basics/7_4_pointer_arr_func.cpp | d4a02fda872e707ff63223b9d5f2845cac3dbd15 | [] | no_license | rsun07/Cpp_learning | dc9315a87682c075982c4a789763e2cb3dc0bbd4 | 4baff171ffccdae1ae073e71bbf9ced6effcfcac | refs/heads/main | 2023-05-14T12:51:33.501795 | 2021-06-11T02:44:07 | 2021-06-11T02:44:07 | 374,813,867 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,593 | cpp | #include<iostream>
using namespace std;
void print(int a, int b) {
cout << "a = " << a << ", b = " << b << endl;
}
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
void swap(int * pa, int * pb) {
int temp = *pa;
*pa = *pb;
*pb = temp;
}
// int* arr is the same as int arr[].
// it's the pointer that point to the first element in the array
void printArray(int* arr, int len) {
cout << endl;
// warning: sizeof on array function parameter will return size of 'int *' instead of 'int []' [-Wsizeof-array-argument]
cout << "printArray sizeof(arr) = " << sizeof(arr) << endl;
for (int i = 0; i < len; i++) {
cout << arr[i] << ",";
}
cout << endl;
cout << "*arr = " << * arr << " , arr = " << arr << endl;
cout << endl;
// stop at end indicator
for (int i = 0; i < len; i++, arr++) {
cout << *arr << ",";
}
cout << endl;
// the following doesn't work
// while(arr != '\0')
// while(arr != NULL)
// because we moved pointer to later
cout << "*arr = " << * arr << " , arr = " << arr << endl;
// move 5 element
cout << "*(----------arr) = " << *(------------arr) << " , arr = " << arr << endl;
cout << endl;
}
int main() {
int a = 1;
int b = 2;
// pass as value, method swap will create new a and b varialbes using copy constructor
swap(a, b);
print(a, b);
// pass as reference, same a and b passed into method swap
swap(&a, &b);
print(a, b);
int arr[10] = {1,3,5,7,9};
int len = sizeof(arr) / sizeof(arr[0]);
cout << "\n" << "main sizeof(arr) = " << sizeof(arr) << endl;
printArray(arr, len);
system("pause");
return 0;
} | [
"[email protected]"
] | |
ebfc04657ac42f11030cb53d2a94a382ce7b7818 | f79dec3c4033ca3cbb55d8a51a748cc7b8b6fbab | /mail/thunderbird24/patches/patch-ipc_chromium_src_base_platform__thread__posix.cc | 39e66d26d8f63147ef12b213a9d68383b8e931af | [] | no_license | jsonn/pkgsrc | fb34c4a6a2d350e8e415f3c4955d4989fcd86881 | c1514b5f4a3726d90e30aa16b0c209adbc276d17 | refs/heads/trunk | 2021-01-24T09:10:01.038867 | 2017-07-07T15:49:43 | 2017-07-07T15:49:43 | 2,095,004 | 106 | 47 | null | 2016-09-19T09:26:01 | 2011-07-23T23:49:04 | Makefile | UTF-8 | C++ | false | false | 866 | cc | $NetBSD: patch-ipc_chromium_src_base_platform__thread__posix.cc,v 1.1 2014/07/27 05:36:07 ryoon Exp $
--- mozilla/ipc/chromium/src/base/platform_thread_posix.cc.orig 2013-10-23 22:09:00.000000000 +0000
+++ mozilla/ipc/chromium/src/base/platform_thread_posix.cc
@@ -10,7 +10,9 @@
#if defined(OS_MACOSX)
#include <mach/mach.h>
#elif defined(OS_NETBSD)
+_Pragma("GCC visibility push(default)")
#include <lwp.h>
+_Pragma("GCC visibility pop")
#elif defined(OS_LINUX)
#include <sys/syscall.h>
#include <sys/prctl.h>
@@ -110,7 +112,8 @@ void PlatformThread::SetName(const char*
pthread_setname_np(pthread_self(), "%s", (void *)name);
#elif defined(OS_BSD) && !defined(__GLIBC__)
pthread_set_name_np(pthread_self(), name);
-#else
+#elif !defined(OS_SOLARIS)
+ prctl(PR_SET_NAME, reinterpret_cast<uintptr_t>(name), 0, 0, 0);
#endif
}
#endif // !OS_MACOSX
| [
"ryoon"
] | ryoon |
df3e34d4da54a067670c29dd0367e974f2669446 | b3a8fae5c8a13f16eb6a21277989822777660168 | /main.cpp | c103f08bb2e1aec5d9e7c05015205a87d421c9f4 | [] | no_license | oleg0x/Trees | 3476af21f1bd5646fb14997fecbecc451a14d797 | 3c26443cb801dc44b35ae8eeda686cfc07815da8 | refs/heads/main | 2023-04-25T14:28:56.356565 | 2021-04-27T14:06:24 | 2021-04-27T14:06:24 | 357,186,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 711 | cpp | #include <iostream>
void CtorsTest();
void AssignmentTest();
void PutGetTest();
void InsertEraseTest();
void AtTest();
void OperSquareBracketsTest();
void MinMaxKeyTest();
void FloorCeilingKeyTest();
void SizeTest();
void EraseMinTest();
void EraseTest();
void TraverseTest();
void OperEqualTest();
void RBTPutGetTest();
void RBTEraseTest();
void RBTEraseTest2();
int main()
{
std::cerr << std::boolalpha;
CtorsTest();
AssignmentTest();
PutGetTest();
InsertEraseTest();
AtTest();
OperSquareBracketsTest();
MinMaxKeyTest();
FloorCeilingKeyTest();
SizeTest();
EraseMinTest();
EraseTest();
TraverseTest();
OperEqualTest();
RBTPutGetTest();
RBTEraseTest();
RBTEraseTest2();
}
| [
"[email protected]"
] | |
8e2838fc9ac49399726adc675b77d8c0ebf782bb | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/mpl/preprocessed/vector/vector10.cpp | c84f9bf7c1b787a0034e0b43709de3acd5027451 | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp |
// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#define BOOST_MPL_PREPROCESSING_MODE
#include <sstd/boost/config.hpp>
#include <sstd/boost/mpl/vector/vector10.hpp>
| [
"[email protected]"
] | |
3871abbbd66bd5c16d0289db5c22ae32e3496a57 | 5d4eef8b29e5c0584fdbe250bcd142f9a2420044 | /spi.cpp | ae89eaae82fb7b24df37b0dcb73063d40242b098 | [] | no_license | PRAJJWAL0606/spiral | a08a31e006c6bf28a5ce8f4c5251313ea1a3a7ae | 871dadcf72fbc61f553cea8a273486ff6445059e | refs/heads/master | 2020-07-25T03:04:51.277584 | 2019-09-12T21:00:24 | 2019-09-12T21:00:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp | #include<iostream>
using namespace std;
void fun()
{
int n;
int m;
cin>>n;
cin>>m;
int b=0;int c=0;
int a[n][m];int j=0;int k=0;int y=m-1;int v=n-1;
for(int i=0;i<n;i++)
{
for(int p=0;p<m;p++)
{
cin>>a[i][p];
}
}
while(k!=(n)/2||j!=(m)/2)
{
while(j<=y)
{
cout<<a[k][j];
j++;
}
j=j-1;
if(k!=(n)/2||j!=(m)/2)
{
while(k<=v)
{
k++;
if(k<=v)
cout<<a[k][j];
}
k=k-1;
}
if((k!=(n)/2||j!=(m)/2))
{
while(j>=b)
{
j--;
if(j>=b)
cout<<a[k][j];
}
j=j+1;
}
if(k!=(n)/2||j!=(m)/2)
{
while(k>=b)
{
k--;
if(k>b)
cout<<a[k][j];
}
k=k+1;
}
b++;
c++;
k=b;
j=c;
y--;
v--;
}
}
int main()
{
fun();
return 0;
}
| [
"[email protected]"
] | |
54487e31d03055bf0592a174aff8aa0d25aaa0f2 | 1216def0fa454bac13a2f394da613c89cfa33f94 | /queue/queue_list.cpp | 4d1c3804c9b87abc248a21a7043143fc2d118ba9 | [] | no_license | anishkumark82/interview_prep | 7b688d4e7dd50e6bdb50a30c437b24c9dba8961f | b60b9804620625a84e5cffdfa069aeff291de266 | refs/heads/master | 2020-12-24T11:18:06.144759 | 2018-03-25T03:09:09 | 2018-03-25T03:09:09 | 73,036,871 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,189 | cpp | // Queue implementation using list (not using std::list or std::queue)
// Basic operations
// - push() - O(n)
// - pop() - O(1)
// - isEmpty() - O(1)
#include <iostream>
using namespace std;
template <typename T>
class MyQueue
{
private:
typedef struct _node
{
T data;
struct _node *next;
}node;
node *head;
// create a node
node *create_node(T &data)
{
node *temp = new node();
temp->data = data;
temp->next = NULL;
return temp;
}
public:
MyQueue():
head(nullptr)
{}
bool isEmpty()
{
return(head == NULL);
}
bool push(T &&data) // Builds only with C++11
{
node *temp = create_node(data);
bool status = (temp);
if(status)
{
if(head == NULL)
{
head = temp;
}
else
{
node *temp1 = head;
while(temp1->next)
{
temp1 = temp1->next;
}
temp1->next = temp;
}
}
return status;
}
bool pop(T &data)
{
bool status = true;
if(isEmpty())
{
status = false;
}
else
{
node *temp = head;
data = temp->data;
head = head->next;
delete temp;
}
return status;
}
void display_q()
{
if(!isEmpty())
{
cout<<endl;
node *temp = head;
while(temp)
{
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
}
};
int main()
{
MyQueue<int> q;
int data;
q.push(10);
q.display_q();
q.push(20);
q.display_q();
q.push(30);
q.display_q();
q.push(40);
q.display_q();
q.push(50);
q.display_q();
q.push(60);
q.display_q();
q.pop(data);
q.display_q();
q.pop(data);
q.display_q();
q.pop(data);
q.display_q();
q.pop(data);
q.display_q();
q.pop(data);
q.display_q();
return 0;
}
| [
"[email protected]"
] | |
81d6fa0430e797c234aee8f02f43909bda8f6766 | b79922441be78aa772787c5e2f2fbcc4e27a40fa | /geometry/proximity/test/deformable_contact_internal_test.cc | a8dbbf45fd4c5d5b5cfa9e04a7e7a475ab02e99d | [
"BSD-3-Clause"
] | permissive | hongkai-dai/drake | 7fd528b9da306ac5045d9ac50a468118b043cd84 | 7904810e90b91fdef2bef54d7a5d806940165626 | refs/heads/master | 2023-08-22T15:04:55.066709 | 2023-07-25T04:04:27 | 2023-07-25T04:04:27 | 16,714,749 | 2 | 5 | NOASSERTION | 2023-06-21T18:42:52 | 2014-02-11T00:58:57 | C++ | UTF-8 | C++ | false | false | 15,936 | cc | #include "drake/geometry/proximity/deformable_contact_internal.h"
#include <gtest/gtest.h>
#include "drake/common/find_resource.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/geometry/proximity/deformable_mesh_intersection.h"
#include "drake/geometry/proximity/make_box_mesh.h"
#include "drake/geometry/proximity/make_sphere_mesh.h"
namespace drake {
namespace geometry {
namespace internal {
namespace deformable {
class GeometriesTester {
public:
/* Returns the deformable geometry with `deformable_id` registered in
`geometries`.
@pre a deformable representation with `deformable_id` exists in `geometries`.
*/
static const DeformableGeometry& get_deformable_geometry(
const Geometries& geometries, GeometryId deformable_id) {
return geometries.deformable_geometries_.at(deformable_id);
}
/* Returns the rigid geometry with `rigid_id` registered in `geometries`.
@pre a rigid representation with `rigid_id` exists in `geometries`. */
static const RigidGeometry& get_rigid_geometry(const Geometries& geometries,
GeometryId rigid_id) {
return geometries.rigid_geometries_.at(rigid_id);
}
};
namespace {
using Eigen::Vector3d;
using Eigen::VectorXd;
/* Makes an arbitrary volume mesh. */
VolumeMesh<double> MakeVolumeMesh() {
constexpr double kRadius = 0.5;
constexpr double kRezHint = 0.5;
Sphere sphere(kRadius);
return MakeSphereVolumeMesh<double>(
sphere, kRezHint, TessellationStrategy::kDenseInteriorVertices);
}
/* Makes a ProximityProperties with a resolution hint property in the hydro
group.
@pre resolution_hint > 0. */
ProximityProperties MakeProximityPropsWithRezHint(double resolution_hint) {
ProximityProperties props;
props.AddProperty(internal::kHydroGroup, internal::kRezHint, resolution_hint);
return props;
}
math::RigidTransformd default_pose() {
return math::RigidTransformd(math::RollPitchYaw<double>(1, 2, 3),
Vector3d(4, 5, 6));
}
GTEST_TEST(GeometriesTest, AddRigidGeometry) {
Geometries geometries;
GeometryId rigid_id = GeometryId::get_new_id();
/* No geometries have been added yet. */
EXPECT_FALSE(geometries.is_rigid(rigid_id));
EXPECT_FALSE(geometries.is_deformable(rigid_id));
/* Add a rigid geometry with resolution hint property. */
constexpr double kRadius = 0.5;
constexpr double kRezHint = 0.5;
ProximityProperties props = MakeProximityPropsWithRezHint(kRezHint);
geometries.MaybeAddRigidGeometry(Sphere(kRadius), rigid_id, props,
default_pose());
EXPECT_TRUE(geometries.is_rigid(rigid_id));
EXPECT_FALSE(geometries.is_deformable(rigid_id));
/* Trying to a rigid geometry without the resolution hint property is a no-op.
*/
GeometryId g_id = GeometryId::get_new_id();
ProximityProperties empty_props;
geometries.MaybeAddRigidGeometry(Sphere(kRadius), g_id, empty_props,
default_pose());
EXPECT_FALSE(geometries.is_rigid(g_id));
EXPECT_FALSE(geometries.is_deformable(g_id));
}
/* Test coverage for all unsupported shapes as rigid geometries: MeshcatCone and
* HalfSpace. */
GTEST_TEST(GeometriesTest, UnsupportedRigidShapes) {
constexpr double kRezHint = 0.5;
ProximityProperties props = MakeProximityPropsWithRezHint(kRezHint);
Geometries geometries;
/* Unsupported shapes: MeshcatCone, HalfSpace. */
/* MeshcatCone */
{
GeometryId cone_id = GeometryId::get_new_id();
const double height = 2.0;
const double a = 1.0;
const double b = 1.0;
EXPECT_NO_THROW(geometries.MaybeAddRigidGeometry(
MeshcatCone(height, a, b), cone_id, props, default_pose()));
EXPECT_FALSE(geometries.is_rigid(cone_id));
}
/* HalfSpace */
{
GeometryId hs_id = GeometryId::get_new_id();
EXPECT_NO_THROW(geometries.MaybeAddRigidGeometry(HalfSpace(), hs_id, props,
default_pose()));
EXPECT_FALSE(geometries.is_rigid(hs_id));
}
}
/* Test coverage for all supported shapes as rigid geometries: Box, Sphere,
Cylinder, Capsule, Ellipsoid, Mesh, Convex. */
GTEST_TEST(GeometriesTest, SupportedRigidShapes) {
constexpr double kRezHint = 0.5;
ProximityProperties props = MakeProximityPropsWithRezHint(kRezHint);
Geometries geometries;
/* Box */
{
GeometryId box_id = GeometryId::get_new_id();
geometries.MaybeAddRigidGeometry(Box::MakeCube(1.0), box_id, props,
default_pose());
EXPECT_TRUE(geometries.is_rigid(box_id));
}
/* Sphere */
{
const double radius = 1.0;
GeometryId box_id = GeometryId::get_new_id();
geometries.MaybeAddRigidGeometry(Sphere(radius), box_id, props,
default_pose());
EXPECT_TRUE(geometries.is_rigid(box_id));
}
/* Cylinder */
{
GeometryId cylinder_id = GeometryId::get_new_id();
const double radius = 1.0;
const double length = 2.0;
geometries.MaybeAddRigidGeometry(Cylinder(radius, length), cylinder_id,
props, default_pose());
EXPECT_TRUE(geometries.is_rigid(cylinder_id));
}
/* Capsule */
{
GeometryId capsule_id = GeometryId::get_new_id();
const double radius = 1.0;
const double length = 2.0;
geometries.MaybeAddRigidGeometry(Capsule(radius, length), capsule_id, props,
default_pose());
EXPECT_TRUE(geometries.is_rigid(capsule_id));
}
/* Ellipsoid */
{
GeometryId ellipsoid_id = GeometryId::get_new_id();
const double a = 0.5;
const double b = 0.8;
const double c = 0.3;
geometries.MaybeAddRigidGeometry(Ellipsoid(a, b, c), ellipsoid_id, props,
default_pose());
EXPECT_TRUE(geometries.is_rigid(ellipsoid_id));
}
/* Mesh */
{
GeometryId mesh_id = GeometryId::get_new_id();
std::string file = FindResourceOrThrow("drake/geometry/test/quad_cube.obj");
geometries.MaybeAddRigidGeometry(Mesh(file, 1.0), mesh_id, props,
default_pose());
EXPECT_TRUE(geometries.is_rigid(mesh_id));
}
/* Convex */
{
GeometryId convex_id = GeometryId::get_new_id();
std::string file = FindResourceOrThrow("drake/geometry/test/quad_cube.obj");
geometries.MaybeAddRigidGeometry(Convex(file, 1.0), convex_id, props,
default_pose());
EXPECT_TRUE(geometries.is_rigid(convex_id));
}
}
GTEST_TEST(GeometriesTest, UpdateRigidWorldPose) {
Geometries geometries;
/* Add a rigid geometry. */
GeometryId rigid_id = GeometryId::get_new_id();
constexpr double kRadius = 0.5;
constexpr double kRezHint = 0.5;
ProximityProperties props = MakeProximityPropsWithRezHint(kRezHint);
geometries.MaybeAddRigidGeometry(Sphere(kRadius), rigid_id, props,
default_pose());
/* Initially the pose is the default pose. */
{
const RigidGeometry& rigid_geometry =
GeometriesTester::get_rigid_geometry(geometries, rigid_id);
EXPECT_TRUE(
rigid_geometry.pose_in_world().IsExactlyEqualTo(default_pose()));
}
/* Update the pose to some arbitrary value. */
const math::RigidTransform<double> X_WG(
math::RollPitchYaw<double>(-1.57, 0, 3), Vector3d(-0.3, -0.55, 0.36));
geometries.UpdateRigidWorldPose(rigid_id, X_WG);
{
const RigidGeometry& rigid_geometry =
GeometriesTester::get_rigid_geometry(geometries, rigid_id);
EXPECT_TRUE(rigid_geometry.pose_in_world().IsExactlyEqualTo(X_WG));
}
}
GTEST_TEST(GeometriesTest, AddDeformableGeometry) {
Geometries geometries;
GeometryId deformable_id = GeometryId::get_new_id();
EXPECT_FALSE(geometries.is_rigid(deformable_id));
EXPECT_FALSE(geometries.is_deformable(deformable_id));
/* Add a deformable geometry. */
geometries.AddDeformableGeometry(deformable_id, MakeVolumeMesh());
EXPECT_FALSE(geometries.is_rigid(deformable_id));
EXPECT_TRUE(geometries.is_deformable(deformable_id));
}
GTEST_TEST(GeometriesTest, RemoveGeometry) {
Geometries geometries;
/* Add a couple of deformable geometries. */
GeometryId deformable_id0 = GeometryId::get_new_id();
GeometryId deformable_id1 = GeometryId::get_new_id();
geometries.AddDeformableGeometry(deformable_id0, MakeVolumeMesh());
geometries.AddDeformableGeometry(deformable_id1, MakeVolumeMesh());
/* Add a couple of rigid geometries. */
GeometryId rigid_id0 = GeometryId::get_new_id();
GeometryId rigid_id1 = GeometryId::get_new_id();
constexpr double kRadius = 0.5;
constexpr double kRezHint = 0.5;
ProximityProperties props = MakeProximityPropsWithRezHint(kRezHint);
geometries.MaybeAddRigidGeometry(Sphere(kRadius), rigid_id0, props,
default_pose());
geometries.MaybeAddRigidGeometry(Sphere(kRadius), rigid_id1, props,
default_pose());
/* Calling RemoveGeometry on an existing deformable geometry. */
geometries.RemoveGeometry(deformable_id0);
/* The geometry is indeed removed. */
EXPECT_FALSE(geometries.is_deformable(deformable_id0));
/* Other geometries are unaffected. */
EXPECT_TRUE(geometries.is_deformable(deformable_id1));
EXPECT_TRUE(geometries.is_rigid(rigid_id0));
EXPECT_TRUE(geometries.is_rigid(rigid_id1));
/* Calling RemoveGeometry on an existing rigid geometry. */
geometries.RemoveGeometry(rigid_id0);
/* The geometry is indeed removed. */
EXPECT_FALSE(geometries.is_rigid(rigid_id0));
/* Other geometries are unaffected. */
EXPECT_FALSE(geometries.is_deformable(deformable_id0));
EXPECT_TRUE(geometries.is_deformable(deformable_id1));
EXPECT_TRUE(geometries.is_rigid(rigid_id1));
/* Calling RemoveGeometry on an invalid or already deleted geometry is a
no-op. */
GeometryId invalid_id = GeometryId::get_new_id();
EXPECT_NO_THROW(geometries.RemoveGeometry(invalid_id));
EXPECT_NO_THROW(geometries.RemoveGeometry(rigid_id0));
EXPECT_FALSE(geometries.is_rigid(rigid_id0));
EXPECT_FALSE(geometries.is_deformable(deformable_id0));
EXPECT_TRUE(geometries.is_rigid(rigid_id1));
EXPECT_TRUE(geometries.is_deformable(deformable_id1));
}
GTEST_TEST(GeometriesTest, UpdateDeformableVertexPositions) {
Geometries geometries;
/* Add a deformable geometry. */
GeometryId deformable_id = GeometryId::get_new_id();
const VolumeMesh<double> input_mesh = MakeVolumeMesh();
geometries.AddDeformableGeometry(deformable_id, input_mesh);
const int num_vertices = input_mesh.num_vertices();
/* Initially the vertex positions is the same as the registered mesh. */
{
ASSERT_TRUE(geometries.is_deformable(deformable_id));
const DeformableGeometry& geometry =
GeometriesTester::get_deformable_geometry(geometries, deformable_id);
EXPECT_TRUE(geometry.deformable_mesh().mesh().Equal(input_mesh));
}
/* Update the vertex positions to some arbitrary value. */
const VectorXd q = VectorXd::LinSpaced(3 * num_vertices, 0.0, 1.0);
geometries.UpdateDeformableVertexPositions(deformable_id, q);
{
const DeformableGeometry& geometry =
GeometriesTester::get_deformable_geometry(geometries, deformable_id);
const VolumeMesh<double>& mesh = geometry.deformable_mesh().mesh();
for (int i = 0; i < num_vertices; ++i) {
const Vector3d& q_MV = mesh.vertex(i);
const Vector3d& reference_q_MV = input_mesh.vertex(i);
const Vector3d& expected_q_MV = q.segment<3>(3 * i);
EXPECT_EQ(q_MV, expected_q_MV);
EXPECT_NE(q_MV, reference_q_MV);
}
}
}
GTEST_TEST(GeometriesTest, ComputeDeformableContact) {
Geometries geometries;
/* The contact data is empty when there is no deformable geometry. */
DeformableContact<double> contact_data =
geometries.ComputeDeformableContact();
EXPECT_EQ(contact_data.contact_surfaces().size(), 0);
/* Add a deformable unit cube. */
GeometryId deformable_id = GeometryId::get_new_id();
VolumeMesh<double> deformable_mesh =
MakeBoxVolumeMesh<double>(Box::MakeCube(1.0), 1.0);
const int num_vertices = deformable_mesh.num_vertices();
geometries.AddDeformableGeometry(deformable_id, std::move(deformable_mesh));
/* There is no geometry to collide with the deformable geometry yet. */
contact_data = geometries.ComputeDeformableContact();
ASSERT_EQ(contact_data.contact_surfaces().size(), 0);
/* Add a rigid unit cube. */
GeometryId rigid_id = GeometryId::get_new_id();
ProximityProperties rigid_properties = MakeProximityPropsWithRezHint(1.0);
math::RigidTransform<double> X_WR(Vector3d(0, -2.0, 0));
geometries.MaybeAddRigidGeometry(Box::MakeCube(1.0), rigid_id,
rigid_properties, X_WR);
/* The deformable box and the rigid box are not in contact yet. */
contact_data = geometries.ComputeDeformableContact();
ASSERT_EQ(contact_data.contact_surfaces().size(), 0);
/* Now shift the rigid geometry closer to the deformable geometry.
+Z
|
|
rigid box | deformable box
----------+--+--+-------
| | ● | |
| | | | |
-Y-----+---------+--+--+------+-------+Y
| | | | |
| | ● | |
----------+--+--+-------
|
|
|
-Z
where the "●"s denote representative contact points. */
X_WR = math::RigidTransform<double>(Vector3d(0, -0.75, 0));
geometries.UpdateRigidWorldPose(rigid_id, X_WR);
/* Now there should be exactly one contact data. */
contact_data = geometries.ComputeDeformableContact();
ASSERT_EQ(contact_data.contact_surfaces().size(), 1);
/* Verify that the contact surface is as expected. */
const auto& X_DR =
X_WR; // The deformable mesh frame is always the world frame.
const DeformableGeometry& deformable_geometry =
GeometriesTester::get_deformable_geometry(geometries, deformable_id);
const RigidGeometry& rigid_geometry =
GeometriesTester::get_rigid_geometry(geometries, rigid_id);
DeformableContact<double> expected_contact_data;
expected_contact_data.RegisterDeformableGeometry(deformable_id, num_vertices);
AddDeformableRigidContactSurface(deformable_geometry, deformable_id, rigid_id,
rigid_geometry.rigid_mesh().mesh(),
rigid_geometry.rigid_mesh().bvh(), X_DR,
&expected_contact_data);
/* Verify that the contact data is the same as expected by checking a subset
of all data fields. */
ASSERT_EQ(contact_data.contact_surfaces().size(),
expected_contact_data.contact_surfaces().size());
const DeformableContactSurface<double>& contact_surface =
contact_data.contact_surfaces()[0];
const DeformableContactSurface<double>& expected_contact_surface =
expected_contact_data.contact_surfaces()[0];
// TODO(xuchenhan-tri): consider adding a `Equal` function for
// DeformableContactSurface.
EXPECT_EQ(contact_surface.id_A(), expected_contact_surface.id_A());
EXPECT_EQ(contact_surface.id_B(), expected_contact_surface.id_B());
EXPECT_EQ(contact_surface.num_contact_points(),
expected_contact_surface.num_contact_points());
EXPECT_TRUE(contact_surface.contact_mesh_W().Equal(
expected_contact_surface.contact_mesh_W()));
}
} // namespace
} // namespace deformable
} // namespace internal
} // namespace geometry
} // namespace drake
| [
"[email protected]"
] | |
63e42f49755b2695c1b6e3411cb83fcea49eecba | b89de7e39eb9b2ef094e2578d0d71349bebc1f08 | /old stuff/F_Aviles_Lab9/Node.cpp | f9bb21883e568702a28c796d0299963c7561b8cd | [] | no_license | r556a812/olderKUFiles | 43bc54bbbb749650fdb6c3b08e718ad938b942fe | 25f3224d0b7542eb4a5d33d179290940072a7e92 | refs/heads/master | 2020-03-16T22:52:17.985779 | 2018-05-11T15:49:23 | 2018-05-11T15:49:23 | 133,055,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | /**
* @file : Node.cpp
* @author : Richard Aviles
* @date : 2015.08.26
* Purpose: Creates the Node and its set and get methods.
*/
#include "Node.h"
Node::Node()
{
m_value = 0;
m_left = nullptr;
m_right = nullptr;
rank = 1;
}
void Node::setValue(int value)
{
m_value = value;
}
int Node::getValue() const
{
return(m_value);
}
void Node::setLeft(Node* left)
{
m_left = left;
}
void Node::setRight(Node* right)
{
m_right = right;
}
Node* Node::getLeft() const
{
return(m_left);
}
Node* Node::getRight() const
{
return(m_right);
}
void Node::setRank(int a)
{
rank = a;
}
int Node::getRank()
{
return(rank);
}
| [
"[email protected]"
] | |
6f3540d77d3f263609999b900fdbb901788ea7a1 | 9f6ac63e81535daeb55611d66560ab2a87fc9d8c | /libs/vislib/graphics/src/FpsCounter.cpp | 0aff2e18150e2902774fa30065ddd3fec03fb60f | [] | no_license | ComputationalRadiationPhysics/rivlib | 68e4de9cc98f62112ec21a05d68c406ef580a32d | 1a838630400892a53ff7eb120aec4282fc9967ac | refs/heads/master | 2021-01-21T05:00:23.480426 | 2016-05-23T07:29:51 | 2016-05-23T07:29:51 | 29,530,946 | 3 | 1 | null | 2016-05-23T07:29:51 | 2015-01-20T13:27:18 | C++ | UTF-8 | C++ | false | false | 5,381 | cpp | /*
* FpsCounter.cpp
*
* Copyright (C) 2006 - 2007 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "vislib/FpsCounter.h"
#include <climits>
#include <cfloat>
#include "vislib/assert.h"
#include "vislib/mathfunctions.h"
#include "vislib/memutils.h"
#include "vislib/IllegalParamException.h"
#include "vislib/IllegalStateException.h"
#include "vislib/PerformanceCounter.h"
#include "vislib/UnsupportedOperationException.h"
/*
* vislib::graphics::FpsCounter::FpsCounter
*/
vislib::graphics::FpsCounter::FpsCounter(unsigned int bufLength)
: now(0), timeValues(NULL), timeValuesCount(0), timeValuesPos(0),
wholeBufferValid(false), frameRunning(false), avrMillis(FLT_MAX),
fpsValuesValid(false) {
this->SetBufferLength(bufLength);
}
/*
* vislib::graphics::FpsCounter::~FpsCounter
*/
vislib::graphics::FpsCounter::~FpsCounter(void) {
ARY_SAFE_DELETE(this->timeValues);
this->timeValuesCount = 0; // paranoia
}
/*
* vislib::graphics::FpsCounter::FrameBegin
*/
void vislib::graphics::FpsCounter::FrameBegin(void) {
if (this->frameRunning) {
throw IllegalStateException("Must call \"FrameEnd\" first.",
__FILE__, __LINE__);
}
double newNow = vislib::sys::PerformanceCounter::QueryMillis();
double diff = (newNow > this->now) ? (newNow - this->now) : 0.0;
this->timeValues[this->timeValuesPos].before = diff;
this->now = newNow;
this->frameRunning = true;
this->fpsValuesValid = false;
}
/*
* vislib::graphics::FpsCounter::FrameEnd
*/
void vislib::graphics::FpsCounter::FrameEnd(void) {
if (!this->frameRunning) {
throw IllegalStateException("Must call \"FrameBegin\" first.",
__FILE__, __LINE__);
}
double newNow = vislib::sys::PerformanceCounter::QueryMillis();
double diff = (newNow > this->now) ? (newNow - this->now) : 0.0;
this->timeValues[this->timeValuesPos++].frame = diff;
if (this->timeValuesPos >= this->timeValuesCount) {
this->timeValuesPos = 0;
this->wholeBufferValid = true;
}
this->now = newNow;
this->frameRunning = false;
this->fpsValuesValid = false;
}
/*
* vislib::graphics::FpsCounter::LastFrameTime
*/
double vislib::graphics::FpsCounter::LastFrameTime(void) const {
unsigned int idx = this->timeValuesPos;
if (idx > 0) {
idx--;
} else if (this->wholeBufferValid) {
idx = this->timeValuesCount - 1;
} else {
return 0.0;
}
return this->timeValues[idx].before + this->timeValues[idx].frame;
}
/*
* vislib::graphics::FpsCounter::Reset
*/
void vislib::graphics::FpsCounter::Reset(void) {
this->now = vislib::sys::PerformanceCounter::QueryMillis();
this->timeValuesPos = 0;
this->wholeBufferValid = false;
this->frameRunning = false;
}
/*
* vislib::graphics::FpsCounter::SetBufferLength
*/
void vislib::graphics::FpsCounter::SetBufferLength(unsigned int bufLength) {
ASSERT(bufLength > 0);
ARY_SAFE_DELETE(this->timeValues);
this->timeValuesCount = bufLength;
this->timeValues = new TimeValues[this->timeValuesCount];
this->Reset();
}
/*
* vislib::graphics::FpsCounter::FpsCounter
*/
vislib::graphics::FpsCounter::FpsCounter(const FpsCounter& rhs) {
throw vislib::UnsupportedOperationException("Copy Ctor", __FILE__,
__LINE__);
}
/*
* vislib::graphics::FpsCounter::operator =
*/
vislib::graphics::FpsCounter& vislib::graphics::FpsCounter::operator =(
const vislib::graphics::FpsCounter& rhs) {
if (&rhs != this) {
throw vislib::IllegalParamException("rhs", __FILE__, __LINE__);
}
return *this;
}
/*
* vislib::graphics::FpsCounter::evaluate
*/
void vislib::graphics::FpsCounter::evaluate(void) const {
unsigned int count = (this->wholeBufferValid ? this->timeValuesCount :
vislib::math::Max<int>(this->timeValuesPos - 1, 0));
if (count == 0) {
this->avrFPS = this->minFPS = this->maxFPS = 0.0f;
this->fpsValuesValid = true;
return;
}
unsigned int avrCount = count;
double time;
double allTime = 0.0;
double maxTime = 0.0;
double minTime = FLT_MAX;
/** summarise over the whole measurement buffer */
for (unsigned int i = 0; i < count; i++) {
time = this->timeValues[i].before + this->timeValues[i].frame;
if (allTime < this->avrMillis) {
allTime += time;
if (allTime >= this->avrMillis) {
avrCount = i + 1;
}
}
if (maxTime < time) maxTime = time;
if (minTime > time) minTime = time;
}
/** average fps */
if (allTime > 0) {
this->avrFPS = static_cast<float>(static_cast<double>(avrCount)
* 1000.0 / allTime);
} else {
this->avrFPS = 0.0f;
}
/** maximum fps */
if (minTime > 0) {
this->maxFPS = static_cast<float>(1000.0 / minTime);
} else {
this->maxFPS = 0.0f;
}
/** minimum fps */
if (maxTime > 0) {
this->minFPS = static_cast<float>(1000.0 / maxTime);
} else {
this->minFPS = 0.0f;
}
this->fpsValuesValid = true;
}
| [
"[email protected]"
] | |
37e9d00bbe1a6d46434e9407c204104fd780c44f | a0083508bd1b5fbca2932aba10e4778f1e7b1f5c | /Mesh-Animator/attachment.h | db5060dc8522235eb6ad7186853e39448cec3ef6 | [
"MIT"
] | permissive | adlawren/Computer-Graphics-Exercises | 6bad79f7a81c0b09af4b7529d7c8f51069f06707 | 423630715416105632e624ea78b5a574eb80323e | refs/heads/master | 2021-03-27T15:49:44.017766 | 2017-12-08T06:02:15 | 2017-12-08T18:21:45 | 104,153,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,734 | h | // Notice: The majority of this code was written by Dale Schuurmans, and was
// copied and pasted with his permission
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cfloat>
#include <climits>
#include <cmath>
#include <vector>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#ifndef __APPLE__
#include <GL/glew.h>
#endif
#include <GL/freeglut.h>
#include "mesh.h"
#include "skeleton.h"
#ifndef ATTACHMENT_H
#define ATTACHMENT_H
using namespace Eigen;
struct Wtuple {
unsigned int i, j;
float w;
};
// attachment class
struct attachment {
mesh *objp;
skeleton *skelp;
MatrixXf *D; // These are the matrices defined in the lecture notes.
MatrixXi *V;
MatrixXf *S;
VectorXf *h;
MatrixXf *C;
SparseMatrix<int> *A;
SparseMatrix<int> *L;
MatrixXf *W;
vector<Vector3f> deformedVertexLocations;
vector<Vector3f> deformedVertexNormals;
// constructors
attachment() {}
attachment(mesh *objref, skeleton *skelref) : objp(objref), skelp(skelref) {}
// member functions
void readW(char *);
void glDrawMeshAttach(bool, int);
void glDrawDeformedMesh(void);
void computeDeformedVertices(joint *j, Matrix4f, Vector3f, Quaternionf,
int &);
// computing attachments
void distancesVisibility(float *);
void connectionValues(void);
void adjacencyLaplacian();
void attachmentWeights(float);
void enhanceWeights(float, float);
void connectOrphans();
// output functions
void writeVectorXf(VectorXf *, char *);
void writeMatrixXf(MatrixXf *, char *);
void writeMatrixXi(MatrixXi *, char *);
void writeMatrixXfSparse(MatrixXf *, char *);
void writeSparseMatrixXi(SparseMatrix<int> *, char *);
};
#endif
| [
"[email protected]"
] | |
4c10aa01b92db28e4101a8f21e530c008da2e8f8 | 7e2a6bbaa038429d46631a1b41292bce14dc6d88 | /exnih/LibraryNuclide.cpp | 30459f1f30fb24a1a34a46cee32df43146fc29de | [] | no_license | eNorris/thesis | 6242c531cb3f9f330246458720ecd1a1559aa7e5 | b3b9ed0fcd52e5eb72cf3bbff1342191142bbfae | refs/heads/master | 2021-11-30T15:30:13.185279 | 2017-07-05T01:49:42 | 2017-07-05T01:49:42 | 53,451,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,371 | cpp | //#include "Standard/Interface/AbstractStream.h"
//#include "Resource/AmpxLib/ampxlib_config.h"
#include "LibraryNuclide.h"
#include "BondarenkoGlobal.h"
#include "NuclideResonance.h"
#include "AmpxLibrary.h"
#include <string>
#include <QDebug>
#include "AmpxDataHelper.h"
LibraryNuclide::LibraryNuclide() {
initialize();
}
LibraryNuclide::LibraryNuclide( const LibraryNuclide & orig, NuclideFilter * f){
d = orig.d;
d->ref.ref();
bondarenkoGlobalData = NULL;
subGroups = NULL;
if( orig.subGroups != NULL) subGroups = orig.subGroups->getCopy();
setResonance(NULL);
setTotal2dXS(NULL);
NuclideFilter filter(f!=NULL ? *f : NuclideFilter(NuclideFilter::Keep)); // default global policy is Keep
AmpxLibrary * library = filter.getAmpxLib();
qDebug() << qPrintable("Nuclide ")<<getId()<<" filtered copy with library at address ";
if (orig.totalXS != NULL) {
//qDebug()<<"Copying total xs...";
//if( filter.acceptsTotal() )
this->setTotal2dXS(orig.totalXS->getCopy());
}
if( orig.resonance != NULL){
this->resonance = new NuclideResonance(*orig.resonance);
}
this->setNumBondarenkoSig0Data(0);
this->setNumBondarenkoTempData(0);
this->setMaxNumBondGrp(0);
this->setNumBondarenkoData(0);
if (orig.bondarenkoGlobalData != NULL)
for (int i = 0; i < orig.bondarenkoData.size(); i++){
if( filter.acceptsBondarenko(orig.bondarenkoData.at(i)->getMt() ) ) {
this->bondarenkoGlobalData = orig.bondarenkoGlobalData->getCopy();
this->setNumBondarenkoSig0Data(const_cast<LibraryNuclide*>(&orig)->getNumBondarenkoSig0Data());
this->setNumBondarenkoTempData(const_cast<LibraryNuclide*>(&orig)->getNumBondarenkoTempData());
this->setMaxNumBondGrp(const_cast<LibraryNuclide*>(&orig)->getMaxNumBondGrp());
break;
}
}
//if( filter.acceptsBondarenkoGlobal() )
//this->bondarenkoGlobalData = orig.bondarenkoGlobalData->getCopy();
//qDebug()<<"Done copying global...";
if( library != NULL )
{
char * description = AmpxDataHelper::getDescription(const_cast<LibraryNuclide*>(&orig), library);
this->setDescription(description);
}
else
{
for( int i = 0; i < AMPX_NUCLIDE_DESCR_LENGTH+1; i++)
this->d->description[i] = orig.d->description[i];
if( this->getDescription() == NULL ) {
//for( int i = 0;i < AMPX_NUCLIDE_DESCR_LENGTH; i++)
//char achar=' ';
for( int i = 0; i < AMPX_NUCLIDE_DESCR_LENGTH; i++)
this->d->description[i] = ' ';
}
this->d->description[AMPX_NUCLIDE_DESCR_LENGTH] = '\0';
}
// The following copies are based on the contents of the appropriate lists,
// not the number counts stored in the orig information directory
if( library != NULL )
{
QList<int> * mts = AmpxDataHelper::getBondarenkoDataMts(const_cast<LibraryNuclide*>(&orig), library);
for( int i = 0; i < mts->size(); i++ )
{
if( filter.acceptsBondarenko(mts->at(i) ) ){
this->bondarenkoData.append(AmpxDataHelper::getBondarenkoDataByMt(const_cast<LibraryNuclide*>(&orig),library,mts->at(i),true)->getCopy());
this->setNumBondarenkoData(this->bondarenkoData.size());
}
}
delete mts;
}
else
{
for (int i = 0; i < orig.bondarenkoData.size(); i++){
if( filter.acceptsBondarenko(orig.bondarenkoData.at(i)->getMt() ) ){
qDebug() << qPrintable("Accepting bondarenko ")<<orig.bondarenkoData.at(i)->getMt();
this->bondarenkoData.append(orig.bondarenkoData.at(i)->getCopy());
this->setNumBondarenkoData(this->bondarenkoData.size());
}else
{
qDebug() << qPrintable("NOT Accepting bondarenko ")<<orig.bondarenkoData.at(i)->getMt();
}
}
}
if( library != NULL )
{
QList<int> * mts = AmpxDataHelper::getNeutron1dXSMts(const_cast<LibraryNuclide*>(&orig), library);
for( int i = 0; i < mts->size(); i++ )
{
if( filter.acceptsNeutron1d(mts->at(i) ) ){
this->neutron1dData.append(AmpxDataHelper::getNeutron1dXSByMt(const_cast<LibraryNuclide*>(&orig),library,mts->at(i),true)->getCopy());
this->setNumNeutron1dData(this->neutron1dData.size());
}
}
delete mts;
}
else
{
for (int i = 0; i < orig.neutron1dData.size(); i++){
if( filter.acceptsNeutron1d(orig.neutron1dData.at(i)->getMt() ) ){
this->neutron1dData.append(orig.neutron1dData.at(i)->getCopy());
this->setNumNeutron1dData(this->neutron1dData.size());
}
}
}
if( library != NULL )
{
QList<int> * mts = AmpxDataHelper::getGamma1dXSMts(const_cast<LibraryNuclide*>(&orig), library);
for( int i = 0; i < mts->size(); i++ )
{
if( filter.acceptsGamma1d(mts->at(i) ) ){
this->gamma1dData.append(AmpxDataHelper::getGamma1dXSByMt(const_cast<LibraryNuclide*>(&orig),library,mts->at(i),true)->getCopy());
this->setNumGamma1dData(this->gamma1dData.size());
}
}
delete mts;
}
else
{
for (int i = 0; i < orig.gamma1dData.size(); i++){
if( filter.acceptsGamma1d(orig.gamma1dData.at(i)->getMt() ) ){
this->gamma1dData.append(orig.gamma1dData.at(i)->getCopy());
this->setNumGamma1dData(this->gamma1dData.size());
}
}
}
if( library != NULL )
{
QList<int> * mts = AmpxDataHelper::getNeutron2dXSMts(const_cast<LibraryNuclide*>(&orig), library);
for( int i = 0; i < mts->size(); i++ )
{
if( filter.acceptsNeutron2d(mts->at(i) ) )
{
this->neutron2dData.append(AmpxDataHelper::getNeutron2dXSByMt(const_cast<LibraryNuclide*>(&orig),library,mts->at(i),true)->getCopy());
this->setNumNeutron2dData(this->neutron2dData.size());
}
}
delete mts;
}
else
{
for (int i = 0; i < orig.neutron2dData.size(); i++){
if( filter.acceptsNeutron2d(orig.neutron2dData.at(i)->getMt() ) ){
this->neutron2dData.append(orig.neutron2dData.at(i)->getCopy());
this->setNumNeutron2dData(this->neutron2dData.size());
}
}
}
if( library != NULL )
{
QList<int> * mts = AmpxDataHelper::getGamma2dXSMts(const_cast<LibraryNuclide*>(&orig), library);
for( int i = 0; i < mts->size(); i++ )
{
if( filter.acceptsGamma2d(mts->at(i) ) ){
this->gamma2dData.append(AmpxDataHelper::getGamma2dXSByMt(const_cast<LibraryNuclide*>(&orig),library,mts->at(i),true)->getCopy());
this->setNumGamma2dData(this->gamma2dData.size());
}
}
delete mts;
}
else
{
for (int i = 0; i < orig.gamma2dData.size(); i++){
if( filter.acceptsGamma2d(orig.gamma2dData.at(i)->getMt() ) ){
this->gamma2dData.append(orig.gamma2dData.at(i)->getCopy());
this->setNumGamma2dData(this->gamma2dData.size());
}
}
}
if( library != NULL )
{
QList<int> * mts = AmpxDataHelper::getGammaProdXSMts(const_cast<LibraryNuclide*>(&orig), library);
for( int i = 0; i < mts->size(); i++ )
{
if( filter.acceptsGammaProd(mts->at(i) ) ){
this->gammaProdData.append(AmpxDataHelper::getGammaProdXSByMt(const_cast<LibraryNuclide*>(&orig),library,mts->at(i),true)->getCopy());
this->setNumGammaProdData(this->gammaProdData.size());
}
}
delete mts;
}
else
{
for (int i = 0; i < orig.gammaProdData.size(); i++){
if( filter.acceptsGammaProd(orig.gammaProdData.at(i)->getMt() ) ){
this->gammaProdData.append(orig.gammaProdData.at(i)->getCopy());
this->setNumGammaProdData(this->gammaProdData.size());
}
}
}
}
void LibraryNuclide::initialize() {
d = new LibraryNuclideData();
subGroups = NULL;
setBondarenkoGlobal(NULL);
setResonance(NULL);
setTotal2dXS(NULL);
}// end of initialize
LibraryNuclide::~LibraryNuclide() {
if( !d->ref.deref()){
delete d;
}
if( this->bondarenkoGlobalData != NULL )
{
delete this->bondarenkoGlobalData;
}
if( this->totalXS != NULL ) delete this->totalXS;
for (int i = 0; i < bondarenkoData.size(); i++)
delete bondarenkoData.value(i);
bondarenkoData.clear();
for (int i = 0; i < neutron1dData.size(); i++)
delete neutron1dData.value(i);
neutron1dData.clear();
for (int i = 0; i < neutron2dData.size(); i++)
delete neutron2dData.value(i);
neutron2dData.clear();
for (int i = 0; i < gamma1dData.size(); i++)
delete gamma1dData.value(i);
gamma1dData.clear();
for (int i = 0; i < gamma2dData.size(); i++)
delete gamma2dData.value(i);
gamma2dData.clear();
for (int i = 0; i < gammaProdData.size(); i++)
delete gammaProdData.value(i);
gammaProdData.clear();
if (getResonance() != NULL)
delete getResonance();
if( subGroups != NULL) delete subGroups;
}
bool LibraryNuclide::operator==(LibraryNuclide & a){
if( bondarenkoGlobalData != NULL && a.bondarenkoGlobalData != NULL ){
bool equal = *bondarenkoGlobalData == *a.bondarenkoGlobalData;
if( !equal )
{
qDebug() << qPrintable("BondarenkoGlobal not equal for nuclide id=")<<getId();
return false;
}
}else if(bondarenkoGlobalData == NULL && a.bondarenkoGlobalData != NULL ){
qDebug() << qPrintable("BondarenkoGlobal not equal for nuclide id=")<<getId();
return false;
}else if(bondarenkoGlobalData != NULL && a.bondarenkoGlobalData == NULL ){
qDebug() << qPrintable("BondarenkoGlobal not equal for nuclide id=")<<getId();
return false;
}
if( totalXS != NULL && a.totalXS != NULL ){
bool equal = *totalXS == *a.totalXS;
qDebug() << qPrintable("totalXS2d equal ")<<equal;
if( !equal ){
qDebug() << qPrintable("TotalXS not equal for nuclide id=")<<getId();
return false;
}
}else if(totalXS == NULL && a.totalXS != NULL ){
qDebug() << qPrintable("TotalXS not equal for nuclide id=")<<getId();
return false;
}else if(totalXS != NULL && a.totalXS == NULL ){
qDebug() << qPrintable("TotalXS not equal for nuclide id=")<<getId();
return false;
}
if( bondarenkoData.size() != a.bondarenkoData.size() ){
qDebug() << qPrintable("BondarenkoData of different sizes ")<<bondarenkoData.size()<<" "<<a.bondarenkoData.size();
return false;
}
for( int i = 0; i < bondarenkoData.size(); i++){
bool equal = *bondarenkoData[i] == *a.bondarenkoData[i];
if( !equal ) qDebug() << qPrintable("BondarenkoData at index ")<<i<<" equal "<<equal;
if( !equal ) return false;
}
if( subGroups != 0 && a.subGroups != 0){
bool equal = *subGroups == *a.subGroups;
if( !equal ) qDebug() << qPrintable("Subgroup data do not agree for nuclide id=")<<getId();
if( !equal) return false;
}
else{
if( subGroups != a.subGroups ){
return false;
}
}
if( neutron1dData.size() != a.neutron1dData.size() ){
qDebug() << qPrintable("Neutron1d of different sizes ")<<neutron1dData.size()<<" "<<a.neutron1dData.size();
return false;
}
for( int i = 0; i < neutron1dData.size(); i++){
bool equal = *neutron1dData[i] == *a.neutron1dData[i];
if( !equal )
{
qDebug() << qPrintable("Neutron1d not equal for nuclide id=")<<getId()<<" at index "<<i;
return false;
}
}
if( gamma1dData.size() != a.gamma1dData.size() ){
qDebug() << qPrintable("Gamma1d of different sizes ")<<gamma1dData.size()<<" "<<a.gamma1dData.size();
return false;
}
for( int i = 0; i < gamma1dData.size(); i++){
bool equal = *gamma1dData[i] == *a.gamma1dData[i];
if( !equal ){
qDebug() << qPrintable("Gamma1d not equal for nuclide id=")<<getId()<<" at index "<<i;
return false;
}
}
if( neutron2dData.size() != a.neutron2dData.size() ){
qDebug() << qPrintable("Neutron2d of different sizes ")<<bondarenkoData.size()<<" "<<a.bondarenkoData.size();
return false;
}
for( int i = 0; i < neutron2dData.size(); i++){
bool equal = *neutron2dData[i] == *a.neutron2dData[i];
if( !equal )
{
qDebug() << qPrintable("Neutron2d not equal for nuclide id=")<<getId()<<" at index "<<i;
return false;
}
}
if( gamma2dData.size() != a.gamma2dData.size() ){
qDebug() << qPrintable("Gamma2d of different sizes ")<<gamma2dData.size()<<" "<<a.gamma2dData.size();
return false;
}
for( int i = 0; i < gamma2dData.size(); i++){
bool equal = *gamma2dData[i] == *a.gamma2dData[i];
if( !equal ){
qDebug() << qPrintable("Gamma2d not equal for nuclide id=")<<getId()<<" at index "<<i;
return false;
}
}
if( gammaProdData.size() != a.gammaProdData.size() ){
qDebug() << qPrintable("GammaProd of different sizes ")<<gammaProdData.size()<<" "<<a.gammaProdData.size();
return false;
}
for( int i = 0; i < gammaProdData.size(); i++){
bool equal = *gammaProdData[i] == *a.gammaProdData[i];
if( !equal ){
qDebug() << qPrintable("GammaProd not equal for nuclide id=")<<getId()<<" at index "<<i;
return false;
}
}
if( d == a.d ) return true;
if( strcmp(d->description, a.d->description) != 0 ){
qDebug() << qPrintable("Nuclide description different '")<<d->description<<"' vs '"<<a.d->description<<"'.";
return false;
}
for( int i = 0; i < AMPX_NUMBER_NUCLIDE_INTEGER_OPTIONS; i++){
if( d->words[i] != a.d->words[i] ){
qDebug() << qPrintable("Nuclide word ")<<i<<" is different "<<d->words[i]<<" "<<a.d->words[i];
return false;
}
}
return true;
}
bool LibraryNuclide::containsBondarenkoDataByMt(int mt) {
for( int i = 0; i < bondarenkoData.size(); i ++){
if( bondarenkoData[i]->getMt() == mt ) return true;
}
return false;
}
bool LibraryNuclide::containsNeutron1dDataByMt(int mt) {
for( int i = 0; i < neutron1dData.size(); i ++){
if( neutron1dData[i]->getMt() == mt ) return true;
}
return false;
}
bool LibraryNuclide::containsNeutron2dDataByMt(int mt) {
for( int i = 0; i < neutron2dData.size(); i ++){
if( neutron2dData[i]->getMt() == mt ) return true;
}
return false;
}
bool LibraryNuclide::containsGamma1dDataByMt(int mt) {
for( int i = 0; i < gamma1dData.size(); i ++){
if( gamma1dData[i]->getMt() == mt ) return true;
}
return false;
}
bool LibraryNuclide::containsGamma2dDataByMt(int mt) {
for( int i = 0; i < gamma2dData.size(); i ++){
if( gamma2dData[i]->getMt() == mt ) return true;
}
return false;
}
bool LibraryNuclide::containsGammaProdDataByMt(int mt) {
for( int i = 0; i < gammaProdData.size(); i ++){
if( gammaProdData[i]->getMt() == mt ) return true;
}
return false;
}
LibraryNuclide * LibraryNuclide::getCopy() const {
LibraryNuclide * copy = new LibraryNuclide(*this);
return copy;
}
LibraryNuclide * LibraryNuclide::getCopy(NuclideFilter& filter) {
LibraryNuclide * copy = new LibraryNuclide(*this,&filter);
return copy;
}
void LibraryNuclide::copyFrom(LibraryNuclide & nuclide, bool fixAsMaster) {
//qDebug()<<"Copying nuclide...";
/// copy nuclides data words
qAtomicAssign(d, nuclide.d);
// fix as master is used when you are copying a working nuclide
// to a library nuclide and you want to fix the nuclide directory
if( fixAsMaster ){
for( int i = 2; i <= 9; i++)
setData(i,0);
for( int i = 17; i <=22; i++)
setData(i,0);
/// deep copy
if (nuclide.getTotal2dXS() != NULL) {
//qDebug()<<"Copying total xs...";
this->setTotal2dXS(nuclide.getTotal2dXS()->getCopy());
}
if (nuclide.getBondarenkoGlobal() != NULL)
this->setBondarenkoGlobal(nuclide.getBondarenkoGlobal()->getCopy());
//qDebug()<<"Done copying global...";
// The following copies are based on the contents of the appropriate lists,
// not the number counts stored in the nuclide information directory
for (int i = 0; i < nuclide.bondarenkoData.size(); i++)
this->addBondarenkoData(nuclide.getBondarenkoDataAt(i)->getCopy());
//qDebug()<<"Done copying bondata...";
for (int i = 0; i < nuclide.neutron1dData.size(); i++)
this->addNeutron1dData(nuclide.getNeutron1dDataAt(i)->getCopy());
//qDebug()<<"Done copying neutron1d...";
for (int i = 0; i < nuclide.gamma1dData.size(); i++)
this->addGamma1dData(nuclide.getGamma1dDataAt(i)->getCopy());
//qDebug()<<"Done copying gamma1d...";
for (int i = 0; i < nuclide.neutron2dData.size(); i++)
this->addNeutron2dData(nuclide.getNeutron2dDataAt(i)->getCopy());
//qDebug()<<"Done copying neutron2d...";
for (int i = 0; i < nuclide.gamma2dData.size(); i++)
this->addGamma2dData(nuclide.getGamma2dDataAt(i)->getCopy());
//qDebug()<<"Done copying gamma2d...";
for (int i = 0; i < nuclide.gammaProdData.size(); i++)
this->addGammaProdData(nuclide.getGammaProdDataAt(i)->getCopy());
//qDebug()<<"Done copying gammaProd...";
}else{
if (nuclide.getTotal2dXS() != NULL) {
//qDebug()<<"Copying total xs...";
this->setTotal2dXS(nuclide.getTotal2dXS()->getCopy());
}
if (nuclide.getBondarenkoGlobal() != NULL)
this->bondarenkoGlobalData = nuclide.getBondarenkoGlobal()->getCopy();
//qDebug()<<"Done copying global...";
// The following copies are based on the contents of the appropriate lists,
// not the number counts stored in the nuclide information directory
for (int i = 0; i < nuclide.bondarenkoData.size(); i++)
this->bondarenkoData.append(nuclide.getBondarenkoDataAt(i)->getCopy());
//qDebug()<<"Done copying bondata...";
for (int i = 0; i < nuclide.neutron1dData.size(); i++)
this->neutron1dData.append(nuclide.getNeutron1dDataAt(i)->getCopy());
//qDebug()<<"Done copying neutron1d...";
for (int i = 0; i < nuclide.gamma1dData.size(); i++)
this->gamma1dData.append(nuclide.getGamma1dDataAt(i)->getCopy());
//qDebug()<<"Done copying gamma1d...";
for (int i = 0; i < nuclide.neutron2dData.size(); i++)
this->neutron2dData.append(nuclide.getNeutron2dDataAt(i)->getCopy());
//qDebug()<<"Done copying neutron2d...";
for (int i = 0; i < nuclide.gamma2dData.size(); i++)
this->gamma2dData.append(nuclide.getGamma2dDataAt(i)->getCopy());
//qDebug()<<"Done copying gamma2d...";
for (int i = 0; i < nuclide.gammaProdData.size(); i++)
this->gammaProdData.append(nuclide.getGammaProdDataAt(i)->getCopy());
}
if( nuclide.resonance != NULL){
this->resonance = new NuclideResonance(*nuclide.resonance);
}
}
void LibraryNuclide::setId(int id) {
int oldid = getId();
if (id == oldid) return;
setData(AMPX_MAST_NUCLIDE_ID, id);
}
void LibraryNuclide::setMixture(int mix) {
int oldMixId = getMixture();
if( mix == oldMixId ) return;
setData(AMPX_NUCLIDE_MIXTURE, mix);
}
// Serialization interfaces
const long LibraryNuclide::uid = 0xfbacf55248146501;
/**
* @brief Serialize the object into a contiguous block of data
* @param AbstractStream * stream - the stream into which the contiguous data will be stored
* @return int - 0 upon success, error otherwise
*/
/*
int LibraryNuclide::serialize(Standard::AbstractStream * stream) const{
if( stream == NULL ) return -1;
long classUID = this->getUID();
stream->write((char*)&classUID, sizeof(classUID));
// write the size of this object
unsigned long serializedSize = getSerializedSize();
stream->write((char*)&serializedSize, sizeof(serializedSize));
// DBC=4 - capture the oldWriteHead for checksumming later
Remember(long oldWriteHead = stream->getWriteHead());
// directory information (description and 50 word record)
stream->write((char*)d->description, AMPX_NUCLIDE_DESCR_LENGTH);
stream->write((char*)d->words, sizeof(int)*AMPX_NUMBER_NUCLIDE_INTEGER_OPTIONS);
bool globalPresent = bondarenkoGlobalData != NULL;
stream->write((char*)&globalPresent, sizeof(globalPresent));
if( globalPresent ){
int rtncode = bondarenkoGlobalData->serialize(stream);
if( rtncode != 0) return rtncode;
}
bool totalXS2dPresent = totalXS != NULL;
stream->write((char*)&totalXS2dPresent, sizeof(totalXS2dPresent));
if( totalXS2dPresent ){
int rtncode = totalXS->serialize(stream);
if( rtncode != 0) return rtncode;
}
int bondarenkoCount = bondarenkoData.size();
stream->write((char*)&bondarenkoCount, sizeof(bondarenkoCount));
for( int i = 0; i < bondarenkoCount; i++){
int rtncode = bondarenkoData[i]->serialize(stream);
if( rtncode != 0 ) return rtncode;
}
int neutron1dCount = neutron1dData.size();
stream->write((char*)&neutron1dCount, sizeof(neutron1dCount));
for( int i = 0; i < neutron1dCount; i++){
int rtncode = neutron1dData[i]->serialize(stream);
if( rtncode != 0 ) return rtncode;
}
int gamma1dCount = gamma1dData.size();
stream->write((char*)&gamma1dCount, sizeof(gamma1dCount));
for( int i = 0; i < gamma1dCount; i++){
int rtncode = gamma1dData[i]->serialize(stream);
if( rtncode != 0 ) return rtncode;
}
int neutron2dCount = neutron2dData.size();
stream->write((char*)&neutron2dCount, sizeof(neutron2dCount));
for( int i = 0; i < neutron2dCount; i++){
int rtncode = neutron2dData[i]->serialize(stream);
if( rtncode != 0 ) return rtncode;
}
int gamma2dCount = gamma2dData.size();
stream->write((char*)&gamma2dCount, sizeof(gamma2dCount));
for( int i = 0; i < gamma2dCount; i++){
int rtncode = gamma2dData[i]->serialize(stream);
if( rtncode != 0 ) return rtncode;
}
int gammaProdCount = gammaProdData.size();
stream->write((char*)&gammaProdCount, sizeof(gammaProdCount));
for( int i = 0; i < gammaProdCount; i++){
int rtncode = gammaProdData[i]->serialize(stream);
if( rtncode != 0 ) return rtncode;
}
// subgroup data
bool subPresent = subGroups != NULL;
stream->write((char*)&subPresent, sizeof(subPresent));
if( subPresent ){
int rtncode = subGroups->serialize(stream);
if( rtncode != 0) return rtncode;
}
// DBC=4 - checksum the expected serialized size and the actual serialized size
Ensure( static_cast<unsigned long>(stream->getWriteHead() - oldWriteHead) == LibraryNuclide::getSerializedSize() );
return 0;
}
*/
/**
* @brief deserialize the object from the given AbstractStream
* @param AbstractStream * stream - the stream from which the object will be inflated
* @return int - 0 upon success, error otherwise
*/
/*
int LibraryNuclide::deserialize(Standard::AbstractStream * stream){
long read_uid = stream->getNextUID();
// make sure we know how to parse the object in the stream
if( read_uid != this->getUID() ) return Serializable::TypeMismatch;
// skip over uid
stream->ignore(sizeof(read_uid));
// read objects serialized size
unsigned long serializedSize;
stream->read((char*)&serializedSize, sizeof(serializedSize));
// need to make sure data is only owned by this object
qAtomicDetach(d);
// directory information (description and 50 word record)
stream->read((char*)d->description, AMPX_NUCLIDE_DESCR_LENGTH);
d->description[AMPX_NUCLIDE_DESCR_LENGTH] = '\0'; // null terminate the string
stream->read((char*)d->words, sizeof(int)*AMPX_NUMBER_NUCLIDE_INTEGER_OPTIONS);
bool globalPresent;
stream->read((char*)&globalPresent, sizeof(globalPresent));
if( globalPresent ){
if( !stream->isNext(BondarenkoGlobal::uid) ){
qDebug() << qPrintable("Failed to find BondarenkoGlobal data as the next object... ChildMistmatch error!");
return Serializable::ChildTypeMismatch;
}
Serializable * obj = stream->deserializeNext();
if( obj == NULL ){
qDebug() << qPrintable("Failed to deserialize the BondarenkoGlobal object!");
return Serializable::FailedObjectDeserialization;
}
bondarenkoGlobalData = (BondarenkoGlobal * ) obj;
}
bool totalXS2dPresent;
stream->read((char*)&totalXS2dPresent, sizeof(totalXS2dPresent));
if( totalXS2dPresent ){
if( !stream->isNext(CrossSection2d::uid) ){
qDebug() << qPrintable("Failed to find total XS2d data as the next object... ChildMistmatch error!");
return Serializable::ChildTypeMismatch;
}
Serializable * obj = stream->deserializeNext();
if( obj == NULL ){
qDebug() << qPrintable("Failed to deserialize the BondarenkoGlobal object!");
return Serializable::FailedObjectDeserialization;
}
totalXS = (CrossSection2d * ) obj;
}
int bondarenkoDataCount;
stream->read((char*)&bondarenkoDataCount, sizeof(bondarenkoDataCount));
for( int i = 0; i < bondarenkoDataCount; i++){
if( !stream->isNext(BondarenkoData::uid) ){
qDebug() << qPrintable("Failed to find bondarenkoData data as the next object... ChildMistmatch error!");
return Serializable::ChildTypeMismatch;
}
Serializable * obj = stream->deserializeNext();
if( obj == NULL ){
qDebug() << qPrintable("Failed to deserialize the next bondarenkoData object!");
return Serializable::FailedObjectDeserialization;
}
bondarenkoData.append((BondarenkoData * ) obj);
}
int neutron1dCount;
stream->read((char*)&neutron1dCount, sizeof(neutron1dCount));
for( int i = 0; i < neutron1dCount; i++){
if( !stream->isNext(CrossSection1d::uid) ){
qDebug() << qPrintable("Failed to find neutron1d data as the next object... ChildMistmatch error!");
return Serializable::ChildTypeMismatch;
}
Serializable * obj = stream->deserializeNext();
if( obj == NULL ){
qDebug() << qPrintable("Failed to deserialize the next neutron1d object!");
return Serializable::FailedObjectDeserialization;
}
neutron1dData.append((CrossSection1d * ) obj);
}
int gamma1dCount;
stream->read((char*)&gamma1dCount, sizeof(gamma1dCount));
for( int i = 0; i < gamma1dCount; i++){
if( !stream->isNext(CrossSection1d::uid) ){
qDebug() << qPrintable("Failed to find gamma1d data as the next object... ChildMistmatch error!");
return Serializable::ChildTypeMismatch;
}
Serializable * obj = stream->deserializeNext();
if( obj == NULL ){
qDebug() << qPrintable("Failed to deserialize the next gamma1d object!");
return Serializable::FailedObjectDeserialization;
}
gamma1dData.append((CrossSection1d * ) obj);
}
int neutron2dCount;
stream->read((char*)&neutron2dCount, sizeof(neutron2dCount));
for( int i = 0; i < neutron2dCount; i++){
if( !stream->isNext(CrossSection2d::uid) ){
qDebug() << qPrintable("Failed to find neutron2d data as the next object... ChildMistmatch error!");
return Serializable::ChildTypeMismatch;
}
Serializable * obj = stream->deserializeNext();
if( obj == NULL ){
qDebug() << qPrintable("Failed to deserialize the next neutron2d object!");
return Serializable::FailedObjectDeserialization;
}
neutron2dData.append((CrossSection2d * ) obj);
}
int gamma2dCount;
stream->read((char*)&gamma2dCount, sizeof(gamma2dCount));
for( int i = 0; i < gamma2dCount; i++){
if( !stream->isNext(CrossSection2d::uid) ){
qDebug() << qPrintable("Failed to find gamma2d data as the next object... ChildMistmatch error!");
return Serializable::ChildTypeMismatch;
}
Serializable * obj = stream->deserializeNext();
if( obj == NULL ){
qDebug() << qPrintable("Failed to deserialize the next gamma2d object!");
return Serializable::FailedObjectDeserialization;
}
gamma2dData.append((CrossSection2d * ) obj);
}
int gammaProdCount;
stream->read((char*)&gammaProdCount, sizeof(gammaProdCount)); for( int i = 0; i < gammaProdCount; i++){
if( !stream->isNext(CrossSection2d::uid) ){
qDebug() << qPrintable("Failed to find gammaProd data as the next object... ChildMistmatch error!");
return Serializable::ChildTypeMismatch;
}
Serializable * obj = stream->deserializeNext();
if( obj == NULL ){
qDebug() << qPrintable("Failed to deserialize the next gammaProd object!");
return Serializable::FailedObjectDeserialization;
}
gammaProdData.append((CrossSection2d * ) obj);
}
// subgroup data
bool subPresent;
stream->read((char*)&subPresent, sizeof(subPresent));
this->setSubGroupData(0);
if( subPresent) {
if( !stream->isNext(SubGroupData::uid) ){
qDebug() << qPrintable("Failed to find SubGroupData in the next object... ChildMistmatch error!");
return Serializable::ChildTypeMismatch;
}
Serializable * obj = stream->deserializeNext();
if( obj == NULL ){
qDebug() << qPrintable("Failed to deserialize the next SubGroupData object!");
return Serializable::FailedObjectDeserialization;
}
this->setSubGroupData( (SubGroupData*) obj);
}
return 0;
}
*/
/**
* @brief Obtain the size in bytes of this object when serialized
* @return unsigned long - the size in bytes of the object when serialized
*/
/*
unsigned long LibraryNuclide::getSerializedSize() const{
unsigned long size = 0;
// directory information (description and 50 word record)
size = AMPX_NUCLIDE_DESCR_LENGTH + sizeof(int)*AMPX_NUMBER_NUCLIDE_INTEGER_OPTIONS;
// bondarenko Global data
bool globalPresent = bondarenkoGlobalData != NULL;
size += sizeof(globalPresent);
if( globalPresent ){
unsigned long serialized = bondarenkoGlobalData->getSerializedSize();
size += serialized;
size += sizeof(bondarenkoGlobalData->getUID());
size += sizeof(serialized);
}
// totalXS2d data
bool totalXS2dPresent = totalXS != NULL;
size += sizeof(totalXS2dPresent);
if( totalXS2dPresent ){
unsigned long serialized = totalXS->getSerializedSize();
size += serialized;
size += sizeof(totalXS->getUID());
size += sizeof(serialized);
}
// bondarenko data
size += sizeof(bondarenkoData.size());
for( int i = 0; i < bondarenkoData.size(); i++){
size += sizeof(bondarenkoData[i]->getUID());
unsigned long serialized = bondarenkoData[i]->getSerializedSize();
size += serialized;
size += sizeof(serialized);
}
// neutron1d data
size += sizeof(neutron1dData.size());
for( int i = 0; i < neutron1dData.size(); i++){
size += sizeof(neutron1dData[i]->getUID());
unsigned long serialized = neutron1dData[i]->getSerializedSize();
size += serialized;
size += sizeof(serialized);
}
// gamma1d data
size += sizeof(gamma1dData.size());
for( int i = 0; i < gamma1dData.size(); i++){
size += sizeof(gamma1dData[i]->getUID());
unsigned long serialized = gamma1dData[i]->getSerializedSize();
size += serialized;
size += sizeof(serialized);
}
// neutron2d data
size += sizeof(neutron2dData.size());
for( int i = 0; i < neutron2dData.size(); i++){
size += sizeof(neutron2dData[i]->getUID());
unsigned long serialized = neutron2dData[i]->getSerializedSize();
size += serialized;
size += sizeof(serialized);
}
// gamma2d data
size += sizeof(gamma2dData.size());
for( int i = 0; i < gamma2dData.size(); i++){
size += sizeof(gamma2dData[i]->getUID());
unsigned long serialized = gamma2dData[i]->getSerializedSize();
size += serialized;
size += sizeof(serialized);
}
// gammaProd data
size += sizeof(gammaProdData.size());
for( int i = 0; i < gammaProdData.size(); i++){
size += sizeof(gammaProdData[i]->getUID());
unsigned long serialized = gammaProdData[i]->getSerializedSize();
size += serialized;
size += sizeof(serialized);
}
// subgroup data
bool subPresent = subGroups != NULL;
size += sizeof(subPresent);
if( subPresent ){
unsigned long serialized = subGroups->getSerializedSize();
size += serialized;
size += sizeof(subGroups->getUID());
size += sizeof(serialized);
}
return size;
}
*/
/**
* @brief Obtain the universal version identifier
* the uid should be unique for all Serializable objects such that
* an object factory can retrieve prototypes of the desired Serializable
* object and inflate the serial object into a manageable object
* @return long - the uid of the object
*/
long LibraryNuclide::getUID() const{
return LibraryNuclide::uid;
}
| [
"[email protected]"
] | |
c7aa03e6bcb7c348e9030cd1855739421ea63ac0 | 256c1e63fbe6454146d6bc9655415d43c52bf13c | /AdvancedLevel/1120FriendNumbers.cpp | 66628142723a173cb3ac0871497b43124d565a89 | [] | no_license | czyxm/PAT | c7d5a752d5fc0856da14b907a3c3b99397dd5dd6 | 0951d9a5c9bd8bd3e102f2f3772fc16e8a2b846c | refs/heads/master | 2021-06-17T19:38:34.202686 | 2021-04-19T12:56:06 | 2021-04-19T12:56:06 | 195,560,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 726 | cpp | #include<bits/stdc++.h>
using namespace std;
int id(const string & str)
{
int sum = 0;
for (int i = 0; i < str.size(); i++)
{
sum += str[i] - '0';
}
return sum;
}
int main()
{
int N, M = 0, sum;
bool friendID[37] = {false};
string str;
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> str;
sum = id(str);
if (!friendID[sum])
{
M++;
}
friendID[sum] = true;
}
cout << M << endl;
for (int i = 0; i < 37; i++)
{
if (friendID[i])
{
cout << i;
if (--M != 0)
{
cout << " ";
}
}
}
cout << endl;
return 0;
} | [
"[email protected]"
] | |
b9ab5a662771667d0863796a3ba069f6571f4bf2 | 67da5d92d6df5761e7d7556813dcdbcb19b9927d | /tables/openbsm/src/openbsmservice.cpp | ad9410080d0a7db258a46ce7c93ac048a792db79 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | hamzashahzad1/try-workflow | 5263918c7b037edcf9117ede7602731a6d2cebb4 | 8172465fffc648e37037fe8e823529f5d43c2011 | refs/heads/master | 2023-06-11T02:04:18.668848 | 2021-07-05T16:14:10 | 2021-07-05T16:14:10 | 382,877,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,753 | cpp | #include "openbsmservice.h"
#include "socketeventstableplugin.h"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <thread>
#include <zeek/iopenbsmconsumer.h>
#include <zeek/openbsmservicefactory.h>
namespace zeek {
namespace {
const std::string kServiceName{"openbsm"};
} // namespace
struct OpenbsmService::PrivateData final {
PrivateData(IVirtualDatabase &virtual_database_,
IZeekConfiguration &configuration_, IZeekLogger &logger_)
: virtual_database(virtual_database_), configuration(configuration_),
logger(logger_) {}
IVirtualDatabase &virtual_database;
IZeekConfiguration &configuration;
IZeekLogger &logger;
IOpenbsmConsumer::Ref openbsm_consumer;
IVirtualTable::Ref socket_events_table;
};
OpenbsmService::~OpenbsmService() {
if (d->socket_events_table) {
auto status =
d->virtual_database.unregisterTable(d->socket_events_table->name());
assert(status.succeeded() &&
"Failed to unregister the socket_events table");
}
}
const std::string &OpenbsmService::name() const { return kServiceName; }
Status OpenbsmService::exec(std::atomic_bool &terminate) {
while (!terminate) {
if (!d->socket_events_table) {
d->logger.logMessage(IZeekLogger::Severity::Information,
"Table(s) not created yet, sleeping for 1 second");
std::this_thread::sleep_for(std::chrono::seconds(1U));
continue;
}
auto &socket_events_table_impl =
*static_cast<SocketEventsTablePlugin *>(d->socket_events_table.get());
IOpenbsmConsumer::EventList event_list;
d->openbsm_consumer->getEvents(event_list);
if (event_list.empty()) {
continue;
}
auto status = socket_events_table_impl.processEvents(event_list);
if (!status.succeeded()) {
d->logger.logMessage(
IZeekLogger::Severity::Error,
"The socket_events table failed to process some events: " +
status.message());
}
}
return Status::success();
}
OpenbsmService::OpenbsmService(IVirtualDatabase &virtual_database,
IZeekConfiguration &configuration,
IZeekLogger &logger)
: d(new PrivateData(virtual_database, configuration, logger)) {
auto status =
IOpenbsmConsumer::create(d->openbsm_consumer, logger, configuration);
if (!status.succeeded()) {
d->logger.logMessage(IZeekLogger::Severity::Error,
"Failed to connect to the Openbsm API. The "
"socket_events tables will not be enabled. Error: " +
status.message());
return;
}
status = SocketEventsTablePlugin::create(d->socket_events_table,
configuration, logger);
if (!status.succeeded()) {
throw status;
}
status = d->virtual_database.registerTable(d->socket_events_table);
if (!status.succeeded()) {
throw status;
}
}
struct OpenbsmServiceFactory::PrivateData final {
PrivateData(IVirtualDatabase &virtual_database_,
IZeekConfiguration &configuration_, IZeekLogger &logger_)
: virtual_database(virtual_database_), configuration(configuration_),
logger(logger_) {}
IVirtualDatabase &virtual_database;
IZeekConfiguration &configuration;
IZeekLogger &logger;
};
Status OpenbsmServiceFactory::create(Ref &obj,
IVirtualDatabase &virtual_database,
IZeekConfiguration &configuration,
IZeekLogger &logger) {
obj.reset();
try {
auto ptr =
new OpenbsmServiceFactory(virtual_database, configuration, logger);
obj.reset(ptr);
return Status::success();
} catch (const std::bad_alloc &) {
return Status::failure("Memory allocation failure");
} catch (const Status &status) {
return status;
}
}
OpenbsmServiceFactory::~OpenbsmServiceFactory() {}
const std::string &OpenbsmServiceFactory::name() const { return kServiceName; }
Status OpenbsmServiceFactory::spawn(IZeekService::Ref &obj) {
obj.reset();
try {
obj.reset(
new OpenbsmService(d->virtual_database, d->configuration, d->logger));
return Status::success();
} catch (const std::bad_alloc &) {
return Status::failure("Memory allocation failure");
} catch (const Status &status) {
return status;
}
}
OpenbsmServiceFactory::OpenbsmServiceFactory(IVirtualDatabase &virtual_database,
IZeekConfiguration &configuration,
IZeekLogger &logger)
: d(new PrivateData(virtual_database, configuration, logger)) {}
} // namespace zeek
| [
"[email protected]"
] | |
2287db9bf1fac4b826a19a70fcbd79a87bb535b5 | af6a65756993e5ecb3c2997fccf75e879c1c2fcf | /ChickenGame/ChickenGame/GameOverState.cpp | 5ec3e3dd89e7a1d0b171763d079ca0f2b67c268b | [] | no_license | PaddyReid/Cormac | 6637ce2f2bdc14b9cde3917bc33be3405b2f1c62 | d312f2d771a60c472a94d0a5afb4e2a87fbf39c9 | refs/heads/master | 2021-08-28T09:23:25.905120 | 2017-11-29T12:24:41 | 2017-11-29T12:24:41 | 113,905,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,492 | cpp | #include "GameOverState.hpp"
#include "Utility.hpp"
#include "Player.hpp"
#include "ResourceHolder.hpp"
#include <SFML/Graphics/RectangleShape.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/View.hpp>
GameOverState::GameOverState(StateStack& stack, Context context)
: State(stack, context)
, mGameOverText()
, mElapsedTime(sf::Time::Zero)
{
sf::Font& font = context.fonts->get(Fonts::Main);
sf::Vector2f windowSize(context.window->getSize());
mGameOverText.setFont(font);
if (context.player->getMissionStatus() == Player::MissionFailure)
mGameOverText.setString("Mission failed!");
else
mGameOverText.setString("Mission successful!");
mGameOverText.setCharacterSize(70);
centerOrigin(mGameOverText);
mGameOverText.setPosition(0.5f * windowSize.x, 0.4f * windowSize.y);
}
void GameOverState::draw()
{
sf::RenderWindow& window = *getContext().window;
window.setView(window.getDefaultView());
// Create dark, semitransparent background
sf::RectangleShape backgroundShape;
backgroundShape.setFillColor(sf::Color(0, 0, 0, 150));
backgroundShape.setSize(window.getView().getSize());
window.draw(backgroundShape);
window.draw(mGameOverText);
}
bool GameOverState::update(sf::Time dt)
{
// Show state for 3 seconds, after return to menu
mElapsedTime += dt;
if (mElapsedTime > sf::seconds(3))
{
requestStackClear();
requestStackPush(States::Menu);
}
return false;
}
bool GameOverState::handleEvent(const sf::Event&)
{
return false;
}
| [
"[email protected]"
] | |
9897be0a3108476dadb63ea9bda70e639532aa08 | e5dad8e72f6c89011ae030f8076ac25c365f0b5f | /caret_command_operations/CommandSurfaceBorderToMetric.h | b74bbfddddac1c748be24834c612f15fc1775eb3 | [] | no_license | djsperka/caret | f9a99dc5b88c4ab25edf8b1aa557fe51588c2652 | 153f8e334e0cbe37d14f78c52c935c074b796370 | refs/heads/master | 2023-07-15T19:34:16.565767 | 2020-03-07T00:29:29 | 2020-03-07T00:29:29 | 122,994,146 | 0 | 1 | null | 2018-02-26T16:06:03 | 2018-02-26T16:06:03 | null | UTF-8 | C++ | false | false | 1,805 | h |
#ifndef __COMMAND_SURFACE_BORDER_TO_METRIC_H__
#define __COMMAND_SURFACE_BORDER_TO_METRIC_H__
/*LICENSE_START*/
/*
* Copyright 1995-2002 Washington University School of Medicine
*
* http://brainmap.wustl.edu
*
* This file is part of CARET.
*
* CARET is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* CARET is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CARET; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*LICENSE_END*/
#include "CommandBase.h"
/// class for
class CommandSurfaceBorderToMetric : public CommandBase {
public:
// constructor
CommandSurfaceBorderToMetric();
// destructor
~CommandSurfaceBorderToMetric();
// get full help information
QString getHelpInformation() const;
// get the script builder parameters
virtual void getScriptBuilderParameters(ScriptBuilderParameters& paramsOut) const;
protected:
// execute the command
void executeCommand() throw (BrainModelAlgorithmException,
CommandException,
FileException,
ProgramParametersException,
StatisticException);
};
#endif // __COMMAND_SURFACE_BORDER_TO_METRIC_H__
| [
"[email protected]"
] | |
4d032445d45678c4039d21ad87fd717fe9c04eeb | 957ba9d83a8294e3ae225e1bb62e2f32d6c7b49d | /Week6/CMP105App/Gravball.h | 34768e617dd4b352230567eaab4c30f66b9c29e7 | [] | no_license | StuartMorrison/CMP105_W6 | dce351803e702a0f0396ca9c591ebd5ca4840a86 | a6da0f9301bfc244844882b19ddeb993890ab11e | refs/heads/master | 2021-01-07T05:15:20.832815 | 2020-02-20T12:24:37 | 2020-02-20T12:24:37 | 241,589,446 | 0 | 0 | null | 2020-02-19T10:07:54 | 2020-02-19T10:07:53 | null | UTF-8 | C++ | false | false | 374 | h | #pragma once
#include "Framework/GameObject.h"
class Gravball :
public GameObject
{
public:
float scale;
int isJumping;
sf::Vector2f gravity;
sf::Vector2f stepVelocity;
sf::Vector2f jumpVector;
sf::RenderWindow* window;
Gravball();
void handleInput(float dt);
void update(float dt);
void setWindu(sf::RenderWindow* hwnd) { window = hwnd; };
~Gravball();
};
| [
"[email protected]"
] | |
85ef1f3b94eb67350a184583c1ae4d3e38a7c4bf | 7010579ef5c8483e98f6344d51d350dabab7c9d4 | /Source/CatchMe/Luautils.h | 19c6525eda9a9b3bf71f653bcf865cb6cd518ff7 | [] | no_license | ik3210/CM | 4b18f5993e101ca850e0643f6ac692073b311775 | 72371cb15dd9fa48f9c47f7e28ef6e3a2588b91c | refs/heads/master | 2021-06-19T18:45:30.272872 | 2017-07-02T14:45:51 | 2017-07-02T14:45:51 | 100,611,197 | 1 | 0 | null | 2017-08-17T14:17:42 | 2017-08-17T14:17:42 | null | UTF-8 | C++ | false | false | 1,490 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Kismet/BlueprintFunctionLibrary.h"
#include "Luautils.generated.h"
USTRUCT(meta=(Lua=1))
struct FReplifetimeCond {
GENERATED_USTRUCT_BODY()
UPROPERTY()
FString PropertyName;
UPROPERTY()
TEnumAsByte<ELifetimeCondition> Cond;
};
UCLASS(meta=(lua=1))
class ULuautils : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION()
static UWorld* GetWorld1(AActor *obj);
UFUNCTION()
static void SetupAttachment(USceneComponent* Child, USceneComponent* InParent, FName InSocketName = NAME_None);
UFUNCTION()
static void GetPlayerViewPoint(APlayerController* controler, FVector& out_Location, FRotator& out_Rotation);
UFUNCTION()
static FRotator GetViewRotation(APawn* pawn);
UFUNCTION()
static FVector VRandCone(FRandomStream stream, FVector const& Dir, float HorizontalConeHalfAngleRad, float VerticalConeHalfAngleRad);
UFUNCTION()
static FVector2D FVector2D_New(float InX =0, float InY =0);
UFUNCTION(BlueprintCallable, Category = "luautils")
static FColor FColor_New(uint8 InR = 0, uint8 InG = 0, uint8 InB = 0, uint8 InA = 255);
UFUNCTION()
static void GetAllWidgets(UUserWidget* UserWidget, TArray<FName>& Names, TArray<UWidget*>& Widgets, TArray<FName>&TypesOfWidget);
UFUNCTION()
static void log(FString content);
UFUNCTION()
static FString GetName(UObject* p);
UFUNCTION()
static void UpdateNav(UActorComponent *Component);
};
| [
"[email protected]"
] | |
3e992014f24ea059b9f9be18e90b1a99ac1b85ea | 13dafbe0e33771bd24496637a761c4703fb0beb4 | /Codeforces/ShichikujiAndPowerGrid.cpp | 5a8f432032b7b721699ee2de8e0512443d38ca54 | [] | no_license | Owmicron/CPStuff | 121d498b2418141fa45d27fcbfa0a1fd851a4293 | 436f3234ed2f2930b13169f30428ded5da557b75 | refs/heads/master | 2022-12-30T06:43:18.425735 | 2020-10-20T12:21:59 | 2020-10-20T12:21:59 | 258,448,760 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,837 | cpp | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
#pragma comment(linker, "/stack:200000000")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef string str;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector <pii> vpii;
typedef vector <pll> vpll;
typedef map <str,int> mapsi;
typedef map <str,int> :: iterator mapsitr;
typedef map <int , int> mint;
typedef map <ll , ll> mll;
typedef set <int> si;
typedef set <ll> sll;
typedef si :: iterator sitr;
typedef si :: reverse_iterator rsitr;
typedef sll :: iterator sltr;
typedef sll :: reverse_iterator rsltr;
#define mset multiset
typedef mset <int> msi;
typedef mset <ll> msll;
typedef msi :: iterator msitr;
typedef msi :: reverse_iterator msritr;
typedef msll :: iterator msltr;
typedef msll :: reverse_iterator mslritr;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define mp make_pair
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front
#define fi first
#define se second
#define fs first.second
#define ss second.second
#define ff first.first
#define sf second.first
#define newl '\n'
#define fbo find_by_order
#define ook order_of_key
char to_upper (char x){
if( 97 <= int(x) && int(x) <= 122)return char(x-32);
else if( 65 <= int(x) && int(x) <= 90)return x;
}
char to_lower (char x){
if( 97 <= int(x) && int(x) <= 122)return x;
else if( 65 <= int(x) && int(x) <= 90)return char(x+32);
}
int numerize (char x){
if(48 <= int(x) && int(x) <= 57)return int(x-'0');
else if( 97 <= int(x) && int(x) <= 122)return int(x-96);
else if( 65 <= int(x) && int(x) <= 90)return int(x-64);
}
bool isect (int l1, int r1, int l2, int r2){
pii p1,p2;
p1 = mp(l1,r1); p2 = mp(l2,r2);
if(p1>p2)swap(p1,p2);
if(p2.fi <= p1.se)return true;
else return false;
}
ll quickpow (ll num1, ll num2, ll MOD){
if(num2==0)return 1;
else if(num2==1)return num1;
else{
ll temp = quickpow (num1,num2/2,MOD); ll res = ((temp%MOD) * (temp%MOD))%MOD;
if(num2%2==1) res = ((res%MOD)*(num1%MOD))%MOD; return res;
}
}
ll invmod (ll num, ll MOD){return quickpow (num,MOD-2,MOD);}
ll gcd (ll num1, ll num2){
if(num1 < num2) swap(num1,num2); ll num3 = num1 % num2 ;
while(num3 > 0){ num1 = num2; num2 = num3; num3 = num1 % num2;}
return num2;
}
ll lcm (ll num1 , ll num2){return (ll) (num1/__gcd(num1,num2))*num2;}
// end of Template
ll n,x[3000],y[3000],c[3000],k[3000],par[3000];
vector < pair < ll , pll> > v;
bool lit[3000];
int findrep(int x){
if(par[x] == x) return x;
else{
par[x] = findrep(par[x]);
return par[x];
}
}
void join(int a, int b){
int repa = findrep(a);
int repb = findrep(b);
par[repb] = repa;
}
ll sum;
vll power;
vpll conn;
int main(){
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
// cout.tie(NULL);
cin>>n;
for(int i=1;i<=n;i++){
cin>>x[i]>>y[i];
}
for(int i=1;i<=n;i++){
cin>>c[i];
v.pb (mp (c[i],mp(i,i)));
}
for(int i=1;i<=n;i++) cin>>k[i];
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j) continue;
ll cost = (k[i]+k[j]) * (abs(x[i]-x[j]) + abs(y[i]-y[j]));
v.pb (mp(cost,mp(i,j)));
}
}
for(int i=1;i<=n;i++){
par[i] = i;
}
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++){
ll cost = v[i].fi;
ll l = v[i].sf;
ll r = v[i].ss;
ll a = findrep(l);
ll b = findrep(r);
if(l==r){
if(!lit[a]){
lit[a] = true;
sum += cost;
power.pb(l);
}
}
else{
if(a==b) continue;
if(lit[a]&&lit[b]) continue;
else if(lit[a] && !lit[b]){
conn.pb(mp(l,r));
join(a,b);
sum += cost;
}
else if(lit[b] && !lit[a]){
conn.pb(mp(l,r));
join(b,a);
sum += cost;
}
else{
conn.pb(mp(l,r));
join(a,b);
sum += cost;
}
}
}
cout<<sum<<newl;
cout<<power.size()<<newl;
for(int i=0;i<power.size();i++) cout<<power[i]<<" ";cout<<newl;
cout<<conn.size()<<newl;
for(int i=0;i<conn.size();i++) cout<<conn[i].fi<<" "<<conn[i].se<<newl;
}
| [
"[email protected]"
] | |
0eab640b45134006987337db51e33b72b5e044e9 | 1256b4c60f65ecb4a2d047dd46cc159eb39a2033 | /tests/SolARTest_ModuleOpenCV_FeatureMatchingStabilization/main.cpp | 61299e7e404e9470b0a5498eeb584269bfce858b | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | SolarFramework/SolARModuleOpenCV | 886c20c3e7217b8b1c05a7663ae4626e468dd558 | 9684c9ecd9283843d87020f4ac4da675e9406458 | refs/heads/master | 2023-08-10T23:19:29.778146 | 2023-07-20T13:42:58 | 2023-07-20T13:42:58 | 119,406,923 | 5 | 6 | Apache-2.0 | 2023-06-28T13:24:53 | 2018-01-29T16:13:43 | C++ | UTF-8 | C++ | false | false | 4,264 | cpp | /**
* @copyright Copyright (c) 2017 B-com http://www.b-com.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "xpcf/xpcf.h"
#include "api/input/devices/ICamera.h"
#include "api/features/IKeypointDetector.h"
#include "api/display/IImageViewer.h"
#include "api/display/IMatchesOverlay.h"
#include "api/display/I2DOverlay.h"
#include "api/features/IDescriptorMatcher.h"
#include "api/features/IDescriptorsExtractor.h"
#include "api/features/IMatchesFilter.h"
#include "core/Log.h"
#include <iostream>
#include <boost/log/core.hpp>
#include <string>
#include <vector>
using namespace SolAR;
using namespace SolAR::datastructure;
using namespace SolAR::api;
namespace xpcf = org::bcom::xpcf;
int main(int argc,char** argv)
{
#if NDEBUG
boost::log::core::get()->set_logging_enabled(false);
#endif
LOG_ADD_LOG_TO_CONSOLE();
/* instantiate component manager*/
/* this is needed in dynamic mode */
SRef<xpcf::IComponentManager> xpcfComponentManager = xpcf::getComponentManagerInstance();
if(xpcfComponentManager->load("SolARTest_ModuleOpenCV_FeatureMatchingStabilization_conf.xml")!=org::bcom::xpcf::_SUCCESS)
{
LOG_ERROR("Failed to load the configuration file SolARTest_ModuleOpenCV_FeatureMatchingStabilization_conf.xml")
return -1;
}
// declare and create components
LOG_INFO("Start creating components");
auto camera = xpcfComponentManager->resolve<input::devices::ICamera>();
auto detector = xpcfComponentManager->resolve<features::IKeypointDetector>();
auto extractor = xpcfComponentManager->resolve<features::IDescriptorsExtractor>();
auto matcher = xpcfComponentManager->resolve<features::IDescriptorMatcher>();
auto matchesFilter = xpcfComponentManager->resolve<features::IMatchesFilter>();
auto overlayMatches = xpcfComponentManager->resolve<display::IMatchesOverlay>();
auto overlay2D = xpcfComponentManager->resolve<display::I2DOverlay>();
auto viewer = xpcfComponentManager->resolve<display::IImageViewer>();
LOG_INFO("All components created!");
// Open camera
if (camera->start() != FrameworkReturnCode::_SUCCESS) {
LOG_ERROR("Camera cannot start");
return -1;
}
// check feature matching stabilization
SRef<Frame> frame1;
bool bInitFirstFrame(false);
for (;;) {
SRef<Image> image, imageDisplay;
if (camera->getNextImage(image) != FrameworkReturnCode::_SUCCESS) {
LOG_INFO("Error load image");
return 0;
}
imageDisplay = image->copy();
std::vector<Keypoint> keypoints;
SRef<DescriptorBuffer> descriptors;
std::vector<DescriptorMatch> matches;
// feature detection
detector->detect(image, keypoints);
// feature extraction
extractor->extract(image, keypoints, descriptors);
// make a frame
SRef<Frame> frame = xpcf::utils::make_shared<Frame>(keypoints, descriptors, image);
if (!bInitFirstFrame) {
LOG_INFO("Number of keypoints of the first frame: {}", keypoints.size());
frame1 = frame;
bInitFirstFrame = true;
continue;
}
LOG_INFO("Number of keypoints: {}", keypoints.size());
// feature matching
matcher->match(descriptors, frame1->getDescriptors(), matches);
LOG_INFO("Number of matches: {}", matches.size());
// matches filter
matchesFilter->filter(matches, matches, keypoints, frame1->getKeypoints());
LOG_INFO("Number of filtered matches: {}\n", matches.size());
if (matches.size() < 600) {
frame1 = frame;
continue;
}
// draw keypoints and matches
overlayMatches->draw(image, imageDisplay, keypoints, frame1->getKeypoints(), matches);
overlay2D->drawCircles(keypoints, imageDisplay);
// display
if (viewer->display(imageDisplay) == FrameworkReturnCode::_STOP)
break;
}
return 0;
}
| [
"[email protected]"
] | |
fbca35e588389aff49856bd02e9a2237e3636127 | bcf138c82fcba9acc7d7ce4d3a92618b06ebe7c7 | /gta5/0xA46B73FAA3460AE1.cpp | 44497da24471eff1a366c71db1397d7d2d54d361 | [] | no_license | DeepWolf413/additional-native-data | aded47e042f0feb30057e753910e0884c44121a0 | e015b2500b52065252ffbe3c53865fe3cdd3e06c | refs/heads/main | 2023-07-10T00:19:54.416083 | 2021-08-12T16:00:12 | 2021-08-12T16:00:12 | 395,340,507 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | cpp | // fm_mission_controller.ysc @ L317516
void func_4366()
{
if (MISC::ARE_STRINGS_EQUAL(sLocal_16440, "MPH_PAC_FIN_MCS1") && MISC::IS_BIT_SET(bLocal_14844, 25))
{
func_4367(0);
}
if (MISC::ARE_STRINGS_EQUAL(sLocal_16440, "MPH_NAR_FIN_EXT"))
{
MISC::WATER_OVERRIDE_SET_STRENGTH(0f);
GRAPHICS::_0x649C97D52332341A(1);
}
if (MISC::ARE_STRINGS_EQUAL(sLocal_16440, "MPH_PAC_WIT_MCS1"))
{
MISC::WATER_OVERRIDE_SET_STRENGTH(0f);
HUD::DISPLAY_HUD(true);
}
if (MISC::ARE_STRINGS_EQUAL(sLocal_16440, "MPH_PAC_FIN_EXT"))
{
GRAPHICS::_0xA46B73FAA3460AE1(false);
MISC::CLEAR_BIT(&bLocal_14842, 8);
}
if (INTERIOR::IS_VALID_INTERIOR(iLocal_14791))
{
INTERIOR::UNPIN_INTERIOR(iLocal_14791);
}
if (MISC::ARE_STRINGS_EQUAL(sLocal_16440, "MPH_PRI_BUS_EXT"))
{
AUDIO::DISTANT_COP_CAR_SIRENS(true);
}
} | [
"[email protected]"
] | |
7737acbdd6ac773b6041aec2fd9ff6743824558e | 31a5a5577440049a12af6848d17a6038b73d13ae | /Choco/io_tcp_socket.cpp | cf254237e21eac91c01776334c8574775e5649c0 | [] | no_license | jimmy486/Choco | 5d28fbb4fb11834afc4da33c8cca6602d39856fa | 29c1c9a93a065bcd396704a21336eae38439f33b | refs/heads/master | 2021-01-18T16:56:07.254801 | 2014-07-19T16:56:56 | 2014-07-19T16:57:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,513 | cpp | #ifdef DEPRECATED
#include "io_tcp_socket.h"
#include "io_errno.h"
#include "common_errno.h"
#include <WinSock2.h>
#include <Windows.h>
#include <mswsock.h>
using namespace std;
namespace Choco{
namespace IO{
struct TCPSocketData{
SOCKET socket;
SOCKADDR_IN local, remote;
OvData ov;
};
TCPSocket::TCPSocket() :
sock(nullptr),
inbuf(nullptr), inbufSize(0){
}
TCPSocket::~TCPSocket(){
}
int TCPSocket::initialize(){
sock = new(nothrow) TCPSocketData();
if( sock == nullptr )
return AllocationError;
sock->socket =
socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if( sock->socket == INVALID_SOCKET )
return SocketError;
int val = 0;
setsockopt(
sock->socket,
SOL_SOCKET, SO_SNDBUF,
(char *)&val, sizeof(val));
setsockopt(
sock->socket,
SOL_SOCKET, SO_RCVBUF,
(char *)&val, sizeof(val));
memset( &sock->ov,0, sizeof(OVERLAPPED) );
sock->ov.socket = this;
return 0;
}
int TCPSocket::initialize(char *_inbuf,int _inbufSize){
int ret = 0;
ret = initialize();
inbuf = _inbuf;
inbufSize = _inbufSize;
return ret;
}
void TCPSocket::quit(){
if( sock == nullptr )
return;
if( sock->socket != INVALID_SOCKET )
closesocket( sock->socket );
delete sock;
}
int TCPSocket::write(char *data,int len, int flags){
WSABUF buf;
DWORD written;
buf.buf = data;
buf.len = len;
sock->ov.action = Write;
WSASend(
sock->socket,
&buf, 1, &written, flags,
nullptr, nullptr);
return 0;
}
int TCPSocket::read(char *data,int len, int flags){
WSABUF buf;
DWORD written;
buf.buf = inbuf;
buf.len = inbufSize;
sock->ov.action = Read;
return WSARecv(
sock->socket,
&buf, 1, &written, (DWORD*)&flags,
&sock->ov, nullptr);
}
int TCPSocket::read(int flags){
return read(
inbuf, inbufSize,
flags);
}
void TCPSocket::reset(SOCKET acceptSocket){
TransmitFile(
sock->socket, nullptr, 0, 0,
(OVERLAPPED*)&sock->ov, nullptr,
TF_DISCONNECT | TF_REUSE_SOCKET);
sock->ov.action = Accept;
BOOL ret;
ret = AcceptEx(
acceptSocket,
sock->socket,
inbuf, 0,
sizeof(SOCKADDR_IN) + 16, sizeof(SOCKADDR_IN) + 16,
nullptr, &sock->ov);
}
SOCKET TCPSocket::getSocket(){
return sock->socket;
}
char *TCPSocket::getBuffer(){
return inbuf;
}
int TCPSocket::getBufferSize(){
return inbufSize;
}
SOCKADDR_IN &TCPSocket::getLocalAddr(){
return sock->local;
}
SOCKADDR_IN &TCPSocket::getRemoteAddr(){
return sock->remote;
}
}
};
#endif //DEPRECATED | [
"[email protected]"
] | |
530315e64f512eaec65c1465a51fc794b07d5daa | c8ef491a438a00fe5c1b6ef2dded0c032074f5a6 | /src/platforms/autosar-swc/mindroid/os/SystemClock.cpp | 6314b02d51ede3edde4d86671c3d0ab20ae8468c | [] | no_license | ogsts/Mindroid.ecpp | 38ab13825f3a1ea2c0ab37673b476e75944cec76 | 45c59d83da043e26ebafdcf48220e9120623a915 | refs/heads/master | 2020-12-25T09:37:34.246509 | 2016-05-04T12:05:24 | 2016-05-04T12:05:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | cpp | /*
* Copyright (C) 2011 Daniel Himmelein
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mindroid/os/SystemClock.h"
#include "mindroid/util/concurrent/locks/Lock.h"
namespace mindroid {
uint64_t SystemClock::sMonotonicTime = 0;
uint64_t SystemClock::monotonicTime() {
AutoLock autoLock;
return sMonotonicTime;
}
uint64_t SystemClock::realTime() {
return monotonicTime();
}
void SystemClock::tick(uint32_t duration) {
AutoLock autoLock;
sMonotonicTime += duration;
}
} /* namespace mindroid */
| [
"[email protected]"
] | |
070da6cda459accc515fe2b6425018e4d79c2cd8 | 42f1787ee34a6dedb0371e40f308e0d7ef6f91ce | /Projects/Parser/lexer.cc | c728ea87e4178820a14158e33ab52a677a545bf9 | [] | no_license | KaranKumar3/Personal-Repository | 5f50e43bae94c763e561fa1cc22188a363a82b68 | 682382396670833f4f03712efc349f763992b872 | refs/heads/master | 2020-03-22T00:50:30.669304 | 2020-02-17T18:23:22 | 2020-02-17T18:23:22 | 139,268,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,366 | cc | /*
* Copyright (C) Rida Bazzi, 2016
*
* Do not share this file with anyone
*/
#include <iostream>
#include <istream>
#include <vector>
#include <string>
#include <cctype>
#include "lexer.h"
#include "inputbuf.h"
using namespace std;
string reserved[] = { "END_OF_FILE",
"PUBLIC", "PRIVATE",
"EQUAL", "COLON", "COMMA", "SEMICOLON",
"LBRAC", "RBRAC", "ID", "ERROR"
};
#define KEYWORDS_COUNT 2
string keyword[] = { "public", "private" };
void Token::Print()
{
cout << "{" << this->lexeme << " , "
<< reserved[(int) this->token_type] << " , "
<< this->line_no << "}\n";
}
LexicalAnalyzer::LexicalAnalyzer()
{
this->line_no = 1;
tmp.lexeme = "";
tmp.line_no = 1;
tmp.token_type = ERROR;
}
bool LexicalAnalyzer::SkipSpace()
{
char c;
bool space_encountered = false;
input.GetChar(c);
line_no += (c == '\n');
while (!input.EndOfInput() && isspace(c)) {
space_encountered = true;
input.GetChar(c);
line_no += (c == '\n');
}
if (!input.EndOfInput()) {
input.UngetChar(c);
}
return space_encountered;
}
void LexicalAnalyzer::SkipComment() {
char c;
input.GetChar(c);
while (c == '/') {
while (c != '\n' && !input.EndOfInput()) input.GetChar(c);
SkipSpace();
input.GetChar(c);
}
//once here, we've skipped comments
}
bool LexicalAnalyzer::IsKeyword(string s)
{
for (int i = 0; i < KEYWORDS_COUNT; i++) {
if (s == keyword[i]) {
return true;
}
}
return false;
}
TokenType LexicalAnalyzer::FindKeywordIndex(string s)
{
for (int i = 0; i < KEYWORDS_COUNT; i++) {
if (s == keyword[i]) {
return (TokenType) (i + 1);
}
}
return ERROR;
}
Token LexicalAnalyzer::ScanIdOrKeyword()
{
char c;
input.GetChar(c);
if (isalpha(c)) {
tmp.lexeme = "";
while (!input.EndOfInput() && isalnum(c)) {
tmp.lexeme += c;
input.GetChar(c);
}
if (!input.EndOfInput()) {
input.UngetChar(c);
}
tmp.line_no = line_no;
if (IsKeyword(tmp.lexeme))
tmp.token_type = FindKeywordIndex(tmp.lexeme);
else
tmp.token_type = ID;
} else {
if (!input.EndOfInput()) {
input.UngetChar(c);
}
tmp.lexeme = "";
tmp.token_type = ERROR;
}
return tmp;
}
// you should unget tokens in the reverse order in which they
// are obtained. If you execute
//
// t1 = lexer.GetToken();
// t2 = lexer.GetToken();
// t3 = lexer.GetToken();
//
// in this order, you should execute
//
// lexer.UngetToken(t3);
// lexer.UngetToken(t2);
// lexer.UngetToken(t1);
//
// if you want to unget all three tokens. Note that it does not
// make sense to unget t1 without first ungetting t2 and t3
//
TokenType LexicalAnalyzer::UngetToken(Token tok)
{
tokens.push_back(tok);;
return tok.token_type;
}
Token LexicalAnalyzer::GetToken()
{
char c;
// if there are tokens that were previously
// stored due to UngetToken(), pop a token and
// return it without reading from input
if (!tokens.empty()) {
tmp = tokens.back();
tokens.pop_back();
return tmp;
}
SkipSpace();
tmp.lexeme = "";
tmp.line_no = line_no;
input.GetChar(c);
//SkipComment();
while (c == '/') { //skip comment test
while (c != '\n' && !input.EndOfInput()) input.GetChar(c);
SkipSpace();
input.GetChar(c);
}
switch (c) {
case '=':
tmp.token_type = EQUAL;
return tmp;
case ':':
tmp.token_type = COLON;
return tmp;
case ',':
tmp.token_type = COMMA;
return tmp;
case ';':
tmp.token_type = SEMICOLON;
return tmp;
case '{':
tmp.token_type = LBRACE;
return tmp;
case '}':
tmp.token_type = RBRACE;
return tmp;
default:
if (isalpha(c)) {
input.UngetChar(c);
return ScanIdOrKeyword();
} else if (input.EndOfInput())
tmp.token_type = END_OF_FILE;
else
tmp.token_type = ERROR;
return tmp;
}
}
| [
"[email protected]"
] | |
8d729fa897618431596abf5883593d6c77bb1bd4 | e10ddca5055e39f77cc3676de2916107cd210980 | /catch2-example.test.cpp | 549f026a70dc3ad8f0fe90bdca13f42198661632 | [
"MIT"
] | permissive | matepek/catch2-with-gmock | 3f2953d5b9d265526166e307b4e8941425085c18 | 93e77c0c5760b42069038a9a896f6892d0eca59b | refs/heads/master | 2021-01-06T16:36:33.128462 | 2020-05-01T04:33:09 | 2020-05-01T04:33:09 | 241,400,388 | 16 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 980 | cpp | // https://github.com/matepek/catch2-with-gmock
// NOTE that next line includes gmock and catch2 headers automatically.
#include "ThirdParty/Catch2TestWithMainAndGMock.hpp"
#include "ThirdParty/MockScopeGuard.hpp"
using namespace std;
///
class Foo {
public:
virtual ~Foo() {}
virtual bool Bar() const = 0;
};
class MockFoo : public Foo {
public:
MOCK_METHOD(bool, Bar, (), (const, override));
};
///
TEST_CASE("example #1") {
::testing::StrictMock<MockFoo> mock1, mock2;
Foo& foo1 = mock1;
SECTION("success") {
auto mockGuard = MockScopeGuard(mock1, mock2);
EXPECT_CALL(mock1, Bar).WillOnce(::testing::Return(true));
REQUIRE(true == foo1.Bar());
}
SECTION("failure #1") {
auto mockGuard = MockScopeGuard(mock1, mock2);
EXPECT_CALL(mock1, Bar).WillOnce(::testing::Return(true));
}
SECTION("failure #2") {
auto mockGuard = MockScopeGuard(mock1, mock2);
EXPECT_CALL(mock2, Bar).WillOnce(::testing::Return(true));
}
} | [
"[email protected]"
] | |
58af571c8982ca6550817df9f6b08cd1b72e1616 | abf24191265fb9e6648cf1de7ed848fbe291da7c | /cugl/lib/2d/actions/CUScaleAction.cpp | f99be05427a8c86f8d8aa61399f32ed5fab45963 | [] | no_license | onewordstudios/sweetspace | 4ecc3fe27fb794fac6e8b2e8402f9b010f5553a4 | 5d071cd68eb925b9ae1b004ce5d6080cc3261d30 | refs/heads/master | 2023-02-04T11:13:34.287462 | 2023-02-03T04:03:24 | 2023-02-03T04:03:24 | 241,430,856 | 9 | 2 | null | 2023-02-03T04:03:26 | 2020-02-18T18:00:44 | C++ | UTF-8 | C++ | false | false | 6,139 | cpp | //
// CUScaleAction.cpp
// Cornell University Game Library (CUGL)
//
// This module provides support for the scaling actions. Scaling can specified
// as either the final magnification or multiplicative factor.
//
// These classes use our standard shared-pointer architecture.
//
// 1. The constructor does not perform any initialization; it just sets all
// attributes to their defaults.
//
// 2. All initialization takes place via init methods, which can fail if an
// object is initialized more than once.
//
// 3. All allocation takes place via static constructors which return a shared
// pointer.
//
// CUGL MIT License:
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
// Author: Sophie Huang and Walker White
// Version: 3/12/17
//
#include <cugl/2d/actions/CUScaleAction.h>
#include <string>
#include <sstream>
using namespace cugl;
#pragma mark -
#pragma mark MoveBy
/**
* Initializes a scaling animation by the given factor
*
* When animated, this action will adjust the scale of the node so that it
* is multiplied by the given factor. The animation will take place over
* the given number of seconds.
*
* @param factor The amount to scale the target node
* @param time The animation duration
*
* @return true if initialization was successful.
*/
bool ScaleBy::init(const Vec2& factor, float time) {
_delta = factor;
_duration = time;
return true;
}
/**
* Returns a newly allocated copy of this Action.
*
* @return a newly allocated copy of this Action.
*/
std::shared_ptr<Action> ScaleBy::clone() {
auto action = ScaleBy::alloc();
action->setFactor(_delta);
return action;
}
/**
* Prepares a target for action
*
* The important state of the target is stored in the given state parameter.
* The semantics of this state is action-dependent.
*
* @param target The node to act on
* @param state The relevant node state
*/
void ScaleBy::load(const std::shared_ptr<Node>& target, Uint64* state) {
Vec2* scale = (Vec2*)state;
*scale = target->getScale();
}
/**
* Executes an action on the given target node.
*
* The important state of the target is stored in the given state parameter.
* The semantics of this state is action-dependent.
*
* @param target The node to act on
* @param state The relevant node state
* @param dt The elapsed time to animate.
*/
void ScaleBy::update(const std::shared_ptr<Node>& target, Uint64* state, float dt) {
Vec2 scale = target->getScale();
Vec2* orig = (Vec2*)state;
Vec2 diff = (*orig)*_delta-(*orig);
target->setScale(scale+diff*dt);
}
/**
* Returns a string representation of the action for debugging purposes.
*
* If verbose is true, the string will include class information. This
* allows us to unambiguously identify the class.
*
* @param verbose Whether to include class information
*
* @return a string representation of this action for debuggging purposes.
*/
std::string ScaleBy::toString(bool verbose) const {
std::stringstream ss;
ss << "ScaleBy{";
ss << _delta.toString();
ss << "}'";
return ss.str();
}
#pragma mark -
#pragma mark MoveTo
/**
* Initializes a scaling action towards the given scale amount
*
* The animation will take place over the given number of seconds.
*
* @param scale The target scaling amount
* @param time The animation duration
*
* @return true if initialization was successful.
*/
bool ScaleTo::init(const Vec2& scale, float time) {
_scale = scale;
_duration = time;
return true;
}
/**
* Returns a newly allocated copy of this Action.
*
* @return a newly allocated copy of this Action.
*/
std::shared_ptr<Action> ScaleTo::clone() {
auto action = ScaleTo::alloc();
action->setScale(_scale);
return action;
}
/**
* Prepares a target for action
*
* The important state of the target is stored in the given state parameter.
* The semantics of this state is action-dependent.
*
* @param target The node to act on
* @param state The relevant node state
*/
void ScaleTo::load(const std::shared_ptr<Node>& target, Uint64* state) {
Vec2* scale = (Vec2*)state;
*scale = target->getScale();
}
/**
* Executes an action on the given target node.
*
* The important state of the target is stored in the given state parameter.
* The semantics of this state is action-dependent.
*
* @param target The node to act on
* @param state The relevant node state
* @param dt The elapsed time to animate.
*/
void ScaleTo::update(const std::shared_ptr<Node>& target, Uint64* state, float dt) {
Vec2 scale = target->getScale();
Vec2* orig = (Vec2*)state;
Vec2 diff = _scale-(*orig);
target->setScale(scale+diff*dt);
}
/**
* Returns a string representation of the action for debugging purposes.
*
* If verbose is true, the string will include class information. This
* allows us to unambiguously identify the class.
*
* @param verbose Whether to include class information
*
* @return a string representation of this action for debuggging purposes.
*/
std::string ScaleTo::toString(bool verbose) const {
std::stringstream ss;
ss << "ScaleTo{";
ss << _scale.toString();
ss << "}'";
return ss.str();
}
| [
"[email protected]"
] | |
38df3865fc7c4291b6a69def862a0776251e6a83 | b511bb6461363cf84afa52189603bd9d1a11ad34 | /second year/asdkj.cpp | 56ee60090374844a0b8c936a52f27c1b3b7d3879 | [] | no_license | masumr/problem_solve | ec0059479425e49cc4c76a107556972e1c545e89 | 1ad4ec3e27f28f10662c68bbc268eaad9f5a1a9e | refs/heads/master | 2021-01-16T19:07:01.198885 | 2017-08-12T21:21:59 | 2017-08-12T21:21:59 | 100,135,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | cpp | #include<bits/stdc++.h>
using namespace std;
map<char,int>mp;
int main(){
mp['a']=1;mp['e']=1;mp['i']=1;mp['o']=1;mp['u']=1;mp['y']=1;
mp['A']=1;mp['E']=1;mp['I']=1;mp['O']=1;mp['U']=1;mp['Y']=1;
int t;
while(scanf("%d",&t)==1){
while(t--){
string s;
cin>>s;
int f1=0,l1=s.size()-1;
string sk="";
for(int i=0;i<s.size();i++){
if(mp[s[i]]){
sk+=s[i];
f1++;
}
else break;
}
for(int i=s.size()-1;i>=f1;i--){
if(mp[s[i]])l1--;
else break;
}
for(int i=f1;i<=l1;i++){
if(!mp[s[i]])sk+=s[i];
}
cout<<sk;
//cout<<s[l1]<<endl;
for(int i=l1+1;i<=s.size();i++)cout<<s[i];
cout<<endl;
}
}
}
| [
"[email protected]"
] | |
8644218777ec3b933d5ea08593b3cd3592c02055 | d34969a38cd03d2dc5dea78eded9214c52e60379 | /TETRIS/TETRIS/ts_waiting_room.cpp | 0d112ff804b4c7e8d8de1020cc43eb4ac5703159 | [] | no_license | yeongchiccccc/beginner_cpp | db963cf67ce99722599120b241234bf36c716505 | e01f753efa392b8ea20ad3b90d96d44ce7ccadf5 | refs/heads/main | 2023-08-19T10:52:40.064521 | 2020-11-19T08:41:21 | 2020-11-19T08:41:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,573 | cpp | #include "stdafx.h"
BOOL CALLBACK DlgProc_Waiting(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
int iRetval = 0;
LPNMHDR pHdr = NULL;
LPNMLISTVIEW pNlv = NULL;
pHdr = (LPNMHDR)lParam;
pNlv = (LPNMLISTVIEW)lParam;
switch ( uMsg )
{
case WM_INITDIALOG:
{
InitProc_Waiting(hDlg);
}
return TRUE;
case WM_COMMAND:
{
switch( LOWORD(wParam) )
{
case IDC_BUTTON1:
DialogBox(g_hInst, MAKEINTRESOURCE(IDD_DIALOG_MAKING), NULL, DlgProc_MakingRoom);
if ( g_bWhether_CreateRoom == TRUE )
{
EndDialog(hDlg, 0);
}
break;
case IDOK:
JoinInTheRoom();
EndDialog(hDlg, 0);
break;
case IDCANCEL:
exit(-1);
break;
}
}
return TRUE;
case WM_TIMER:
{
switch ( wParam )
{
case TIMER_TYPE_WATCHDOG :
{
KillTimer(hDlg, TIMER_TYPE_WATCHDOG);
MessageBox(g_hWndMain, _T("Server is Ended..."), _T("Notice"), MB_OK);
}
}
}
break;
case WM_SOCKET:
{
ProcessSocketMessage_Room(hDlg, uMsg, wParam, lParam);
}
return TRUE;
case WM_NOTIFY:
{
switch (((LPNMHDR)lParam)->code)
{
case LVN_ITEMCHANGED:
EnableWindow(g_hOKbutton2, TRUE);
g_lpNIA = (LPNMITEMACTIVATE)lParam;
g_iSaveRoomNumber = GetRoomNumber();
break;
}
}
break;
case WM_DESTROY:
{
EndDialog(hDlg, 0);
closesocket(g_hWRSock);
}
return TRUE;
}
return FALSE;
}
VOID InitProc_Waiting(HWND hDlg)
{
int iRetval = 0;
LVCOLUMN tLVcol;
SetTimer(hDlg, TIMER_TYPE_WATCHDOG, TIMER_TYPE_WATCHDOG_DELAY, NULL);
g_hList = GetDlgItem(hDlg, IDC_LIST1);
g_hRoomCreate = GetDlgItem(hDlg, IDC_BUTTON1);
g_hOKbutton2 = GetDlgItem(hDlg, IDOK);
g_hEdit = GetDlgItem(hDlg, IDC_EDIT_ROOMNAME);
tLVcol.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
tLVcol.fmt = LVCFMT_LEFT;
tLVcol.cx = 150;
tLVcol.pszText = L"Room Name";
tLVcol.iSubItem = 0;
SendMessage(g_hList, LVM_INSERTCOLUMN, 0, (LPARAM)&tLVcol);
tLVcol.pszText = L"Room ID";
tLVcol.iSubItem = 1;
SendMessage(g_hList, LVM_INSERTCOLUMN, 1, (LPARAM)&tLVcol);
tLVcol.pszText = L"personnel";
tLVcol.iSubItem = 2;
SendMessage(g_hList, LVM_INSERTCOLUMN, 2, (LPARAM)&tLVcol);
EnableWindow(g_hOKbutton2, FALSE);
//Socket Create
WSADATA tWSAdata= {0,};
if ( WSAStartup(MAKEWORD(2,2), &tWSAdata) != 0 )
{
exit(-1);
}
//Socket()
g_hWRSock = socket(AF_INET, SOCK_STREAM, 0);
if ( g_hWRSock == INVALID_SOCKET )
{
err_quit("socket()");
}
SOCKADDR_IN tAddrServer = {0,};
tAddrServer.sin_family = AF_INET;
tAddrServer.sin_port = htons(SIN_PORT);
tAddrServer.sin_addr.s_addr = inet_addr(SIN_ADDR);
//WSAAsyncSelect()
iRetval = WSAAsyncSelect(g_hWRSock, hDlg, WM_SOCKET, FD_CONNECT | FD_CLOSE);
if ( iRetval == SOCKET_ERROR )
{
err_quit("WSAAsyncSelect()");
}
//connect()
iRetval = connect(g_hWRSock, (SOCKADDR*)&tAddrServer, sizeof(tAddrServer));
if ( iRetval == INVALID_SOCKET )
{
if ( WSAGetLastError() != WSAEWOULDBLOCK )
{
err_display("connect()");
}
}
}
VOID ProcessSocketMessage_Room(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
int iRetval = 0;
switch (WSAGETSELECTEVENT(lParam))
{
case FD_CLOSE:
{
closesocket(g_hWRSock);
}
break;
case FD_READ:
{
WaitingRoomReadFunction(hDlg, wParam, lParam);
}
break;
case FD_CONNECT:
{
iRetval = WSAAsyncSelect(g_hWRSock, hDlg, WM_SOCKET, FD_READ | FD_CLOSE);
if ( iRetval == SOCKET_ERROR )
{
err_quit("WSAAsyncSelect()");
}
SendingRenew();
}
}
}
VOID ViewRoomList(char *pBody, int iBodySize)
{
int iSizeOfRoom = 0;
char cNumOfRoom[10] = {0,};
g_tLVItem.mask = LVIF_TEXT;
g_tLVItem.iItem = 0;
while (iSizeOfRoom < iBodySize)
{
g_tLVItem.iSubItem = 0;
g_tLVItem.pszText = pBody + (sizeof(int) * 2) + iSizeOfRoom;
SendMessageA(g_hList, LVM_INSERTITEMA, 0, (LPARAM)&g_tLVItem);
g_tLVItem.iSubItem = 1;
g_tLVItem.pszText = pBody + iSizeOfRoom;
sprintf(g_tLVItem.pszText, "%d", g_tLVItem.pszText[0]);
SendMessageA(g_hList, LVM_SETITEMA, 1, (LPARAM)&g_tLVItem);
g_tLVItem.iSubItem = 2;
g_tLVItem.pszText = pBody + sizeof(int) + iSizeOfRoom;
sprintf(g_tLVItem.pszText, "%d/%d", g_tLVItem.pszText[0], MAX_PEOPLE);
SendMessageA(g_hList, LVM_SETITEMA, 2, (LPARAM)&g_tLVItem);
iSizeOfRoom += sizeof(ROOMINFO);
g_tLVItem.iItem++;
}
}
BOOL CreateRoom(HWND hDlg)
{
int iSendTot = 0;
int iSendSize = 0;
LPPACKET_BODY pPacket = NULL;
LPPACKET_HEADER pHeader = NULL;
DWORD dwRespBufSize = 0;
PBYTE pRespBuf = NULL;
PBYTE pBody = NULL;
pPacket = new PACKET_BODY;
ZeroMemory(pPacket, sizeof(PACKET_BODY));
GetDlgItemTextA(hDlg, IDC_EDIT_ROOMNAME, (LPSTR)pPacket->cData, SMALLBUF+1);
if ( '\0' ==pPacket->cData[0] )
{
return FALSE;
}
dwRespBufSize = strlen(pPacket->cData) + sizeof(PACKET_HEADER) + 1;
pRespBuf = new BYTE[dwRespBufSize];
ZeroMemory(pRespBuf, dwRespBufSize);
pHeader = (LPPACKET_HEADER)pRespBuf;
pBody = pRespBuf + sizeof(PACKET_HEADER);
//header setting
pHeader->iFlag = WSABUFFER_ROOMNAME;
pHeader->iSize = strlen(pPacket->cData) + sizeof(PACKET_HEADER);
//body setting
memcpy((LPSTR)pBody, pPacket->cData, strlen(pPacket->cData));
do
{
iSendSize = send(g_hWRSock, (char*)pHeader + iSendTot, pHeader->iSize - iSendTot, NULL);
if (iSendSize == SOCKET_ERROR)
{
printf("send()\n");
break;
}
iSendTot += iSendSize;
} while ( pHeader->iSize != iSendTot );
SetFocus(g_hEdit);
SendMessage(g_hEdit, EM_SETSEL, 0, -1);
SendMessage(g_hEdit, EM_REPLACESEL, NULL, (LPARAM)"");
delete [] pRespBuf;
pRespBuf = NULL;
delete pPacket;
pPacket = NULL;
return TRUE;
}
BOOL CALLBACK DlgProc_MakingRoom(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch ( uMsg )
{
case WM_COMMAND:
switch(LOWORD(wParam))
{
case IDOK:
{
g_bWhether_CreateRoom = CreateRoom(hDlg);
if ( g_bWhether_CreateRoom == TRUE )
{
EndDialog(hDlg, 0);
}
}
return TRUE;
case IDCANCEL:
{
EndDialog(hDlg, 0);
return FALSE;
}
}
return TRUE;
}
return FALSE;
}
VOID JoinInTheRoom()
{
int iSendTot = 0;
int iSendLen = 0;
int iSaveRoomNum = 0;
LPPACKET_HEADER pHeader = NULL;
DWORD dwRespBufSize = 0;
PBYTE pRespBuf = NULL;
PBYTE pBody = NULL;
dwRespBufSize = sizeof(PACKET_HEADER) + sizeof(int) + 1;
pRespBuf = new BYTE[dwRespBufSize];
ZeroMemory(pRespBuf, dwRespBufSize);
pHeader = (LPPACKET_HEADER)pRespBuf;
pBody = pRespBuf + sizeof(PACKET_HEADER);
pHeader->iFlag = WSABUFFER_JOIN;
pHeader->iSize = sizeof(PACKET_HEADER) + sizeof(int);
iSaveRoomNum = g_iSaveRoomNumber;
memcpy(pBody, &iSaveRoomNum, sizeof(int));
do
{
iSendLen = send(g_hWRSock, (LPSTR)pHeader + iSendTot, pHeader->iSize - iSendTot, NULL);
if ( iSendLen == SOCKET_ERROR )
{
printf("send()\n");
continue;
}
iSendTot += iSendLen;
} while ( pHeader->iSize != iSendTot );
delete [] pRespBuf;
pRespBuf = NULL;
}
int GetRoomNumber()
{
int iBuflength = 0;
WCHAR wBuf[SMALLBUF] = {0,};
iBuflength = wcslen(wBuf);
ListView_GetItemText(g_hList, g_lpNIA->iItem, 1, wBuf, 255);
if (iBuflength <= 1)
{
g_iSaveRoomNumber = (int) (wBuf[0] - '0');
}
else
{
g_iSaveRoomNumber--;
g_iSaveRoomNumber += (int)(wBuf[iBuflength - 0] - '0');
g_iSaveRoomNumber += (int)((wBuf[iBuflength - 1] - '0') * 10);
g_iSaveRoomNumber += (int)((wBuf[iBuflength - 2] - '0') * 100);
}
return g_iSaveRoomNumber;
}
VOID WaitingRoomReadFunction(HWND hDlg, WPARAM wParam, LPARAM lParam)
{
SOCKET hSock = (SOCKET)wParam;
int iRecvLen = 0;
int iBodySize = 0;
int iMaxLen = 0;
LPPACKET_BODY pPacket = NULL;
LPPACKET_HEADER pHeader = NULL;
LPSTR pBody = NULL;
pPacket = new PACKET_BODY;
ZeroMemory(pPacket, sizeof(PACKET_BODY));
iMaxLen = BUFSIZE;
while(pPacket->iCurRecv < iMaxLen)
{
iRecvLen = recv(hSock, (LPSTR)(pPacket->cData + pPacket->iCurRecv), (iMaxLen - pPacket->iCurRecv), NULL);
if (iRecvLen == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAEWOULDBLOCK)
{
continue;
}
}
pPacket->iCurRecv += ((iRecvLen > 0) ? iRecvLen : 0);
if (pPacket->iCurRecv >= sizeof(PACKET_HEADER))
{
if ( !pHeader )
{
pHeader = (LPPACKET_HEADER) pPacket->cData;
iMaxLen = pHeader->iSize;
}
}
}
pBody = (LPSTR)(pPacket->cData + sizeof(PACKET_HEADER));
iBodySize = pHeader->iSize - sizeof(PACKET_HEADER);
switch ( pHeader->iFlag )
{
case WSABUFFER_RENEW:
{
ListView_DeleteAllItems(g_hList);
UpdateWindow(g_hList);
ViewRoomList(pBody, iBodySize);
}
break;
case WSABUFFER_JOIN:
{
}
break;
case WSABUFFER_FULL:
{
MessageBox(hDlg, _T("Can't Join this room"), NULL, MB_OK);
}
break;
case WSABUFFER_NOTFULL:
{
EndDialog(hDlg, 0);
}
break;
case WSABUFFER_WATCHDOG:
{
Watchdog_Kill(hDlg);
}
break;
}
}
VOID SendingRenew()
{
int iSendByte = 0;
LPPACKET_HEADER pHeader = {0,};
pHeader = new PACKET_HEADER;
ZeroMemory(pHeader, sizeof(PACKET_HEADER));
pHeader->iFlag = WSABUFFER_RENEW;
iSendByte = send(g_hWRSock, (LPSTR)pHeader, sizeof(PACKET_HEADER), NULL);
} | [
"[email protected]"
] | |
62d15e4edfe35215f3541057b4040510a229c52c | 33303d4a07598139320c796f07c614d5e901e6ef | /cpp/oneapi/dal/algo/svm/detail/infer_ops.hpp | 24a90633ac29b1ea416f8f15916e48310578bc09 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"Intel",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"MIT",
"Zlib"
] | permissive | bysheva/oneDAL | 7eb33dbb5aa3393c032f4e68cc1cb93fc50c0c3f | 84cb27c9afde49320670006b4ff0791ee90d73d1 | refs/heads/master | 2023-05-05T21:18:45.345237 | 2021-03-01T08:00:08 | 2021-03-01T08:00:08 | 284,727,302 | 0 | 2 | Apache-2.0 | 2021-05-29T00:02:24 | 2020-08-03T14:49:26 | C++ | UTF-8 | C++ | false | false | 3,732 | hpp | /*******************************************************************************
* Copyright 2020-2021 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#pragma once
#include "oneapi/dal/algo/svm/infer_types.hpp"
#include "oneapi/dal/detail/error_messages.hpp"
namespace oneapi::dal::svm::detail {
namespace v1 {
template <typename Context, typename Float, typename Method, typename Task, typename... Options>
struct infer_ops_dispatcher {
infer_result<Task> operator()(const Context&,
const descriptor_base<Task>&,
const infer_input<Task>&) const;
};
template <typename Descriptor>
struct infer_ops {
using float_t = typename Descriptor::float_t;
using method_t = method::by_default;
using task_t = typename Descriptor::task_t;
using input_t = infer_input<task_t>;
using result_t = infer_result<task_t>;
using descriptor_base_t = descriptor_base<task_t>;
void check_preconditions(const Descriptor& params, const input_t& input) const {
using msg = dal::detail::error_messages;
if (!input.get_data().has_data()) {
throw domain_error(msg::input_data_is_empty());
}
if (!input.get_model().get_support_vectors().has_data()) {
throw domain_error(msg::input_model_support_vectors_are_empty());
}
if (!input.get_model().get_coeffs().has_data()) {
throw domain_error(msg::input_model_coeffs_are_empty());
}
if (input.get_model().get_support_vectors().get_column_count() !=
input.get_data().get_column_count()) {
throw invalid_argument(msg::input_model_support_vectors_cc_neq_input_data_cc());
}
if (input.get_model().get_support_vectors().get_row_count() !=
input.get_model().get_support_vector_count()) {
throw invalid_argument(
msg::input_model_support_vectors_rc_neq_input_model_support_vector_count());
}
if (input.get_model().get_coeffs().get_row_count() !=
input.get_model().get_support_vector_count()) {
throw invalid_argument(
msg::input_model_coeffs_rc_neq_input_model_support_vector_count());
}
}
void check_postconditions(const Descriptor& params,
const input_t& input,
const result_t& result) const {
ONEDAL_ASSERT(result.get_labels().has_data());
ONEDAL_ASSERT(result.get_decision_function().has_data());
ONEDAL_ASSERT(result.get_decision_function().get_row_count() ==
result.get_labels().get_row_count());
}
template <typename Context>
auto operator()(const Context& ctx, const Descriptor& desc, const input_t& input) const {
check_preconditions(desc, input);
const auto result =
infer_ops_dispatcher<Context, float_t, method_t, task_t>()(ctx, desc, input);
check_postconditions(desc, input, result);
return result;
}
};
} // namespace v1
using v1::infer_ops;
} // namespace oneapi::dal::svm::detail
| [
"[email protected]"
] | |
96910a6d12b1f7bbd6e8f893118c187fbe638261 | a725c4f380cc19b46ff97e769cf3cbf44214333b | /cpp-leetcode/leetcode599-minimum-index-sum-of-two-lists_sort.cpp | 8b3f27551c1a4ac76e6f3dc2081907a5f2a8b9d3 | [
"MIT"
] | permissive | llenroc/leetcode-ac | b4e120d42aa138bfaa092a24dc941b03eb0c9279 | fd199fe254898fcb5de7d16a5d39ff78cfcd1026 | refs/heads/master | 2023-08-12T07:58:16.609374 | 2021-10-12T14:03:23 | 2021-10-12T14:03:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,499 | cpp | #include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
vector<string> res;
const int len1 = list1.size();
const int len2 = list2.size();
vector<pair<string, int>> kvVect;
int indexSum = 0;
for (int i = 0; i < len1; i++)
{
auto it = find(list2.begin(), list2.end(), list1[i]);
if (it != list2.end())
{
indexSum = it - list2.begin() + i;
kvVect.push_back({list1[i], indexSum});
}
}
auto cmp = [](pair<string, int>& p1, pair<string, int>& p2)
{
if (p1.second == p2.second)
return p1.first < p2.first;
return p1.second < p2.second;
};
sort(kvVect.begin(), kvVect.end(), cmp);
int minIndexSum = kvVect.front().second;
for (auto &kvp : kvVect)
{
if (kvp.second == minIndexSum)
res.push_back(kvp.first);
}
return res;
}
};
// Test
int main()
{
Solution sol;
vector<string> list1 = {"Shogun","Tapioca Express","Burger King","KFC"};
vector<string> list2 = {"KFC","Burger King","Tapioca Express","Shogun"};
auto res = sol.findRestaurant(list1, list2);
for (auto str : res)
cout << str << endl;
return 0;
} | [
"[email protected]"
] | |
4dc7db8fc4b1229ee98fbcf71aacbff4d4a12f3c | 48b23a49c093e8303b90ed6335e61d64362e40af | /shandalovych-viktoriia/src/shandalovych03/AutoWheelScreen.cpp | 7cf8342fde01ddb1e536fcb405b1508c8437eadb | [
"MIT"
] | permissive | zeienko-vitalii/se-cpp | e5b7d1d8800e2a5c777e76cc9cfd30d898400282 | 54a5dfb2e98af099fbfaef129a7fe03a7b815d6f | refs/heads/master | 2021-08-15T15:22:30.559011 | 2017-11-17T22:37:45 | 2017-11-17T22:37:45 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 544 | cpp | /*
* AutoWheelScreen.cpp
*
* Created on: 8 окт. 2017 г.
* Author: Viktotia
*/
#include "AutoWheelScreen.h"
AutoWheelScreen::AutoWheelScreen() {
// TODO Auto-generated constructor stub
}
AutoWheelScreen::AutoWheelScreen(AutoWheel* autoWheel):Screen(autoWheel) {
}
AutoWheelScreen::~AutoWheelScreen() {
// TODO Auto-generated destructor stub
}
void AutoWheelScreen::ShowHeader() {
}
void AutoWheelScreen::ShowContent() {
cout << (*wheel).ToString();
}
void AutoWheelScreen::ShowFooter() {
}
| [
"[email protected]"
] | |
6929d8175519a7eacc98f9997f0ebd80e0a152c0 | 7d9ba4c049d472efdab0a84e80872a1390ab895d | /C++/09 Pythagorean Triples.cpp | f7294ed37b9827948c5a572d824e4b8978640ed9 | [] | no_license | spencerng/ProjectEuler | fd33d70f350ca5c548536efe09381d2cf96558c9 | df4d9c9d02297d60e3dff40cf7fffb3593423b4f | refs/heads/master | 2021-01-01T04:28:18.239012 | 2017-07-14T01:41:02 | 2017-07-14T01:41:02 | 97,180,165 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | #include<iostream>
#include<vector>
#include <string>
#include <cmath>
using namespace std;
//use the idea that Pythagoream Triples can be constructed with any
//m and n, where a = n^2-m^2, b = 2mn, c=n^2+m^2
int main() {
int testCases, num;
cin >> testCases;
for (int i = 0; i<testCases; i++) {
cin >> num;
int greatestTriple = -1;
for(int m=2; m < num; m++){
for(int n = 2; n < num; n++){
if(2*n*(n+m)==num&&2*m*n*(pow(n, 4)-pow(m, 4))>greatestTriple)
greatestTriple=2*m*n*(pow(n, 4)-pow(m, 4));
}
}
cout << greatestTriple << endl;
}
return 0;
} | [
"[email protected]"
] | |
76a3ada9866d6da79f446348752ba299a1ecd91c | 03781c98597e3cc175a4c0ae25951167f7c41e6a | /SGU/180.cpp | 7dc720e79378c054feced055301e60cb26ffa565 | [] | no_license | Liuchenlong/acm | e4ea0d59739d05ae808a45c4164decf91f2087ff | d52dc289d836874dd30f4d8a5a2002398a0639e8 | refs/heads/master | 2020-04-03T22:06:28.611879 | 2019-09-28T14:08:27 | 2019-09-28T14:08:27 | 59,131,382 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | #include<stdio.h>
#include<cmath>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<queue>
#include<set>
#include<vector>
#include<map>
using namespace std;
#define eps 1e-12
const int maxn=70005;
int N;
int a[maxn];
int lowbit(int x)
{
return x&(-x);
}
int add(int x)
{
for(int i=x;i<=N;i+=lowbit(i))
a[i]++;
}
int sum(int x)
{
int ans=0;
for(int i=x;i>0;i-=lowbit(i))
ans+=a[i];
return ans;
}
int n;
int n1[maxn];
int n2[maxn];
map<int,int>mp;
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&n1[i]);
n2[i]=n1[i];
}
sort(n2,n2+n);
N=unique(n2,n2+n)-n2;
for(int i=0;i<N;i++)
mp[n2[i]]=i+1;
long long ans=0;
for(int i=0;i<n;i++)
{
ans+=(i-sum(mp[n1[i]]));
add(mp[n1[i]]);
}
printf("%I64d\n",ans);
return 0;
}
| [
"[email protected]"
] | |
f19b9b5dad3f80c82ebd4fe4e5dc0ad51430d22e | 5e924ac5f31ce1003e551625178a110d8c013eea | /include/SPTK/filter/line_spectral_pairs_digital_filter.h | 8cc7f84111c714ac6e33d734749838d830311208 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | AudioBucket/SPTK | c1f5d29298d1f7052bd5858f345025ae5395839d | f07cc56722ac82c0f4d7625e655f1ac304dc0d93 | refs/heads/master | 2020-03-28T06:18:57.681257 | 2018-09-03T13:44:28 | 2018-09-03T13:44:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,449 | h | // ----------------------------------------------------------------- //
// The Speech Signal Processing Toolkit (SPTK) //
// developed by SPTK Working Group //
// http://sp-tk.sourceforge.net/ //
// ----------------------------------------------------------------- //
// //
// Copyright (c) 1984-2007 Tokyo Institute of Technology //
// Interdisciplinary Graduate School of //
// Science and Engineering //
// //
// 1996-2018 Nagoya Institute of Technology //
// Department of Computer Science //
// //
// All rights reserved. //
// //
// Redistribution and use in source and binary forms, with or //
// without modification, are permitted provided that the following //
// conditions are met: //
// //
// - Redistributions of source code must retain the above copyright //
// notice, this list of conditions and the following disclaimer. //
// - Redistributions in binary form must reproduce the above //
// copyright notice, this list of conditions and the following //
// disclaimer in the documentation and/or other materials provided //
// with the distribution. //
// - Neither the name of the SPTK working group nor the names of its //
// contributors may be used to endorse or promote products derived //
// from this software without specific prior written permission. //
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND //
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, //
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF //
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS //
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, //
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED //
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, //
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON //
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY //
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE //
// POSSIBILITY OF SUCH DAMAGE. //
// ----------------------------------------------------------------- //
#ifndef SPTK_FILTER_LINE_SPECTRAL_PAIRS_DIGITAL_FILTER_H_
#define SPTK_FILTER_LINE_SPECTRAL_PAIRS_DIGITAL_FILTER_H_
#include <vector> // std::vector
#include "SPTK/utils/sptk_utils.h"
namespace sptk {
class LineSpectralPairsDigitalFilter {
public:
class Buffer {
public:
//
Buffer() {
}
//
virtual ~Buffer() {
}
private:
//
std::vector<double> signals1_;
//
std::vector<double> signals2_;
//
friend class LineSpectralPairsDigitalFilter;
//
DISALLOW_COPY_AND_ASSIGN(Buffer);
};
//
explicit LineSpectralPairsDigitalFilter(int num_filter_order)
: num_filter_order_(num_filter_order), is_valid_(true) {
if (num_filter_order_ < 0) {
is_valid_ = false;
}
}
//
virtual ~LineSpectralPairsDigitalFilter() {
}
//
int GetNumFilterOrder() const {
return num_filter_order_;
}
//
bool IsValid() const {
return is_valid_;
}
//
bool Run(const std::vector<double>& filter_coefficients, double filter_input,
double* filter_output,
LineSpectralPairsDigitalFilter::Buffer* buffer) const;
private:
//
const int num_filter_order_;
//
bool is_valid_;
//
DISALLOW_COPY_AND_ASSIGN(LineSpectralPairsDigitalFilter);
};
} // namespace sptk
#endif // SPTK_FILTER_LINE_SPECTRAL_PAIRS_DIGITAL_FILTER_H_
| [
"[email protected]"
] | |
00c09c578a444c63accab397914856310e449cc1 | 916e7c5c7fc660dfdb58d235051fdfd9d1c53f41 | /GCQL/colorbtn.cpp | 9c2f95ed31f484aec9812e86eb10f7e9e40ef933 | [
"MIT"
] | permissive | palestar/gamecq | 13a98686273aef446f80099a003f156eba351b86 | 1fe2dfa396769bb8bfbe2a47914a41e5e821a26b | refs/heads/develop | 2020-12-24T18:24:05.416537 | 2020-02-08T20:38:01 | 2020-02-08T20:38:01 | 59,443,046 | 10 | 11 | null | 2016-12-12T15:34:27 | 2016-05-23T01:20:10 | C++ | UTF-8 | C++ | false | false | 14,455 | cpp | // ColorBtn.cpp : implementation file
#define MATERIALPORT_DLL
#include "stdafx.h"
#include "ColorBtn.h"
#ifdef _DEBUG
//#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// The color table, initialized to windows' 20 static colors
//COLORREF RGB( unsigned char r, unsigned char g, unsigned char b )
//{
// return( r | (g << 8) | (b << 16) );
//}
COLORREF CColorBtnDlg::colors[20] =
{
RGB(0,0,0),
RGB(128,0,0),
RGB(0,128,0),
RGB(128,128,0),
RGB(0,0,128),
RGB(128,0,128),
RGB(0,128,128),
RGB(192,192,192),
RGB(192,220,192),
RGB(166,202,240),
RGB(255,251,240),
RGB(160,160,164),
RGB(128,128,128),
RGB(255,0,0),
RGB(0,255,0),
RGB(255,255,0),
RGB(0,0,255),
RGB(255,0,255),
RGB(0,255,255),
RGB(255,255,255)
};
// MRU table. See notes for Reset()
BYTE CColorBtnDlg::used[20] =
{
1,3,5,7,9,11,13,15,17,19,20,18,16,14,12,10,8,6,4,2
};
/////////////////////////////////////////////////////////////////////////////
// CColorBtn
CColorBtn::CColorBtn()
{
currentcolor = RGB(255,255,255);
dlg.parent = this; // This will allow the dialog to position itself
// Create the pens and brushes that we'll need to draw the button
nullpen.CreateStockObject(NULL_PEN);
blackpen.CreateStockObject(BLACK_PEN);
whitepen.CreateStockObject(WHITE_PEN);
nullbrush.CreateStockObject(NULL_BRUSH);
backbrush.CreateSolidBrush(GetSysColor(COLOR_3DFACE));
dkgray.CreatePen(PS_SOLID,1,RGB(128,128,128));
}
CColorBtn::~CColorBtn()
{
}
BEGIN_MESSAGE_MAP(CColorBtn, CButton)
//{{AFX_MSG_MAP(CColorBtn)
ON_CONTROL_REFLECT(BN_CLICKED, OnClicked)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CColorBtn message handlers
void CColorBtn::DrawItem(LPDRAWITEMSTRUCT lpd)
{
// Draw the button
CBrush colorbrush;
CDC DC;
DC.Attach(lpd->hDC);
int top,left,bottom,right;
// Store this for convinience
top = lpd->rcItem.top;
left = lpd->rcItem.left;
bottom = lpd->rcItem.bottom;
right = lpd->rcItem.right;
colorbrush.CreateSolidBrush(currentcolor);
oldpen = DC.SelectObject(&nullpen);
oldbrush = DC.SelectObject(&backbrush);
// Clear the background using the 3DFACE color.
DC.Rectangle(&lpd->rcItem);
// Draw the border
if (!(lpd->itemState & ODS_SELECTED))
{
// Button is up
DC.SelectObject(&blackpen);
DC.MoveTo(left,bottom-1);
DC.LineTo(right-1,bottom-1);
DC.LineTo(right-1,top);
DC.SelectObject(&dkgray);
DC.MoveTo(left+1,bottom-2);
DC.LineTo(right-2,bottom-2);
DC.LineTo(right-2,top+1);
DC.SelectObject(&whitepen);
DC.LineTo(left+1,top+1);
DC.LineTo(left+1,bottom-2);
}
else
{
// Button is down
DC.SelectObject(&dkgray);
DC.MoveTo(left,bottom-1);
DC.LineTo(left,top);
DC.LineTo(right-1,top);
DC.SelectObject(&whitepen);
DC.MoveTo(right-1,top-1);
DC.LineTo(right-1,bottom-1);
DC.LineTo(left+1,bottom-1);
DC.SelectObject(&blackpen);
DC.MoveTo(left+1,bottom-2);
DC.LineTo(left+1,top+1);
DC.LineTo(right-2,top+1);
// by moving this, we get the things inside the button
// to draw themselves one pixel down and one to the right.
// This completes the "pushed" effect
left++;
right++;
bottom++;
top++;
}
// The division
DC.SelectObject(&whitepen);
DC.MoveTo(right-10,top+4);
DC.LineTo(right-10,bottom-4);
DC.SelectObject(dkgray);
DC.MoveTo(right-11,top+4);
DC.LineTo(right-11,bottom-4);
// The triangle
if (lpd->itemState & ODS_DISABLED)
DC.SelectObject(dkgray);
else
DC.SelectObject(blackpen);
DC.MoveTo(right-4,(bottom/2)-1);
DC.LineTo(right-9,(bottom/2)-1);
DC.MoveTo(right-5,(bottom/2));
DC.LineTo(right-8,(bottom/2));
if (lpd->itemState & ODS_DISABLED)
{
DC.SetPixel(right-4,(bottom/2)-1,RGB(255,255,255));
DC.SetPixel(right-5,(bottom/2),RGB(255,255,255));
DC.SetPixel(right-6,(bottom/2)+1,RGB(255,255,255));
}
else
{
DC.SetPixel(right-6,(bottom/2)+1,RGB(0,0,0));
}
if (!(lpd->itemState & ODS_DISABLED))
{
// The color rectangle, only if enabled
DC.SelectObject(&colorbrush);
DC.Rectangle(left+5,top+4,right-15,bottom-4);
}
if (lpd->itemState & ODS_FOCUS)
{
// Draw the focus
//
// It would have been nice just to
// draw a rectangle using a pen created
// with the PS_ALTERNATE style, but
// this is not supported by WIN95
int i;
for (i=left+3;i<right-4;i+=2)
{
DC.SetPixel(i,top+3,RGB(0,0,0));
DC.SetPixel(i,bottom-4,RGB(0,0,0));
}
for (i=top+3;i<bottom-4;i+=2)
{
DC.SetPixel(left+3,i,RGB(0,0,0));
DC.SetPixel(right-4,i,RGB(0,0,0));
}
}
DC.SelectObject(oldpen);
DC.SelectObject(oldbrush);
DC.Detach();
}
void CColorBtn::OnClicked()
{
// When the button is clicked, show the dialog.
if (dlg.DoModal() == IDOK)
{
currentcolor = CColorBtnDlg::colors[dlg.colorindex];
InvalidateRect(NULL);
}
}
// Store and Load use an undocumented CWinApp function
BOOL CColorBtn::Store()
{
return (AfxGetApp()->WriteProfileBinary(_T("ColorData"), _T("ColorTable"),(LPBYTE)CColorBtnDlg::colors,sizeof(COLORREF)*20) &&
AfxGetApp()->WriteProfileBinary(_T("ColorData"), _T("MRU"),(LPBYTE)CColorBtnDlg::used,sizeof(BYTE)*20));
}
BOOL CColorBtn::Load()
{
BYTE *data = NULL;
UINT size;
// This function allocates the memory it needs
AfxGetApp()->GetProfileBinary(_T("ColorData"), _T("ColorTable"),&data,&size);
if (data)
{
// Copy the data into our table and get rid of the buffer
memcpy((void *)CColorBtnDlg::colors,(void *)data,size);
free((void *)data);
AfxGetApp()->GetProfileBinary(_T("ColorData"), _T("MRU"),&data,&size);
if (data)
{
memcpy((void *)CColorBtnDlg::used,(void *)data,size);
free((void *)data);
return TRUE;
}
}
// If the loading fails, back to the defaults
Reset();
return FALSE;
}
void CColorBtn::Reset()
{
CColorBtnDlg::colors[0] = RGB(0,0,0);
CColorBtnDlg::colors[1] = RGB(128,0,0);
CColorBtnDlg::colors[2] = RGB(0,128,0);
CColorBtnDlg::colors[3] = RGB(128,128,0);
CColorBtnDlg::colors[4] = RGB(0,0,128);
CColorBtnDlg::colors[5] = RGB(128,0,128);
CColorBtnDlg::colors[6] = RGB(0,128,128);
CColorBtnDlg::colors[7] = RGB(192,192,192);
CColorBtnDlg::colors[8] = RGB(192,220,192);
CColorBtnDlg::colors[9] = RGB(166,202,240);
CColorBtnDlg::colors[10] = RGB(255,251,240);
CColorBtnDlg::colors[11] = RGB(160,160,164);
CColorBtnDlg::colors[12] = RGB(128,128,128);
CColorBtnDlg::colors[13] = RGB(255,0,0);
CColorBtnDlg::colors[14] = RGB(0,255,0);
CColorBtnDlg::colors[15] = RGB(255,255,0);
CColorBtnDlg::colors[16] = RGB(0,0,255);
CColorBtnDlg::colors[17] = RGB(255,0,255);
CColorBtnDlg::colors[18] = RGB(0,255,255);
CColorBtnDlg::colors[19] = RGB(255,255,255);
// This "colorful" (no pun intended) order ensures
// that the colors at the center of the color table
// will get replaced first. This preserves the white
// and black colors even if they're not used (They'll
// get replaced last).
CColorBtnDlg::used[0]= 1;
CColorBtnDlg::used[1]= 3;
CColorBtnDlg::used[2]= 5;
CColorBtnDlg::used[3]= 7;
CColorBtnDlg::used[4]= 9;
CColorBtnDlg::used[5]= 11;
CColorBtnDlg::used[6]= 13;
CColorBtnDlg::used[7]= 15;
CColorBtnDlg::used[8]= 17;
CColorBtnDlg::used[9]= 19;
CColorBtnDlg::used[10]= 20;
CColorBtnDlg::used[11]= 18;
CColorBtnDlg::used[12]= 16;
CColorBtnDlg::used[13]= 14;
CColorBtnDlg::used[14]= 12;
CColorBtnDlg::used[15]= 10;
CColorBtnDlg::used[16]= 8;
CColorBtnDlg::used[17]= 6;
CColorBtnDlg::used[18]= 4;
CColorBtnDlg::used[19]= 2;
}
//
//void CColorBtn::Serialize( CArchive& ar )
//{
// if (ar.IsStoring())
// {
// ar.Write((void *)CColorBtnDlg::colors,sizeof(COLORREF)*20);
// ar.Write((void *)CColorBtnDlg::used,sizeof(BYTE)*20);
// }
// else
// {
// ar.Read((void *)CColorBtnDlg::colors,sizeof(COLORREF)*20);
// ar.Read((void *)CColorBtnDlg::used,sizeof(BYTE)*20);
// }
//}
//
/////////////////////////////////////////////////////////////////////////////
// CColorBtnDlg dialog
CColorBtnDlg::CColorBtnDlg(CWnd* pParent /*=NULL*/)
: CDialog(CColorBtnDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CColorBtnDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CColorBtnDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CColorBtnDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CColorBtnDlg, CDialog)
//{{AFX_MSG_MAP(CColorBtnDlg)
ON_BN_CLICKED(IDC_OTHER, OnOther)
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_DRAWITEM()
//}}AFX_MSG_MAP
ON_COMMAND_RANGE(IDC_COLOR1,IDC_COLOR20,OnColor)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CColorBtnDlg message handlers
BOOL CColorBtnDlg::OnInitDialog()
{
CDialog::OnInitDialog();
RECT r,r2;
parent->GetWindowRect(&r);
// Move the dialog to be below the button
SetWindowPos(NULL,r.left,r.bottom,0,0,SWP_NOSIZE|SWP_NOZORDER);
GetWindowRect(&r2);
// Check to see if the dialog has a portion outside the
// screen, if so, adjust.
if (r2.bottom > GetSystemMetrics(SM_CYSCREEN))
{
r2.top = r.top-(r2.bottom-r2.top);
}
if (r2.right > GetSystemMetrics(SM_CXSCREEN))
{
r2.left = GetSystemMetrics(SM_CXSCREEN) - (r2.right-r2.left);
}
SetWindowPos(NULL,r2.left,r2.top,0,0,SWP_NOSIZE|SWP_NOZORDER);
// Capture the mouse, this allows the dialog to close when
// the user clicks outside.
// Remember that the dialog has no "close" button.
SetCapture();
return TRUE;
}
void CColorBtnDlg::EndDialog( int nResult )
{
ReleaseCapture();
CDialog::EndDialog(nResult);
}
void CColorBtnDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
RECT r;
POINT p;
p.x = point.x;
p.y = point.y;
ClientToScreen(&p);
GetWindowRect(&r);
// The user clicked...
if (!PtInRect(&r,p))
{
// ...outside the dialog, close.
EndDialog(IDCANCEL);
}
else
{
// ...inside the dialog. Since this window
// has the mouse captured, its children
// get no messages. So, check to see
// if the click was in one of its children
// and tell him.
// If the user clicks inside the dialog
// but not on any of the controls,
// ChildWindowFromPoint returns a
// pointer to the dialog. In this
// case we do not resend the message
// (obviously) because it would cause
// a stack overflow.
CWnd *child = ChildWindowFromPoint(point);
if (child && child != this)
child->SendMessage(WM_LBUTTONDOWN,0,0l);
}
CDialog::OnLButtonDown(nFlags, point);
}
void CColorBtnDlg::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpd)
{
CDC dc;
CPen nullpen;
CBrush brush;
CPen *oldpen;
CBrush *oldbrush;
// Draw the wells using the current color table
nullpen.CreateStockObject(NULL_PEN);
brush.CreateSolidBrush(colors[nIDCtl-IDC_COLOR1]);
dc.Attach(lpd->hDC);
oldpen = dc.SelectObject(&nullpen);
oldbrush = dc.SelectObject(&brush);
lpd->rcItem.right++;
lpd->rcItem.bottom++;
dc.Rectangle(&lpd->rcItem);
dc.SelectObject(oldpen);
dc.SelectObject(oldbrush);
dc.Detach();
CDialog::OnDrawItem(nIDCtl, lpd);
}
void CColorBtnDlg::OnColor(UINT id)
{
// A well has been clicked, set the color index
// and close.
colorindex = id-IDC_COLOR1;
int i;
// This color is now the MRU
for (i=0;i<20;i++)
{
if (used[colorindex] > used[i])
{
used[i]++;
}
}
used[colorindex] = 1;
EndDialog(IDOK);
}
void CColorBtnDlg::OnOther()
{
int i;
COLORREF newcolor;
// The "Other" button.
ReleaseCapture();
CColorDialog dlg;
dlg.m_cc.Flags |= CC_FULLOPEN;
if (dlg.DoModal() == IDOK)
{
// The user clicked OK.
// set the color and close
newcolor = dlg.GetColor();
// Check to see if the selected color is
// already in the table.
colorindex = -1;
for (i=0;i<20;i++)
{
if (colors[i] == newcolor)
{
colorindex = i;
break;
}
}
// If the color was not found,
// replace the LRU with this color
if (colorindex == -1)
{
for (i=0;i<20;i++)
{
if (used[i] == 20)
{
colors[i] = newcolor;
colorindex = i;
break;
}
}
}
// This is the new MRU
for (i=0;i<20;i++)
{
if (used[colorindex] > used[i])
{
used[i]++;
}
}
used[colorindex] = 1;
EndDialog(IDOK);
return;
}
// If the user clicked "Cancel" reclaim the mouse capture.
SetCapture();
}
void CColorBtnDlg::OnLButtonUp(UINT nFlags, CPoint point)
{
// See notes for OnLButtonDown.
CWnd *child = ChildWindowFromPoint(point,CWP_ALL);
if (child && child != this)
child->SendMessage(WM_LBUTTONDOWN,0,0l);
CDialog::OnLButtonUp(nFlags, point);
}
| [
"[email protected]"
] | |
9dc07790d9096fb4a83c0f4234ac2b2f2f03060d | 11651cbf0eb9ecc4088afa9b2877d2ce16c10289 | /Code/_Utils/BIF/oBIFsQuantization.cpp | 12391f1446167077710d5422e469d219814daf11 | [
"Apache-2.0"
] | permissive | SebastienTs/LOBSTER | 0d32c2d70d1e5561b0a0520a75a10cda9cb1cbab | 3b096cb84a1988d65ccc015d84677d9b8039f2c1 | refs/heads/master | 2020-08-29T16:50:27.291380 | 2020-07-24T16:00:15 | 2020-07-24T16:00:15 | 218,098,866 | 12 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,198 | cpp | #include "mex.h"
#include <math.h>
//nlhs Number of expected mxArrays (Left Hand Side)
//plhs Array of pointers to expected outputs
//nrhs Number of inputs (Right Hand Side)
//prhs Array of pointers to input data. The input data is read-only and should not be altered by your mexFunction .
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
int i, index, outputX, outputY;
double *inputArray, *inputImage;
double *output;
double closest;
int elements,nDirections;
// Get the input angle
inputImage = mxGetPr(prhs[0]);
inputArray = mxGetPr(prhs[1]);
outputX = (int)mxGetPr(prhs[2])[0];
outputY = (int)mxGetPr(prhs[3])[0];
/* Create a pointer to the output data */
plhs[0] = mxCreateDoubleMatrix(outputX, outputY,mxREAL);
output = mxGetPr(plhs[0]);
elements=mxGetNumberOfElements(prhs[0]);
nDirections=mxGetNumberOfElements(prhs[1]);
for ( int x = 0; x < elements; x++) {
closest = inputArray[0];
output[x] = 1;
for ( int i = 0; i < nDirections; ++i ) {
if ( fabs( inputArray[ i ] - inputImage[x] ) < fabs( closest - inputImage[x] ) )
{
closest = inputArray[i];
output[x] = i+1;
}
}
}
}
| [
"[email protected]"
] | |
641b0881b6108974ad3b4ad7fa490d1906afb065 | ccfdc8d0125ed54652289758b68f755230458b95 | /SQLite/CppSQLite3.cpp | 9f78f132c241e2f09ffc3334685379acb0a5895d | [
"MIT"
] | permissive | IgorYunusov/Reclass-2016 | 0197b7f19881ead44be2c9d98adc6efbe176997c | c1fc56ccd66034cd7ef0264c78c1a6ccf3204a39 | refs/heads/master | 2021-01-01T15:43:12.212749 | 2016-10-07T20:19:28 | 2016-10-07T20:19:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,229 | cpp | ////////////////////////////////////////////////////////////////////////////////
// CppSQLite3 - A C++ wrapper around the SQLite3 embedded database library.
//
// Copyright (c) 2004 Rob Groves. All Rights Reserved. [email protected]
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement, is hereby granted, provided that the above copyright notice,
// this paragraph and the following two paragraphs appear in all copies,
// modifications, and distributions.
//
// IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
// INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
// PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
// ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
// V3.0 03/08/2004 -Initial Version for sqlite3
//
// V3.1 16/09/2004 -Implemented getXXXXField using sqlite3 functions
// -Added CppSQLiteDB3::tableExists()
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "CppSQLite3.h"
#include <cstdlib>
// Named constant for passing to CppSQLite3Exception when passing it a string
// that cannot be deleted.
static const bool DONT_DELETE_MSG = false;
////////////////////////////////////////////////////////////////////////////////
// Prototypes for SQLite functions not included in SQLite DLL, but copied below
// from SQLite encode.c
////////////////////////////////////////////////////////////////////////////////
int sqlite3_encode_binary( const unsigned char *in, int n, unsigned char *out );
int sqlite3_decode_binary( const unsigned char *in, unsigned char *out );
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
CppSQLite3Exception::CppSQLite3Exception( const int nErrCode,
char* szErrMess,
bool bDeleteMsg/*=true*/ ) :
mnErrCode( nErrCode )
{
mpszErrMess = sqlite3_mprintf( "%s[%d]: %s",
errorCodeAsString( nErrCode ),
nErrCode,
szErrMess ? szErrMess : "" );
if (bDeleteMsg && szErrMess)
{
sqlite3_free( szErrMess );
}
}
CppSQLite3Exception::CppSQLite3Exception( const CppSQLite3Exception& e ) :
mnErrCode( e.mnErrCode )
{
mpszErrMess = 0;
if (e.mpszErrMess)
{
mpszErrMess = sqlite3_mprintf( "%s", e.mpszErrMess );
}
}
const char* CppSQLite3Exception::errorCodeAsString( int nErrCode )
{
switch (nErrCode)
{
case SQLITE_OK: return "SQLITE_OK";
case SQLITE_ERROR: return "SQLITE_ERROR";
case SQLITE_INTERNAL: return "SQLITE_INTERNAL";
case SQLITE_PERM: return "SQLITE_PERM";
case SQLITE_ABORT: return "SQLITE_ABORT";
case SQLITE_BUSY: return "SQLITE_BUSY";
case SQLITE_LOCKED: return "SQLITE_LOCKED";
case SQLITE_NOMEM: return "SQLITE_NOMEM";
case SQLITE_READONLY: return "SQLITE_READONLY";
case SQLITE_INTERRUPT: return "SQLITE_INTERRUPT";
case SQLITE_IOERR: return "SQLITE_IOERR";
case SQLITE_CORRUPT: return "SQLITE_CORRUPT";
case SQLITE_NOTFOUND: return "SQLITE_NOTFOUND";
case SQLITE_FULL: return "SQLITE_FULL";
case SQLITE_CANTOPEN: return "SQLITE_CANTOPEN";
case SQLITE_PROTOCOL: return "SQLITE_PROTOCOL";
case SQLITE_EMPTY: return "SQLITE_EMPTY";
case SQLITE_SCHEMA: return "SQLITE_SCHEMA";
case SQLITE_TOOBIG: return "SQLITE_TOOBIG";
case SQLITE_CONSTRAINT: return "SQLITE_CONSTRAINT";
case SQLITE_MISMATCH: return "SQLITE_MISMATCH";
case SQLITE_MISUSE: return "SQLITE_MISUSE";
case SQLITE_NOLFS: return "SQLITE_NOLFS";
case SQLITE_AUTH: return "SQLITE_AUTH";
case SQLITE_FORMAT: return "SQLITE_FORMAT";
case SQLITE_RANGE: return "SQLITE_RANGE";
case SQLITE_ROW: return "SQLITE_ROW";
case SQLITE_DONE: return "SQLITE_DONE";
case CPPSQLITE_ERROR: return "CPPSQLITE_ERROR";
default: return "UNKNOWN_ERROR";
}
}
CppSQLite3Exception::~CppSQLite3Exception( )
{
if (mpszErrMess)
{
sqlite3_free( mpszErrMess );
mpszErrMess = 0;
}
}
////////////////////////////////////////////////////////////////////////////////
CppSQLite3Buffer::CppSQLite3Buffer( )
{
mpBuf = 0;
}
CppSQLite3Buffer::~CppSQLite3Buffer( )
{
clear( );
}
void CppSQLite3Buffer::clear( )
{
if (mpBuf)
{
sqlite3_free( mpBuf );
mpBuf = 0;
}
}
const char* CppSQLite3Buffer::format( const char* szFormat, ... )
{
clear( );
va_list va;
va_start( va, szFormat );
mpBuf = sqlite3_vmprintf( szFormat, va );
va_end( va );
return mpBuf;
}
////////////////////////////////////////////////////////////////////////////////
CppSQLite3Binary::CppSQLite3Binary( ) :
mpBuf( 0 ),
mnBinaryLen( 0 ),
mnBufferLen( 0 ),
mnEncodedLen( 0 ),
mbEncoded( false )
{
}
CppSQLite3Binary::~CppSQLite3Binary( )
{
clear( );
}
void CppSQLite3Binary::setBinary( const unsigned char* pBuf, int nLen )
{
mpBuf = allocBuffer( nLen );
memcpy( mpBuf, pBuf, nLen );
}
void CppSQLite3Binary::setEncoded( const unsigned char* pBuf )
{
clear( );
mnEncodedLen = (int)strlen( (const char*)pBuf );
mnBufferLen = mnEncodedLen + 1; // Allow for NULL terminator
mpBuf = (unsigned char*)malloc( mnBufferLen );
if (!mpBuf)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Cannot allocate memory",
DONT_DELETE_MSG );
}
memcpy( mpBuf, pBuf, mnBufferLen );
mbEncoded = true;
}
const unsigned char* CppSQLite3Binary::getEncoded( )
{
if (!mbEncoded)
{
unsigned char* ptmp = (unsigned char*)malloc( mnBinaryLen );
memcpy( ptmp, mpBuf, mnBinaryLen );
mnEncodedLen = sqlite3_encode_binary( ptmp, mnBinaryLen, mpBuf );
free( ptmp );
mbEncoded = true;
}
return mpBuf;
}
const unsigned char* CppSQLite3Binary::getBinary( )
{
if (mbEncoded)
{
// in/out buffers can be the same
mnBinaryLen = sqlite3_decode_binary( mpBuf, mpBuf );
if (mnBinaryLen == -1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Cannot decode binary",
DONT_DELETE_MSG );
}
mbEncoded = false;
}
return mpBuf;
}
int CppSQLite3Binary::getBinaryLength( )
{
getBinary( );
return mnBinaryLen;
}
unsigned char* CppSQLite3Binary::allocBuffer( int nLen )
{
clear( );
// Allow extra space for encoded binary as per comments in
// SQLite encode.c See bottom of this file for implementation
// of SQLite functions use 3 instead of 2 just to be sure ;-)
mnBinaryLen = nLen;
mnBufferLen = 3 + (257 * nLen) / 254;
mpBuf = (unsigned char*)malloc( mnBufferLen );
if (!mpBuf)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Cannot allocate memory",
DONT_DELETE_MSG );
}
mbEncoded = false;
return mpBuf;
}
void CppSQLite3Binary::clear( )
{
if (mpBuf)
{
mnBinaryLen = 0;
mnBufferLen = 0;
free( mpBuf );
mpBuf = 0;
}
}
////////////////////////////////////////////////////////////////////////////////
CppSQLite3Query::CppSQLite3Query( )
{
mpVM = 0;
mbEof = true;
mnCols = 0;
mbOwnVM = false;
}
CppSQLite3Query::CppSQLite3Query( const CppSQLite3Query& rQuery )
{
mpVM = rQuery.mpVM;
// Only one object can own the VM
const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
mbEof = rQuery.mbEof;
mnCols = rQuery.mnCols;
mbOwnVM = rQuery.mbOwnVM;
}
CppSQLite3Query::CppSQLite3Query( sqlite3* pDB,
sqlite3_stmt* pVM,
bool bEof,
bool bOwnVM/*=true*/ )
{
mpDB = pDB;
mpVM = pVM;
mbEof = bEof;
mnCols = sqlite3_column_count( mpVM );
mbOwnVM = bOwnVM;
}
CppSQLite3Query::~CppSQLite3Query( )
{
try
{
finalize( );
}
catch (...)
{
}
}
CppSQLite3Query& CppSQLite3Query::operator=( const CppSQLite3Query& rQuery )
{
try
{
finalize( );
}
catch (...)
{
}
mpVM = rQuery.mpVM;
// Only one object can own the VM
const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
mbEof = rQuery.mbEof;
mnCols = rQuery.mnCols;
mbOwnVM = rQuery.mbOwnVM;
return *this;
}
int CppSQLite3Query::numFields( )
{
checkVM( );
return mnCols;
}
const char* CppSQLite3Query::fieldValue( int nField )
{
checkVM( );
if (nField < 0 || nField > mnCols - 1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid field index requested",
DONT_DELETE_MSG );
}
return (const char*)sqlite3_column_text( mpVM, nField );
}
const char* CppSQLite3Query::fieldValue( const char* szField )
{
int nField = fieldIndex( szField );
return (const char*)sqlite3_column_text( mpVM, nField );
}
int CppSQLite3Query::getIntField( int nField, int nNullValue/*=0*/ )
{
if (fieldDataType( nField ) == SQLITE_NULL)
{
return nNullValue;
}
else
{
return sqlite3_column_int( mpVM, nField );
}
}
int CppSQLite3Query::getIntField( const char* szField, int nNullValue/*=0*/ )
{
int nField = fieldIndex( szField );
return getIntField( nField, nNullValue );
}
double CppSQLite3Query::getFloatField( int nField, double fNullValue/*=0.0*/ )
{
if (fieldDataType( nField ) == SQLITE_NULL)
{
return fNullValue;
}
else
{
return sqlite3_column_double( mpVM, nField );
}
}
double CppSQLite3Query::getFloatField( const char* szField, double fNullValue/*=0.0*/ )
{
int nField = fieldIndex( szField );
return getFloatField( nField, fNullValue );
}
const char* CppSQLite3Query::getStringField( int nField, const char* szNullValue/*=""*/ )
{
if (fieldDataType( nField ) == SQLITE_NULL)
{
return szNullValue;
}
else
{
return (const char*)sqlite3_column_text( mpVM, nField );
}
}
const char* CppSQLite3Query::getStringField( const char* szField, const char* szNullValue/*=""*/ )
{
int nField = fieldIndex( szField );
return getStringField( nField, szNullValue );
}
const unsigned char* CppSQLite3Query::getBlobField( int nField, int& nLen )
{
checkVM( );
if (nField < 0 || nField > mnCols - 1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid field index requested",
DONT_DELETE_MSG );
}
nLen = sqlite3_column_bytes( mpVM, nField );
return (const unsigned char*)sqlite3_column_blob( mpVM, nField );
}
const unsigned char* CppSQLite3Query::getBlobField( const char* szField, int& nLen )
{
int nField = fieldIndex( szField );
return getBlobField( nField, nLen );
}
bool CppSQLite3Query::fieldIsNull( int nField )
{
return (fieldDataType( nField ) == SQLITE_NULL);
}
bool CppSQLite3Query::fieldIsNull( const char* szField )
{
int nField = fieldIndex( szField );
return (fieldDataType( nField ) == SQLITE_NULL);
}
int CppSQLite3Query::fieldIndex( const char* szField )
{
checkVM( );
if (szField)
{
for (int nField = 0; nField < mnCols; nField++)
{
const char* szTemp = sqlite3_column_name( mpVM, nField );
if (strcmp( szField, szTemp ) == 0)
{
return nField;
}
}
}
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid field name requested",
DONT_DELETE_MSG );
}
const char* CppSQLite3Query::fieldName( int nCol )
{
checkVM( );
if (nCol < 0 || nCol > mnCols - 1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid field index requested",
DONT_DELETE_MSG );
}
return sqlite3_column_name( mpVM, nCol );
}
const char* CppSQLite3Query::fieldDeclType( int nCol )
{
checkVM( );
if (nCol < 0 || nCol > mnCols - 1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid field index requested",
DONT_DELETE_MSG );
}
return sqlite3_column_decltype( mpVM, nCol );
}
int CppSQLite3Query::fieldDataType( int nCol )
{
checkVM( );
if (nCol < 0 || nCol > mnCols - 1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid field index requested",
DONT_DELETE_MSG );
}
return sqlite3_column_type( mpVM, nCol );
}
bool CppSQLite3Query::eof( )
{
checkVM( );
return mbEof;
}
void CppSQLite3Query::nextRow( )
{
checkVM( );
int nRet = sqlite3_step( mpVM );
if (nRet == SQLITE_DONE)
{
// no rows
mbEof = true;
}
else if (nRet == SQLITE_ROW)
{
// more rows, nothing to do
}
else
{
nRet = sqlite3_finalize( mpVM );
mpVM = 0;
const char* szError = sqlite3_errmsg( mpDB );
throw CppSQLite3Exception( nRet,
(char*)szError,
DONT_DELETE_MSG );
}
}
void CppSQLite3Query::finalize( )
{
if (mpVM && mbOwnVM)
{
int nRet = sqlite3_finalize( mpVM );
mpVM = 0;
if (nRet != SQLITE_OK)
{
const char* szError = sqlite3_errmsg( mpDB );
throw CppSQLite3Exception( nRet, (char*)szError, DONT_DELETE_MSG );
}
}
}
void CppSQLite3Query::checkVM( )
{
if (mpVM == 0)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Null Virtual Machine pointer",
DONT_DELETE_MSG );
}
}
////////////////////////////////////////////////////////////////////////////////
CppSQLite3Table::CppSQLite3Table( )
{
mpaszResults = 0;
mnRows = 0;
mnCols = 0;
mnCurrentRow = 0;
}
CppSQLite3Table::CppSQLite3Table( const CppSQLite3Table& rTable )
{
mpaszResults = rTable.mpaszResults;
// Only one object can own the results
const_cast<CppSQLite3Table&>(rTable).mpaszResults = 0;
mnRows = rTable.mnRows;
mnCols = rTable.mnCols;
mnCurrentRow = rTable.mnCurrentRow;
}
CppSQLite3Table::CppSQLite3Table( char** paszResults, int nRows, int nCols )
{
mpaszResults = paszResults;
mnRows = nRows;
mnCols = nCols;
mnCurrentRow = 0;
}
CppSQLite3Table::~CppSQLite3Table( )
{
try
{
finalize( );
}
catch (...)
{
}
}
CppSQLite3Table& CppSQLite3Table::operator=( const CppSQLite3Table& rTable )
{
try
{
finalize( );
}
catch (...)
{
}
mpaszResults = rTable.mpaszResults;
// Only one object can own the results
const_cast<CppSQLite3Table&>(rTable).mpaszResults = 0;
mnRows = rTable.mnRows;
mnCols = rTable.mnCols;
mnCurrentRow = rTable.mnCurrentRow;
return *this;
}
void CppSQLite3Table::finalize( )
{
if (mpaszResults)
{
sqlite3_free_table( mpaszResults );
mpaszResults = 0;
}
}
int CppSQLite3Table::numFields( )
{
checkResults( );
return mnCols;
}
int CppSQLite3Table::numRows( )
{
checkResults( );
return mnRows;
}
const char* CppSQLite3Table::fieldValue( int nField )
{
checkResults( );
if (nField < 0 || nField > mnCols - 1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid field index requested",
DONT_DELETE_MSG );
}
int nIndex = (mnCurrentRow*mnCols) + mnCols + nField;
return mpaszResults[nIndex];
}
const char* CppSQLite3Table::fieldValue( const char* szField )
{
checkResults( );
if (szField)
{
for (int nField = 0; nField < mnCols; nField++)
{
if (strcmp( szField, mpaszResults[nField] ) == 0)
{
int nIndex = (mnCurrentRow*mnCols) + mnCols + nField;
return mpaszResults[nIndex];
}
}
}
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid field name requested",
DONT_DELETE_MSG );
}
int CppSQLite3Table::getIntField( int nField, int nNullValue/*=0*/ )
{
if (fieldIsNull( nField ))
{
return nNullValue;
}
else
{
return atoi( fieldValue( nField ) );
}
}
int CppSQLite3Table::getIntField( const char* szField, int nNullValue/*=0*/ )
{
if (fieldIsNull( szField ))
{
return nNullValue;
}
else
{
return atoi( fieldValue( szField ) );
}
}
double CppSQLite3Table::getFloatField( int nField, double fNullValue/*=0.0*/ )
{
if (fieldIsNull( nField ))
{
return fNullValue;
}
else
{
return atof( fieldValue( nField ) );
}
}
double CppSQLite3Table::getFloatField( const char* szField, double fNullValue/*=0.0*/ )
{
if (fieldIsNull( szField ))
{
return fNullValue;
}
else
{
return atof( fieldValue( szField ) );
}
}
const char* CppSQLite3Table::getStringField( int nField, const char* szNullValue/*=""*/ )
{
if (fieldIsNull( nField ))
{
return szNullValue;
}
else
{
return fieldValue( nField );
}
}
const char* CppSQLite3Table::getStringField( const char* szField, const char* szNullValue/*=""*/ )
{
if (fieldIsNull( szField ))
{
return szNullValue;
}
else
{
return fieldValue( szField );
}
}
bool CppSQLite3Table::fieldIsNull( int nField )
{
checkResults( );
return (fieldValue( nField ) == 0);
}
bool CppSQLite3Table::fieldIsNull( const char* szField )
{
checkResults( );
return (fieldValue( szField ) == 0);
}
const char* CppSQLite3Table::fieldName( int nCol )
{
checkResults( );
if (nCol < 0 || nCol > mnCols - 1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid field index requested",
DONT_DELETE_MSG );
}
return mpaszResults[nCol];
}
void CppSQLite3Table::setRow( int nRow )
{
checkResults( );
if (nRow < 0 || nRow > mnRows - 1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid row index requested",
DONT_DELETE_MSG );
}
mnCurrentRow = nRow;
}
void CppSQLite3Table::checkResults( )
{
if (mpaszResults == 0)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Null Results pointer",
DONT_DELETE_MSG );
}
}
////////////////////////////////////////////////////////////////////////////////
CppSQLite3Statement::CppSQLite3Statement( )
{
mpDB = 0;
mpVM = 0;
}
CppSQLite3Statement::CppSQLite3Statement( const CppSQLite3Statement& rStatement )
{
mpDB = rStatement.mpDB;
mpVM = rStatement.mpVM;
// Only one object can own VM
const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
}
CppSQLite3Statement::CppSQLite3Statement( sqlite3* pDB, sqlite3_stmt* pVM )
{
mpDB = pDB;
mpVM = pVM;
}
CppSQLite3Statement::~CppSQLite3Statement( )
{
try
{
finalize( );
}
catch (...)
{
}
}
CppSQLite3Statement& CppSQLite3Statement::operator=( const CppSQLite3Statement& rStatement )
{
mpDB = rStatement.mpDB;
mpVM = rStatement.mpVM;
// Only one object can own VM
const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
return *this;
}
int CppSQLite3Statement::execDML( )
{
checkDB( );
checkVM( );
const char* szError = 0;
int nRet = sqlite3_step( mpVM );
if (nRet == SQLITE_DONE)
{
int nRowsChanged = sqlite3_changes( mpDB );
nRet = sqlite3_reset( mpVM );
if (nRet != SQLITE_OK)
{
szError = sqlite3_errmsg( mpDB );
throw CppSQLite3Exception( nRet, (char*)szError, DONT_DELETE_MSG );
}
return nRowsChanged;
}
else
{
nRet = sqlite3_reset( mpVM );
szError = sqlite3_errmsg( mpDB );
throw CppSQLite3Exception( nRet, (char*)szError, DONT_DELETE_MSG );
}
}
CppSQLite3Query CppSQLite3Statement::execQuery( )
{
checkDB( );
checkVM( );
int nRet = sqlite3_step( mpVM );
if (nRet == SQLITE_DONE)
{
// no rows
return CppSQLite3Query( mpDB, mpVM, true/*eof*/, false );
}
else if (nRet == SQLITE_ROW)
{
// at least 1 row
return CppSQLite3Query( mpDB, mpVM, false/*eof*/, false );
}
else
{
nRet = sqlite3_reset( mpVM );
const char* szError = sqlite3_errmsg( mpDB );
throw CppSQLite3Exception( nRet, (char*)szError, DONT_DELETE_MSG );
}
}
void CppSQLite3Statement::bind( int nParam, const char* szValue )
{
checkVM( );
int nRes = sqlite3_bind_text( mpVM, nParam, szValue, -1, SQLITE_TRANSIENT );
if (nRes != SQLITE_OK)
{
throw CppSQLite3Exception( nRes,
"Error binding string param",
DONT_DELETE_MSG );
}
}
void CppSQLite3Statement::bind( int nParam, const int nValue )
{
checkVM( );
int nRes = sqlite3_bind_int( mpVM, nParam, nValue );
if (nRes != SQLITE_OK)
{
throw CppSQLite3Exception( nRes,
"Error binding int param",
DONT_DELETE_MSG );
}
}
void CppSQLite3Statement::bind( int nParam, const double dValue )
{
checkVM( );
int nRes = sqlite3_bind_double( mpVM, nParam, dValue );
if (nRes != SQLITE_OK)
{
throw CppSQLite3Exception( nRes,
"Error binding double param",
DONT_DELETE_MSG );
}
}
void CppSQLite3Statement::bind( int nParam, const unsigned char* blobValue, int nLen )
{
checkVM( );
int nRes = sqlite3_bind_blob( mpVM, nParam,
(const void*)blobValue, nLen, SQLITE_TRANSIENT );
if (nRes != SQLITE_OK)
{
throw CppSQLite3Exception( nRes,
"Error binding blob param",
DONT_DELETE_MSG );
}
}
void CppSQLite3Statement::bindNull( int nParam )
{
checkVM( );
int nRes = sqlite3_bind_null( mpVM, nParam );
if (nRes != SQLITE_OK)
{
throw CppSQLite3Exception( nRes,
"Error binding NULL param",
DONT_DELETE_MSG );
}
}
void CppSQLite3Statement::reset( )
{
if (mpVM)
{
int nRet = sqlite3_reset( mpVM );
if (nRet != SQLITE_OK)
{
const char* szError = sqlite3_errmsg( mpDB );
throw CppSQLite3Exception( nRet, (char*)szError, DONT_DELETE_MSG );
}
}
}
void CppSQLite3Statement::finalize( )
{
if (mpVM)
{
int nRet = sqlite3_finalize( mpVM );
mpVM = 0;
if (nRet != SQLITE_OK)
{
const char* szError = sqlite3_errmsg( mpDB );
throw CppSQLite3Exception( nRet, (char*)szError, DONT_DELETE_MSG );
}
}
}
void CppSQLite3Statement::checkDB( )
{
if (mpDB == 0)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Database not open",
DONT_DELETE_MSG );
}
}
void CppSQLite3Statement::checkVM( )
{
if (mpVM == 0)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Null Virtual Machine pointer",
DONT_DELETE_MSG );
}
}
////////////////////////////////////////////////////////////////////////////////
CppSQLite3DB::CppSQLite3DB( )
{
mpDB = 0;
mnBusyTimeoutMs = 60000; // 60 seconds
}
CppSQLite3DB::CppSQLite3DB( const CppSQLite3DB& db )
{
mpDB = db.mpDB;
mnBusyTimeoutMs = 60000; // 60 seconds
}
CppSQLite3DB::~CppSQLite3DB( )
{
close( );
}
CppSQLite3DB& CppSQLite3DB::operator=( const CppSQLite3DB& db )
{
mpDB = db.mpDB;
mnBusyTimeoutMs = 60000; // 60 seconds
return *this;
}
void CppSQLite3DB::open( const char* szFile )
{
int nRet = sqlite3_open( szFile, &mpDB );
if (nRet != SQLITE_OK)
{
const char* szError = sqlite3_errmsg( mpDB );
throw CppSQLite3Exception( nRet, (char*)szError, DONT_DELETE_MSG );
}
setBusyTimeout( mnBusyTimeoutMs );
}
void CppSQLite3DB::close( )
{
if (mpDB)
{
sqlite3_close( mpDB );
mpDB = 0;
}
}
CppSQLite3Statement CppSQLite3DB::compileStatement( const char* szSQL )
{
checkDB( );
sqlite3_stmt* pVM = compile( szSQL );
return CppSQLite3Statement( mpDB, pVM );
}
bool CppSQLite3DB::tableExists( const char* szTable )
{
char szSQL[128];
sprintf( szSQL,
"select count(*) from sqlite_master where type='table' and name='%s'",
szTable );
int nRet = execScalar( szSQL );
return (nRet > 0);
}
int CppSQLite3DB::execDML( const char* szSQL )
{
checkDB( );
char* szError = 0;
int nRet = sqlite3_exec( mpDB, szSQL, 0, 0, &szError );
if (nRet == SQLITE_OK)
{
return sqlite3_changes( mpDB );
}
else
{
throw CppSQLite3Exception( nRet, szError );
}
}
CppSQLite3Query CppSQLite3DB::execQuery( const char* szSQL )
{
checkDB( );
sqlite3_stmt* pVM = compile( szSQL );
int nRet = sqlite3_step( pVM );
if (nRet == SQLITE_DONE)
{
// no rows
return CppSQLite3Query( mpDB, pVM, true/*eof*/ );
}
else if (nRet == SQLITE_ROW)
{
// at least 1 row
return CppSQLite3Query( mpDB, pVM, false/*eof*/ );
}
else
{
nRet = sqlite3_finalize( pVM );
const char* szError = sqlite3_errmsg( mpDB );
throw CppSQLite3Exception( nRet, (char*)szError, DONT_DELETE_MSG );
}
}
int CppSQLite3DB::execScalar( const char* szSQL )
{
CppSQLite3Query q = execQuery( szSQL );
if (q.eof( ) || q.numFields( ) < 1)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Invalid scalar query",
DONT_DELETE_MSG );
}
return atoi( q.fieldValue( 0 ) );
}
CppSQLite3Table CppSQLite3DB::getTable( const char* szSQL )
{
checkDB( );
char* szError = 0;
char** paszResults = 0;
int nRet;
int nRows( 0 );
int nCols( 0 );
nRet = sqlite3_get_table( mpDB, szSQL, &paszResults, &nRows, &nCols, &szError );
if (nRet == SQLITE_OK)
{
return CppSQLite3Table( paszResults, nRows, nCols );
}
else
{
throw CppSQLite3Exception( nRet, szError );
}
}
sqlite_int64 CppSQLite3DB::lastRowId( )
{
return sqlite3_last_insert_rowid( mpDB );
}
void CppSQLite3DB::setBusyTimeout( int nMillisecs )
{
mnBusyTimeoutMs = nMillisecs;
sqlite3_busy_timeout( mpDB, mnBusyTimeoutMs );
}
void CppSQLite3DB::checkDB( )
{
if (!mpDB)
{
throw CppSQLite3Exception( CPPSQLITE_ERROR,
"Database not open",
DONT_DELETE_MSG );
}
}
sqlite3_stmt* CppSQLite3DB::compile( const char* szSQL )
{
checkDB( );
char* szError = 0;
const char* szTail = 0;
sqlite3_stmt* pVM;
int nRet = sqlite3_prepare( mpDB, szSQL, -1, &pVM, &szTail );
if (nRet != SQLITE_OK)
{
throw CppSQLite3Exception( nRet, szError );
}
return pVM;
}
////////////////////////////////////////////////////////////////////////////////
// SQLite encode.c reproduced here, containing implementation notes and source
// for sqlite3_encode_binary() and sqlite3_decode_binary()
////////////////////////////////////////////////////////////////////////////////
/*
** 2002 April 25
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains helper routines used to translate binary data into
** a null-terminated string (suitable for use in SQLite) and back again.
** These are convenience routines for use by people who want to store binary
** data in an SQLite database. The code in this file is not used by any other
** part of the SQLite library.
**
** $Id: CppSQLite3.cpp,v 1.1 2007/03/28 18:39:20 m Exp $
*/
/*
** How This Encoder Works
**
** The output is allowed to contain any character except 0x27 (') and
** 0x00. This is accomplished by using an escape character to encode
** 0x27 and 0x00 as a two-byte sequence. The escape character is always
** 0x01. An 0x00 is encoded as the two byte sequence 0x01 0x01. The
** 0x27 character is encoded as the two byte sequence 0x01 0x03. Finally,
** the escape character itself is encoded as the two-character sequence
** 0x01 0x02.
**
** To summarize, the encoder works by using an escape sequences as follows:
**
** 0x00 -> 0x01 0x01
** 0x01 -> 0x01 0x02
** 0x27 -> 0x01 0x03
**
** If that were all the encoder did, it would work, but in certain cases
** it could double the size of the encoded string. For example, to
** encode a string of 100 0x27 characters would require 100 instances of
** the 0x01 0x03 escape sequence resulting in a 200-character output.
** We would prefer to keep the size of the encoded string smaller than
** this.
**
** To minimize the encoding size, we first add a fixed offset value to each
** byte in the sequence. The addition is modulo 256. (That is to say, if
** the sum of the original character value and the offset exceeds 256, then
** the higher order bits are truncated.) The offset is chosen to minimize
** the number of characters in the string that need to be escaped. For
** example, in the case above where the string was composed of 100 0x27
** characters, the offset might be 0x01. Each of the 0x27 characters would
** then be converted into an 0x28 character which would not need to be
** escaped at all and so the 100 character input string would be converted
** into just 100 characters of output. Actually 101 characters of output -
** we have to record the offset used as the first byte in the sequence so
** that the string can be decoded. Since the offset value is stored as
** part of the output string and the output string is not allowed to contain
** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
**
** Here, then, are the encoding steps:
**
** (1) Choose an offset value and make it the first character of
** output.
**
** (2) Copy each input character into the output buffer, one by
** one, adding the offset value as you copy.
**
** (3) If the value of an input character plus offset is 0x00, replace
** that one character by the two-character sequence 0x01 0x01.
** If the sum is 0x01, replace it with 0x01 0x02. If the sum
** is 0x27, replace it with 0x01 0x03.
**
** (4) Put a 0x00 terminator at the end of the output.
**
** Decoding is obvious:
**
** (5) Copy encoded characters except the first into the decode
** buffer. Set the first encoded character aside for use as
** the offset in step 7 below.
**
** (6) Convert each 0x01 0x01 sequence into a single character 0x00.
** Convert 0x01 0x02 into 0x01. Convert 0x01 0x03 into 0x27.
**
** (7) Subtract the offset value that was the first character of
** the encoded buffer from all characters in the output buffer.
**
** The only tricky part is step (1) - how to compute an offset value to
** minimize the size of the output buffer. This is accomplished by testing
** all offset values and picking the one that results in the fewest number
** of escapes. To do that, we first scan the entire input and count the
** number of occurances of each character value in the input. Suppose
** the number of 0x00 characters is N(0), the number of occurances of 0x01
** is N(1), and so forth up to the number of occurances of 0xff is N(255).
** An offset of 0 is not allowed so we don't have to test it. The number
** of escapes required for an offset of 1 is N(1)+N(2)+N(40). The number
** of escapes required for an offset of 2 is N(2)+N(3)+N(41). And so forth.
** In this way we find the offset that gives the minimum number of escapes,
** and thus minimizes the length of the output string.
*/
/*
** Encode a binary buffer "in" of size n bytes so that it contains
** no instances of characters '\'' or '\000'. The output is
** null-terminated and can be used as a string value in an INSERT
** or UPDATE statement. Use sqlite3_decode_binary() to convert the
** string back into its original binary.
**
** The result is written into a preallocated output buffer "out".
** "out" must be able to hold at least 2 +(257*n)/254 bytes.
** In other words, the output will be expanded by as much as 3
** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
**
** The return value is the number of characters in the encoded
** string, excluding the "\000" terminator.
*/
int sqlite3_encode_binary( const unsigned char *in, int n, unsigned char *out )
{
int i, j, e, m;
int cnt[256];
if (n <= 0)
{
out[0] = 'x';
out[1] = 0;
return 1;
}
memset( cnt, 0, sizeof( cnt ) );
for (i = n - 1; i >= 0; i--) { cnt[in[i]]++; }
m = n;
for (i = 1; i < 256; i++)
{
int sum;
if (i == '\'') continue;
sum = cnt[i] + cnt[(i + 1) & 0xff] + cnt[(i + '\'') & 0xff];
if (sum < m)
{
m = sum;
e = i;
if (m == 0) break;
}
}
out[0] = e;
j = 1;
for (i = 0; i < n; i++)
{
int c = (in[i] - e) & 0xff;
if (c == 0)
{
out[j++] = 1;
out[j++] = 1;
}
else if (c == 1)
{
out[j++] = 1;
out[j++] = 2;
}
else if (c == '\'')
{
out[j++] = 1;
out[j++] = 3;
}
else
{
out[j++] = c;
}
}
out[j] = 0;
return j;
}
/*
** Decode the string "in" into binary data and write it into "out".
** This routine reverses the encoding created by sqlite3_encode_binary().
** The output will always be a few bytes less than the input. The number
** of bytes of output is returned. If the input is not a well-formed
** encoding, -1 is returned.
**
** The "in" and "out" parameters may point to the same buffer in order
** to decode a string in place.
*/
int sqlite3_decode_binary( const unsigned char *in, unsigned char *out )
{
int i, c, e;
e = *(in++);
i = 0;
while ((c = *(in++)) != 0)
{
if (c == 1)
{
c = *(in++);
if (c == 1)
{
c = 0;
}
else if (c == 2)
{
c = 1;
}
else if (c == 3)
{
c = '\'';
}
else
{
return -1;
}
}
out[i++] = (c + e) & 0xff;
}
return i;
}
| [
"[email protected]"
] | |
3d97d2a46bc0632314147d8334e3f53b6d9c4d43 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/MuonSpectrometer/MuonGeoModel/MuonGeoModel/MYSQL.h | 556c6319369308aef9bac57378fa3a677a8eb29e | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,624 | h | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#ifndef MYSQL_H
#define MYSQL_H
#include <map>
#include <string>
#include "MuonGeoModel/Station.h"
#include "MuonGeoModel/Position.h"
#include "GaudiKernel/MsgStream.h"
#include "AthenaKernel/getMessageSvc.h"
/*
This class holds an std::map of stations* (key = stationName, i.e. BMS5),
an std::map of Technolgies* (key = RPC20), and an std::map of TgcReadoutParams*.
Stations and Technolgies are used only to build the geometry (can be deleted
after that).
TgcReadoutParams are used by the TgcReadoutElements -> must leave forever
(they belong to the readout geometry).
MYSQL is used only to build the geometry - can be deleted as soon as the job is
done (in the Factory).
It is responsible for releasing the memory allocated by these objects.
*/
namespace MuonGM {
class Technology;
class TgcReadoutParams;
typedef std::map<std::string,Station* >::const_iterator StationIterator;
typedef std::map<std::string,TgcReadoutParams* >::const_iterator TgcReadParsIterator;
typedef std::map<int, std::string>::const_iterator AllocposIterator;
typedef std::map<std::string, int>::const_iterator allocPosIterator;
class MYSQL {
public:
enum TgcReadoutRange
{
NTgcReadouts = 30
};
~MYSQL();
inline bool amdb_from_RDB() const;
inline void set_amdb_from_RDB(bool );
inline void set_DBMuonVersion(std::string );
inline std::string get_DBMuonVersion();
inline void setGeometryVersion(std::string s);
inline std::string getGeometryVersion() const;
inline void setCtbBisFlag(int i);
inline int getCtbBisFlag() const;
inline void setLayoutName(std::string s);
inline std::string getLayoutName() const;
inline void setCutoutsBogFlag(int i);
inline int getCutoutsBogFlag() const;
inline void setNovaVersion(int i);
inline int getNovaVersion() const;
inline void setNovaReadVersion(int i);
inline int getNovaReadVersion() const;
inline void setControlAlines(int );
inline int controlAlines() const;
inline StationIterator StationBegin();
inline StationIterator StationEnd();
inline TgcReadParsIterator TgcRParsBegin();
inline TgcReadParsIterator TgcRParsend();
inline AllocposIterator AllocposBegin();
inline AllocposIterator AllocposEnd();
inline AllocposIterator AllocposFind(int );
inline std::string AllocposFindName(int );
inline void addAllocpos(int i, std::string str);
// the new ones
std::string allocPosBuildKey(std::string statType, int fi, int zi);
inline int allocPosBuildValue(int subtype, int cutout);
inline allocPosIterator allocPosBegin();
inline allocPosIterator allocPosEnd();
inline allocPosIterator allocPosFind(std::string key);
allocPosIterator allocPosFind(std::string statType, int fi, int zi);
int allocPosFindSubtype(std::string statType, int fi, int zi);
inline int allocPosFindSubtype(std::string key);
inline int allocPosFindSubtype(allocPosIterator it);
int allocPosFindCutout(std::string statType, int fi, int zi);
inline int allocPosFindCutout(std::string key);
inline int allocPosFindCutout(allocPosIterator it);
inline void addallocPos(std::string key, int value);
void addallocPos(std::string statType, int fi, int zi, int subtyp, int cutout);
inline void addallocPos(std::string key, int subtype, int cutout);
inline int NStations();
inline int NTgcReadTypes();
static MYSQL* GetPointer();
Station* GetStation(std::string name);
Position GetStationPosition(std::string nameType, int fi, int zi);
TgcReadoutParams* GetTgcRPars(std::string name);
TgcReadoutParams* GetTgcRPars(int i);
void StoreStation(Station *s);
void PrintAllStations();
void StoreTechnology(Technology *t);
void StoreTgcRPars(TgcReadoutParams *t);
Technology* GetTechnology(std::string name);
Technology* GetATechnology(std::string name);
void PrintTechnologies();
MsgStream& reLog() const {return *m_MsgStream;}
// singleton
private:
static MYSQL* s_thePointer;
MYSQL();
std::map<int, std::string> m_allocatedpos;
std::map<std::string, int> m_allocPos;
std::map<std::string, Station* > m_stations;
std::map<std::string,Technology* > m_technologies;
std::map<std::string, TgcReadoutParams* > m_tgcReadouts;
TgcReadoutParams *m_tgcReadout[NTgcReadouts];
std::string m_geometry_version; //from our job-option
std::string m_layout_name; //from nova
std::string m_DBMuonVersion; //name of the MuonVersion table-collection in Oracle
int m_nova_version;
int m_amdb_version;
bool m_amdb_from_rdb;
int m_includeCutoutsBog;
int m_includeCtbBis;
int m_controlAlines;
MsgStream* m_MsgStream;
};
void MYSQL::addAllocpos(int i, std::string str)
{
// std::cout<<" trying to declare pos. at key "<<i<<" for station "<<str<<std::endl;
m_allocatedpos[i]= str;
// std::cout<<" declaring pos. at key "<<i<<" allocated to station "<<str<<std::endl;
}
AllocposIterator MYSQL::AllocposEnd()
{
return m_allocatedpos.end();
}
AllocposIterator MYSQL::AllocposBegin()
{
return m_allocatedpos.begin();
}
AllocposIterator MYSQL::AllocposFind(int i)
{
return m_allocatedpos.find(i);
}
std::string MYSQL::AllocposFindName(int i)
{
AllocposIterator it = m_allocatedpos.find(i);
// imt fix in case key is wrong:
if (it != m_allocatedpos.end())
return (*it).second;
else
return "ERROR: bad key!";
}
StationIterator MYSQL::StationBegin()
{
return m_stations.begin();
}
StationIterator MYSQL::StationEnd()
{
return m_stations.end();
}
TgcReadParsIterator MYSQL::TgcRParsBegin()
{
return m_tgcReadouts.begin();
}
TgcReadParsIterator MYSQL::TgcRParsend()
{
return m_tgcReadouts.end();
}
int MYSQL::NStations()
{
return m_stations.size();
}
int MYSQL::NTgcReadTypes()
{
return m_tgcReadouts.size();
}
int MYSQL::allocPosBuildValue(int subtype, int cutout)
{
return 100*subtype+cutout;
}
allocPosIterator MYSQL::allocPosBegin()
{
return m_allocPos.begin();
}
allocPosIterator MYSQL::allocPosEnd()
{
return m_allocPos.end();
}
allocPosIterator MYSQL::allocPosFind(std::string key)
{
return m_allocPos.find(key);
}
int MYSQL::allocPosFindSubtype(std::string key)
{
int subtype = 0;
allocPosIterator it = m_allocPos.find(key);
if (it != allocPosEnd())
{
return allocPosFindSubtype(it);
}
std::cerr<<"MYSQL::allocPosFindSubtype for key "<<key<<" no element found"<<std::endl;
return subtype;
}
int MYSQL::allocPosFindSubtype(allocPosIterator it)
{
int value = it->second;
int subtype = int(value/100);
return subtype;
}
int MYSQL::allocPosFindCutout(std::string key)
{
int cutout = 0;
allocPosIterator it = m_allocPos.find(key);
if (it != allocPosEnd())
{
return allocPosFindCutout(it);
}
std::cerr<<"MYSQL::allocPosFindCutout for key "<<key
<<" no element found"<<std::endl;
return cutout;
}
int MYSQL::allocPosFindCutout(allocPosIterator it)
{
int value = (*it).second;
int cutout = int(value%100);
return cutout;
}
void MYSQL::addallocPos(std::string key, int value)
{
m_allocPos[key]= value;
}
void MYSQL::addallocPos(std::string key, int subtype, int cutout)
{
m_allocPos[key]= allocPosBuildValue(subtype, cutout);
}
void MYSQL::setGeometryVersion(std::string s)
{
if (m_geometry_version != "unknown")
{
if (s == m_geometry_version) return;
reLog()<<MSG::WARNING<<"GeometryVersion already set to <"<< m_geometry_version<<">"<<" resetting to <"<<s<<">"<<endmsg;
}
m_geometry_version = s;
reLog()<<MSG::INFO<<"GeometryVersion set to <"<< m_geometry_version<<">"<<endmsg;
}
std::string MYSQL::getGeometryVersion() const
{return m_geometry_version;}
void MYSQL::setCtbBisFlag(int i)
{
m_includeCtbBis = i;
}
int MYSQL::getCtbBisFlag() const
{return m_includeCtbBis;}
void MYSQL::setNovaReadVersion(int i)
{
m_amdb_version = i;
if (reLog().level()<=MSG::VERBOSE) reLog()<<MSG::VERBOSE<<"setNovaReadVersion to "<< m_amdb_version<<endmsg;
}
int MYSQL::getNovaReadVersion() const
{return m_amdb_version;}
void MYSQL::setLayoutName(std::string s)
{
if (m_layout_name != "unknown")
{
if (s == m_layout_name) return;
reLog()<<MSG::WARNING<<"LayoutName already set to <"<< m_layout_name<<">"<<" resetting to <"<<s<<">"<<endmsg;
}
m_layout_name = s;
reLog()<<MSG::INFO<<"LayoutName (from DBAM) set to <"<< m_layout_name<<"> -- relevant for CTB2004"<<endmsg;
}
std::string MYSQL::getLayoutName() const
{return m_layout_name;}
void MYSQL::setCutoutsBogFlag(int i)
{
m_includeCutoutsBog = i;
}
int MYSQL::getCutoutsBogFlag() const
{
return m_includeCutoutsBog;
}
void MYSQL::setNovaVersion(int i)
{
m_nova_version = i;
if (reLog().level()<=MSG::VERBOSE) reLog()<<MSG::VERBOSE<<"setNovaVersion to "<< m_nova_version<<endmsg;
}
int MYSQL::getNovaVersion() const
{
return m_nova_version;
}
bool MYSQL::amdb_from_RDB() const
{
return m_amdb_from_rdb;
}
void MYSQL::set_amdb_from_RDB(bool val)
{
m_amdb_from_rdb = val;
}
void MYSQL::set_DBMuonVersion(std::string a)
{
m_DBMuonVersion = a;
}
std::string MYSQL::get_DBMuonVersion()
{
return m_DBMuonVersion;
}
void MYSQL::setControlAlines(int cA) {m_controlAlines = cA;}
int MYSQL::controlAlines() const {return m_controlAlines;}
} // namespace MuonGM
#endif
| [
"[email protected]"
] | |
7b944de322e6a10d1e2c942b67ef07e96cab2a7a | d754ba23c8ff391ce9dcefcfae3b90cef16ecde0 | /DMOJ/BackToSchool/bts18p4.cpp | 37c55ab1f394a895d42ca5c9152ff338315f8d2c | [] | no_license | TruVortex/Competitive-Programming | 3edc0838aef41128a27fdc7f47d704adbf2c3f38 | 3812ff630488d7589754ff25a3eefd8898226301 | refs/heads/master | 2023-05-10T01:48:00.996120 | 2021-06-02T03:36:35 | 2021-06-02T03:36:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | #include <bits/stdc++.h>
using namespace std;
static inline __attribute__((always_inline)) bool valid(long long y)
{
long double val = sqrt(1+4*y);
if (abs((long long)val-val) <= 1e-10)
return ((long long)val)&1;
return false;
}
const int MAXN = 100010;
vector<bool> val(MAXN), vis(MAXN);
vector<vector<int>> adj(MAXN);
void dfs(int u, int p, int d, int &mD, int &mN)
{
vis[u] = true;
if (d > mD)
mD = d, mN = u;
for (auto &x : adj[u])
if ((x ^ p) && val[x])
dfs(x, u, d+1, mD, mN);
}
int main()
{
int n, a, b, ma = 0;
long long y;
scanf("%i", &n);
for (int x = 1; x <= n; x++)
{
scanf("%lli", &y);
val[x] = valid(y);
}
for (int x = 1; x < n; x++)
{
scanf("%i%i", &a, &b);
adj[a].push_back(b);
adj[b].push_back(a);
}
for (int x = 1; x <= n; x++)
{
if (!vis[x] && val[x])
{
int mD = 0, mN = 0;
dfs(x, x, 1, mD, mN);
dfs(mN, mN, 1, mD=0, mN);
ma = max(ma, mD);
}
}
printf("%i\n", ma);
}
| [
"[email protected]"
] | |
d03277921aff95cafc66f8d285e4cedc30cbebf5 | 2b1bff70fcce2359a158c2960994c539e1cc3057 | /include/MenuManager.hpp | 791702e00b9432ef4401697e820045a351c3d2e8 | [] | no_license | VictorLuc4/Boomberman | 39e3d40c63e0b8e219bf7910cee8230df1df0809 | 9f73ebad57f66e4361498118f1f7927fb6f5f986 | refs/heads/master | 2020-04-05T04:07:36.393193 | 2018-11-07T11:53:24 | 2018-11-07T11:53:24 | 156,538,442 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | hpp | /*
** EPITECH PROJECT, 2018
** cpp_indie_studio
** File description:
** MenuManager
*/
#ifndef MENUMANAGER_HPP_
#define MENUMANAGER_HPP_
#include "MenuGui.hpp"
#include "MainMenuGui.hpp"
#include "OptionMenuGui.hpp"
#include "NewGameMenuGui.hpp"
#include "HudGui.hpp"
#include "VictoryGui.hpp"
class MenuManager {
public:
MenuManager(irr::IrrlichtDevice *, InfoMenu *infoMenu);
~MenuManager() = default;
MenuGui *getCurrentGui();
MenuGui *getPreviousGui() const;
InfoMenu *getInfoMenu();
private:
MenuGui *_currentGui;
MenuGui *_previousGui;
std::map<MenuType, MenuGui *> _menus;
irr::IrrlichtDevice *_device;
InfoMenu *_infoMenu;
};
#endif /* !MENUMANAGER_HPP_ */ | [
"[email protected]"
] | |
4fa7820741183ee705009da7f985736cbf7fd2a0 | 55d560fe6678a3edc9232ef14de8fafd7b7ece12 | /libs/process/test/vfork.cpp | c0abeff771fc361fe2182a790a435bf706bec37f | [
"BSL-1.0"
] | permissive | stardog-union/boost | ec3abeeef1b45389228df031bf25b470d3d123c5 | caa4a540db892caa92e5346e0094c63dea51cbfb | refs/heads/stardog/develop | 2021-06-25T02:15:10.697006 | 2020-11-17T19:50:35 | 2020-11-17T19:50:35 | 148,681,713 | 0 | 0 | BSL-1.0 | 2020-11-17T19:50:36 | 2018-09-13T18:38:54 | C++ | UTF-8 | C++ | false | false | 1,912 | cpp | // Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_TEST_MAIN
#define BOOST_TEST_IGNORE_SIGCHLD
#include <boost/test/included/unit_test.hpp>
#include <boost/process.hpp>
#include <boost/process/posix.hpp>
#include <system_error>
#include <string>
#include <sys/wait.h>
#include <errno.h>
namespace bp = boost::process;
#if defined(BOOST_POSIX_HAS_VFORK)
BOOST_AUTO_TEST_CASE(bind_fd, *boost::unit_test::timeout(2))
{
using boost::unit_test::framework::master_test_suite;
bp::pipe p;
std::error_code ec;
bp::child c(
master_test_suite().argv[1],
"test", "--posix-echo-one", "3", "hello",
bp::posix::fd.bind(3, p.native_sink()),
bp::posix::use_vfork,
ec
);
BOOST_CHECK(!ec);
bp::ipstream is(std::move(p));
std::string s;
is >> s;
BOOST_CHECK_EQUAL(s, "hello");
}
BOOST_AUTO_TEST_CASE(execve_set_on_error, *boost::unit_test::timeout(2))
{
std::error_code ec;
bp::spawn(
"doesnt-exist",
bp::posix::use_vfork,
ec
);
BOOST_CHECK(ec);
BOOST_CHECK_EQUAL(ec.value(), ENOENT);
}
BOOST_AUTO_TEST_CASE(execve_throw_on_error, *boost::unit_test::timeout(2))
{
try
{
bp::spawn("doesnt-exist", bp::posix::use_vfork);
BOOST_CHECK(false);
}
catch (std::system_error &e)
{
BOOST_CHECK(e.code());
BOOST_CHECK_EQUAL(e.code().value(), ENOENT);
}
}
#else
BOOST_AUTO_TEST_CASE(dummy) {}
#endif
| [
"[email protected]"
] | |
194f834ca7292a8e2382b8756132574371c4140a | 2bb98b4a6e2a95e5471614b49dc395380e385254 | /arduino_src/backups/cablecontrol.ino | ac8011cebe3b8206c52ab5291944b3ed8256c3f5 | [] | no_license | stashako/minirover_ROS | 4c7d5f8a75f2f71de25b23024549468d8c7442d7 | abe4fcdb69c37aeae3bf846fadb278503906df02 | refs/heads/master | 2020-05-07T19:25:03.515853 | 2019-04-11T15:20:07 | 2019-04-11T15:20:07 | 180,812,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,370 | ino | /*
This example code uses bogde's excellent library: https://github.com/bogde/HX711
bogde's library is released under a GNU GENERAL PUBLIC LICENSE
The HX711 does one thing well: read load cells. The breakout board is compatible with any wheat-stone bridge
based load cell which should allow a user to measure everything from a few grams to tens of tons.
Arduino pin 2 -> HX711 CLK
3 -> DAT
5V -> VCC
GND -> GND
The HX711 board can be powered from 2.7V to 5V so the Arduino 5V power should be fine.
*/
//*****HX711 load cell*****//
#include "HX711.h"
#define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch
#define DOUT 11
#define CLK 10
HX711 scale(DOUT, CLK);
float loadVal = 0.0;
//******opto photodetector for RPM counter******//
int IR_DETECTOR_PIN = A0;
int sensorValue = 0;
int HIGH_VAL = 1000; // anything above this value is considered high value.
int previousVal = sensorValue;
bool isCW = true; //signifies if the wheel is rotating CW
//hardware
int numHoles = 20; //20 holes for the encoded wheels
//wheel diameter = 44.45 mm
const float distOfSignChanged = (44.45*3.14159/20)/2; // (2*pi*r/radius)/20 in mm
float cLen = 0.0; // in mm
//************************start*****************************//
void setup() {
Serial.begin(9600);
scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0
sensorValue = analogRead(IR_DETECTOR_PIN);
previousVal = sensorValue;
}
void loop() {
// obtain latest scale reading
loadVal = getScaleReading();
//read the opto switch value
sensorValue = analogRead(IR_DETECTOR_PIN);
if (sensorValue >= HIGH_VAL && previousVal < HIGH_VAL)
{
previousVal = sensorValue;
cLen = getCableLength(cLen,true);
}
else if(sensorValue < HIGH_VAL && previousVal >= HIGH_VAL)
{
previousVal = sensorValue;
cLen = getCableLength(cLen,true);
}
}
//****compute the cable length based on diameter of the wheel****//
float getCableLength(float cLen, bool isCW)
{
if(isCW)
return cLen + distOfSignChanged;
else
return cLen - distOfSignChanged;
}
//****read the value from the load cell****//
float getScaleReading()
{
return scale.get_units();
}
| [
"[email protected]"
] | |
75dd5279b4ff04c60500ed95af2a9dd92278e9d5 | 5d757829d285c9f7c1ba17387ab84f8692adad45 | /Easy Problems/singleNumber.cpp | 7c8662fe072006f31858c763eea1e65ae160d52d | [
"MIT"
] | permissive | yigittin/Leet-Solves | cbc17b8e41f2521dcab385c79e42a290a085cf67 | 8c9a4f911be9f9cbad2948c61de37dfa2e898919 | refs/heads/master | 2023-06-18T07:49:35.139540 | 2021-07-06T13:34:24 | 2021-07-06T13:34:24 | 378,749,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | cpp | class Solution {
public:
int singleNumber(vector<int>& nums) {
int n=nums.size();
sort(nums.begin(),nums.begin()+n);
if(n==1){
return nums[0];
}
for(int i=0;i<n;i=i+2){
if(nums[i]!=nums[i+1]){
return nums[i];
}
}
return 0;
}
}; | [
"[email protected]"
] | |
adeeaad82fdc86417e7c60fe3d70e0e77033fd80 | 1e9fbdb90fa4fd3d2c97fc8a45541461ce8ec67f | /src/2016.Hangman/Marych/Hangsman/Source.cpp | 6661435f768f48b5fbf43a1d6081835bc2479ab9 | [] | no_license | vnobis-univ/sonarcube-test | 715168684fdd3547240db032d8ccc4d9680fff6f | f917ef2722144107cb12435021dd02574d149e39 | refs/heads/master | 2020-03-29T11:49:25.879413 | 2018-09-24T12:29:56 | 2018-09-24T12:29:56 | 149,872,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | cpp | #include "View.h"
#include <iostream>
#include "Console.h"
#include "BehindStartView.h"
using namespace std;
int main()
{
setConsoleSize(80, 40);
View* view = new BehindStartView();
while (view != NULL)
{
View* newView;
view->draw();
newView = view->handle();
if (view != newView)
{
delete view;
view = newView;
}
}
return 0;
} | [
"[email protected]"
] | |
a309945e7db9405e89b27d35dea3c93973d4ac93 | a1886f6a52c8a88043b568c6bb8ddb08bb99c6d2 | /wallet/api_cli.cpp | 21666040daad47787cf8948870248b1d44aa0c31 | [
"Apache-2.0"
] | permissive | DUMIE505/defis | 9a03afb16f51452c522d4a5652f6d5ce2e001721 | 2676311bc0c79b556f29e282ac77b7c4bab47bbc | refs/heads/master | 2022-11-21T12:45:20.657681 | 2020-07-30T05:57:52 | 2020-07-30T05:57:52 | 283,681,973 | 1 | 0 | Apache-2.0 | 2020-07-30T05:52:32 | 2020-07-30T05:52:30 | null | UTF-8 | C++ | false | false | 41,093 | cpp | // Copyright 2018 The Beam Team / Copyright 2019 The Grimm Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#define LOG_VERBOSE_ENABLED 1
#include "utility/logger.h"
#include "api.h"
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <map>
#include "utility/cli/options.h"
#include "utility/helpers.h"
#include "utility/io/timer.h"
#include "utility/io/tcpserver.h"
#include "utility/io/sslserver.h"
#include "utility/io/json_serializer.h"
#include "utility/string_helpers.h"
#include "utility/log_rotation.h"
#include "http/http_connection.h"
#include "http/http_msg_creator.h"
#include "p2p/line_protocol.h"
#include "wallet/wallet_db.h"
#include "wallet/wallet_network.h"
#include "wallet/bitcoin/options.h"
#include "wallet/litecoin/options.h"
#include "nlohmann/json.hpp"
#include "version.h"
using json = nlohmann::json;
static const unsigned LOG_ROTATION_PERIOD = 3 * 60 * 60 * 1000; // 3 hours
static const size_t PACKER_FRAGMENTS_SIZE = 4096;
using namespace grimm;
using namespace grimm::wallet;
namespace
{
const char* MinimumFeeError = "Failed to initiate the send operation. The minimum fee is 100 Centum.";
struct TlsOptions
{
bool use;
std::string certPath;
std::string keyPath;
};
WalletApi::ACL loadACL(const std::string& path)
{
std::ifstream file(path);
std::string line;
WalletApi::ACL::value_type keys;
int curLine = 1;
while (std::getline(file, line))
{
boost::algorithm::trim(line);
auto key = string_helpers::split(line, ':');
bool parsed = false;
static const char* READ_ACCESS = "read";
static const char* WRITE_ACCESS = "write";
if (key.size() == 2)
{
boost::algorithm::trim(key[0]);
boost::algorithm::trim(key[1]);
parsed = !key[0].empty() && (key[1] == READ_ACCESS || key[1] == WRITE_ACCESS);
}
if (!parsed)
{
LOG_ERROR() << "ACL parsing error, line " << curLine;
return boost::none;
}
keys.insert({ key[0], key[1] == WRITE_ACCESS });
curLine++;
}
if (keys.empty())
{
LOG_WARNING() << "ACL file is empty";
}
else
{
LOG_INFO() << "ACL file successfully loaded";
}
return WalletApi::ACL(keys);
}
class IWalletApiServer
{
public:
virtual void closeConnection(uint64_t id) = 0;
};
class WalletApiServer : public IWalletApiServer
{
public:
WalletApiServer(IWalletDB::Ptr walletDB, Wallet& wallet, IWalletMessageEndpoint& wnet, io::Reactor& reactor,
io::Address listenTo, bool useHttp, WalletApi::ACL acl, const TlsOptions& tlsOptions, const std::vector<uint32_t>& whitelist)
: _reactor(reactor)
, _bindAddress(listenTo)
, _useHttp(useHttp)
, _tlsOptions(tlsOptions)
, _walletDB(walletDB)
, _wallet(wallet)
, _wnet(wnet)
, _acl(acl)
, _whitelist(whitelist)
{
start();
}
~WalletApiServer()
{
stop();
}
protected:
void start()
{
LOG_INFO() << "Start server on " << _bindAddress;
try
{
_server = _tlsOptions.use
? io::SslServer::create(_reactor, _bindAddress, BIND_THIS_MEMFN(on_stream_accepted), _tlsOptions.certPath.c_str(), _tlsOptions.keyPath.c_str())
: io::TcpServer::create(_reactor, _bindAddress, BIND_THIS_MEMFN(on_stream_accepted));
}
catch (const std::exception& e)
{
LOG_ERROR() << "cannot start server: " << e.what();
}
}
void stop()
{
}
void closeConnection(uint64_t id) override
{
_pendingToClose.push_back(id);
}
private:
void checkConnections()
{
// clean closed connections
{
for (auto id : _pendingToClose)
{
_connections.erase(id);
}
_pendingToClose.clear();
}
}
class ApiConnection;
template<typename T>
std::shared_ptr<ApiConnection> createConnection(io::TcpStream::Ptr&& newStream)
{
return std::static_pointer_cast<ApiConnection>(std::make_shared<T>(*this, _walletDB, _wallet, _wnet, std::move(newStream), _acl));
}
void on_stream_accepted(io::TcpStream::Ptr&& newStream, io::ErrorCode errorCode)
{
if (errorCode == 0)
{
auto peer = newStream->peer_address();
if (!_whitelist.empty())
{
if (std::find(_whitelist.begin(), _whitelist.end(), peer.ip()) == _whitelist.end())
{
LOG_WARNING() << peer.str() << " not in IP whitelist, closing";
return;
}
}
LOG_DEBUG() << "+peer " << peer;
checkConnections();
_connections[peer.u64()] = _useHttp
? createConnection<HttpApiConnection>(std::move(newStream))
: createConnection<TcpApiConnection>(std::move(newStream));
}
LOG_DEBUG() << "on_stream_accepted";
}
private:
class ApiConnection : IWalletApiHandler, IWalletDbObserver
{
public:
ApiConnection(IWalletDB::Ptr walletDB, Wallet& wallet, IWalletMessageEndpoint& wnet, WalletApi::ACL acl)
: _walletDB(walletDB)
, _wallet(wallet)
, _api(*this, acl)
, _wnet(wnet)
{
_walletDB->subscribe(this);
}
virtual ~ApiConnection()
{
_walletDB->unsubscribe(this);
}
virtual void serializeMsg(const json& msg) = 0;
template<typename T>
void doResponse(int id, const T& response)
{
json msg;
_api.getResponse(id, response, msg);
serializeMsg(msg);
}
void doError(int id, int code, const std::string& info)
{
json msg
{
{"jsonrpc", "2.0"},
{"id", id},
{"error",
{
{"code", code},
{"message", info},
}
}
};
serializeMsg(msg);
}
void onInvalidJsonRpc(const json& msg) override
{
LOG_DEBUG() << "onInvalidJsonRpc: " << msg;
serializeMsg(msg);
}
void FillAddressData(const AddressData& data, WalletAddress& address)
{
if (data.comment)
{
address.setLabel(*data.comment);
}
if (data.expiration)
{
switch (*data.expiration)
{
case EditAddress::OneDay:
address.makeActive(24 * 60 * 60);
break;
case EditAddress::Expired:
address.makeExpired();
break;
case EditAddress::Never:
address.makeEternal();
break;
}
}
}
void onMessage(int id, const CreateAddress& data) override
{
LOG_DEBUG() << "CreateAddress(id = " << id << ")";
WalletAddress address = storage::createAddress(*_walletDB);
FillAddressData(data, address);
_walletDB->saveAddress(address);
doResponse(id, CreateAddress::Response{ address.m_walletID });
}
void onMessage(int id, const DeleteAddress& data) override
{
LOG_DEBUG() << "DeleteAddress(id = " << id << " address = " << std::to_string(data.address) << ")";
auto addr = _walletDB->getAddress(data.address);
if (addr)
{
_walletDB->deleteAddress(data.address);
doResponse(id, DeleteAddress::Response{});
}
else
{
doError(id, INVALID_ADDRESS, "Provided address doesn't exist.");
}
}
void onMessage(int id, const EditAddress& data) override
{
LOG_DEBUG() << "EditAddress(id = " << id << " address = " << std::to_string(data.address) << ")";
auto addr = _walletDB->getAddress(data.address);
if (addr)
{
if (addr->m_OwnID)
{
FillAddressData(data, *addr);
_walletDB->saveAddress(*addr);
doResponse(id, EditAddress::Response{});
}
else
{
doError(id, INVALID_ADDRESS, "You can edit only own address.");
}
}
else
{
doError(id, INVALID_ADDRESS, "Provided address doesn't exist.");
}
}
void onMessage(int id, const AddrList& data) override
{
LOG_DEBUG() << "AddrList(id = " << id << ")";
doResponse(id, AddrList::Response{ _walletDB->getAddresses(data.own) });
}
void onMessage(int id, const ValidateAddress& data) override
{
LOG_DEBUG() << "ValidateAddress( address = " << std::to_string(data.address) << ")";
auto addr = _walletDB->getAddress(data.address);
bool isMine = addr ? addr->m_OwnID != 0 : false;
doResponse(id, ValidateAddress::Response{ data.address.IsValid() && (isMine ? !addr->isExpired() : true), isMine});
}
void onMessage(int id, const Send& data) override
{
LOG_DEBUG() << "Send(id = " << id << " amount = " << data.value << " fee = " << data.fee << " address = " << std::to_string(data.address) << ")";
try
{
WalletID from(Zero);
if(data.from)
{
if(!data.from->IsValid())
{
doError(id, INTERNAL_JSON_RPC_ERROR, "Invalid sender address.");
return;
}
auto addr = _walletDB->getAddress(*data.from);
bool isMine = addr ? addr->m_OwnID != 0 : false;
if(!isMine)
{
doError(id, INTERNAL_JSON_RPC_ERROR, "It's not your own address.");
return;
}
from = *data.from;
}
else
{
WalletAddress senderAddress = storage::createAddress(*_walletDB);
_walletDB->saveAddress(senderAddress);
from = senderAddress.m_walletID;
}
ByteBuffer message(data.comment.begin(), data.comment.end());
CoinIDList coins;
if (data.session)
{
coins = _walletDB->getLocked(*data.session);
if (coins.empty())
{
doError(id, INTERNAL_JSON_RPC_ERROR, "Requested session is empty.");
return;
}
}
else
{
coins = data.coins ? *data.coins : CoinIDList();
}
if (data.fee < MinimumFee)
{
doError(id, INTERNAL_JSON_RPC_ERROR, MinimumFeeError);
return;
}
auto txId = _wallet.transfer_money(from, data.address, data.value, data.fee, coins, true, kDefaultTxLifetime, kDefaultTxResponseTime, std::move(message), true);
doResponse(id, Send::Response{ txId });
}
catch(...)
{
doError(id, INTERNAL_JSON_RPC_ERROR, "Transaction could not be created. Please look at logs.");
}
}
void onMessage(int id, const InitBitcoin& data) override
{
LOG_DEBUG() << "InitBitcoin";
io::Address btcNodeAddr;
if (btcNodeAddr.resolve(data.btcNodeAddr.c_str()))
{
BitcoinOptions options;
options.m_userName = data.btcUserName;
options.m_pass = data.btcPass;
options.m_address = btcNodeAddr;
options.m_feeRate = data.feeRate;
_wallet.initBitcoin(io::Reactor::get_Current(), options);
doResponse(id, EditAddress::Response{});
}
else
{
doError(id, INVALID_ADDRESS, "Bitcoin node address is not resolved.");
}
}
void onMessage(int id, const InitLitecoin& data) override
{
LOG_DEBUG() << "InitLitecoin";
io::Address ltcNodeAddr;
if (ltcNodeAddr.resolve(data.ltcNodeAddr.c_str()))
{
LitecoinOptions options;
options.m_userName = data.ltcUserName;
options.m_pass = data.ltcPass;
options.m_address = ltcNodeAddr;
options.m_feeRate = data.feeRate;
_wallet.initLitecoin(io::Reactor::get_Current(), options);
doResponse(id, EditAddress::Response{});
}
else
{
doError(id, INVALID_ADDRESS, "Bitcoin node address is not resolved.");
}
}
void onMessage(int id, const StartSwap& data) override
{
LOG_DEBUG() << "StartSwap(id = " << id << " amount = " << data.amount << " fee = " << data.fee << " address = " << std::to_string(data.address) << " swap amount = " << data.swapAmount << " isGrimmSide = " << data.grimmSide << ")";
try
{
WalletID from(Zero);
WalletAddress senderAddress = storage::createAddress(*_walletDB);
_walletDB->saveAddress(senderAddress);
from = senderAddress.m_walletID;
auto txId = _wallet.swap_coins(from, data.address, data.amount, data.fee, data.swapCoin, data.swapAmount, data.grimmSide);
doResponse(id, StartSwap::Response{ txId });
}
catch (...)
{
doError(id, INTERNAL_JSON_RPC_ERROR, "Atomic swap transaction could not be created. Please look at logs.");
}
}
void onMessage(int id, const AcceptSwap& data) override
{
LOG_DEBUG() << "AcceptSwap(id = " << id << " amount = " << data.amount << " swap amount = " << data.swapAmount << " isGrimmSide = " << data.grimmSide << ")";
try
{
_wallet.initSwapConditions(data.amount, data.swapAmount, data.swapCoin, data.grimmSide);
doResponse(id, AcceptSwap::Response{});
}
catch (...)
{
doError(id, INTERNAL_JSON_RPC_ERROR, "Atomic swap transaction could not be created. Please look at logs.");
}
}
void onMessage(int id, const Status& data) override
{
LOG_DEBUG() << "Status(txId = " << to_hex(data.txId.data(), data.txId.size()) << ")";
auto tx = _walletDB->getTx(data.txId);
if (tx)
{
Block::SystemState::ID stateID = {};
_walletDB->getSystemStateID(stateID);
Status::Response result;
result.tx = *tx;
result.kernelProofHeight = 0;
result.systemHeight = stateID.m_Height;
result.confirmations = 0;
storage::getTxParameter(*_walletDB, tx->m_txId, TxParameterID::KernelProofHeight, result.kernelProofHeight);
doResponse(id, result);
}
else
{
doError(id, INVALID_PARAMS_JSON_RPC, "Unknown transaction ID.");
}
}
void onMessage(int id, const Split& data) override
{
LOG_DEBUG() << "Split(id = " << id << " coins = [";
for (auto& coin : data.coins) LOG_DEBUG() << coin << ",";
LOG_DEBUG() << "], fee = " << data.fee;
try
{
WalletAddress senderAddress = storage::createAddress(*_walletDB);
_walletDB->saveAddress(senderAddress);
if (data.fee < MinimumFee)
{
doError(id, INTERNAL_JSON_RPC_ERROR, MinimumFeeError);
return;
}
auto txId = _wallet.split_coins(senderAddress.m_walletID, data.coins, data.fee);
doResponse(id, Send::Response{ txId });
}
catch(...)
{
doError(id, INTERNAL_JSON_RPC_ERROR, "Transaction could not be created. Please look at logs.");
}
}
void onMessage(int id, const TxCancel& data) override
{
LOG_DEBUG() << "TxCancel(txId = " << to_hex(data.txId.data(), data.txId.size()) << ")";
auto tx = _walletDB->getTx(data.txId);
if (tx)
{
if (tx->canCancel())
{
_wallet.cancel_tx(tx->m_txId);
TxCancel::Response result{ true };
doResponse(id, result);
}
else
{
doError(id, INVALID_TX_STATUS, "Transaction could not be cancelled. Invalid transaction status.");
}
}
else
{
doError(id, INVALID_PARAMS_JSON_RPC, "Unknown transaction ID.");
}
}
void onMessage(int id, const TxDelete& data) override
{
LOG_DEBUG() << "TxDelete(txId = " << to_hex(data.txId.data(), data.txId.size()) << ")";
auto tx = _walletDB->getTx(data.txId);
if (tx)
{
if (tx->canDelete())
{
_walletDB->deleteTx(data.txId);
if (_walletDB->getTx(data.txId))
{
doError(id, INTERNAL_JSON_RPC_ERROR, "Transaction not deleted.");
}
else
{
doResponse(id, TxDelete::Response{true});
}
}
else
{
doError(id, INTERNAL_JSON_RPC_ERROR, "Transaction can't be deleted.");
}
}
else
{
doError(id, INVALID_PARAMS_JSON_RPC, "Unknown transaction ID.");
}
}
template<typename T>
static void doPagination(size_t skip, size_t count, std::vector<T>& res)
{
if (count > 0)
{
size_t start = skip;
size_t end = start + count;
size_t size = res.size();
if (start < size)
{
if (end > size) end = size;
res = std::vector<T>(res.begin() + start, res.begin() + end);
}
else res = {};
}
}
void onMessage(int id, const GetUtxo& data) override
{
LOG_DEBUG() << "GetUtxo(id = " << id << ")";
GetUtxo::Response response;
_walletDB->visit([&response](const Coin& c)->bool
{
response.utxos.push_back(c);
return true;
});
doPagination(data.skip, data.count, response.utxos);
doResponse(id, response);
}
void onMessage(int id, const WalletStatus& data) override
{
LOG_DEBUG() << "WalletStatus(id = " << id << ")";
WalletStatus::Response response;
{
Block::SystemState::ID stateID = {};
_walletDB->getSystemStateID(stateID);
response.currentHeight = stateID.m_Height;
response.currentStateHash = stateID.m_Hash;
}
{
Block::SystemState::Full state;
_walletDB->get_History().get_Tip(state);
response.prevStateHash = state.m_Prev;
response.difficulty = state.m_PoW.m_Difficulty.ToFloat();
}
storage::Totals totals(*_walletDB);
response.available = totals.Avail;
response.receiving = totals.Incoming;
response.sending = totals.Outgoing;
response.maturing = totals.Maturing;
doResponse(id, response);
}
void onMessage(int id, const Lock& data) override
{
LOG_DEBUG() << "Lock(id = " << id << ")";
Lock::Response response;
response.result = _walletDB->lock(data.coins, data.session);
doResponse(id, response);
}
void onMessage(int id, const Unlock& data) override
{
LOG_DEBUG() << "Unlock(id = " << id << " session = " << data.session << ")";
Unlock::Response response;
response.result = _walletDB->unlock(data.session);
doResponse(id, response);
}
void onMessage(int id, const TxList& data) override
{
LOG_DEBUG() << "List(filter.status = " << (data.filter.status ? std::to_string((uint32_t)*data.filter.status) : "nul") << ")";
TxList::Response res;
{
auto txList = _walletDB->getTxHistory();
Block::SystemState::ID stateID = {};
_walletDB->getSystemStateID(stateID);
for (const auto& tx : txList)
{
Status::Response item;
item.tx = tx;
item.kernelProofHeight = 0;
item.systemHeight = stateID.m_Height;
item.confirmations = 0;
storage::getTxParameter(*_walletDB, tx.m_txId, TxParameterID::KernelProofHeight, item.kernelProofHeight);
res.resultList.push_back(item);
}
}
using Result = decltype(res.resultList);
// filter transactions by status if provided
if (data.filter.status)
{
Result filteredList;
for (const auto& it : res.resultList)
if (it.tx.m_status == *data.filter.status)
filteredList.push_back(it);
res.resultList = filteredList;
}
// filter transactions by height if provided
if (data.filter.height)
{
Result filteredList;
for (const auto& it : res.resultList)
if (it.kernelProofHeight == *data.filter.height)
filteredList.push_back(it);
res.resultList = filteredList;
}
doPagination(data.skip, data.count, res.resultList);
doResponse(id, res);
}
private:
void methodNotImplementedYet(int id)
{
doError(id, NOTFOUND_JSON_RPC, "Method not implemented yet.");
}
protected:
IWalletDB::Ptr _walletDB;
Wallet& _wallet;
WalletApi _api;
IWalletMessageEndpoint& _wnet;
};
class TcpApiConnection : public ApiConnection
{
public:
TcpApiConnection(IWalletApiServer& server, IWalletDB::Ptr walletDB, Wallet& wallet, IWalletMessageEndpoint& wnet, io::TcpStream::Ptr&& newStream, WalletApi::ACL acl)
: ApiConnection(walletDB, wallet, wnet, acl)
, _stream(std::move(newStream))
, _lineProtocol(BIND_THIS_MEMFN(on_raw_message), BIND_THIS_MEMFN(on_write))
, _server(server)
{
_stream->enable_keepalive(2);
_stream->enable_read(BIND_THIS_MEMFN(on_stream_data));
}
virtual ~TcpApiConnection()
{
}
void serializeMsg(const json& msg) override
{
serialize_json_msg(_lineProtocol, msg);
}
void on_write(io::SharedBuffer&& msg)
{
_stream->write(msg);
}
bool on_raw_message(void* data, size_t size)
{
LOG_INFO() << "got " << std::string((char*)data, size);
return _api.parse(static_cast<const char*>(data), size);
}
bool on_stream_data(io::ErrorCode errorCode, void* data, size_t size)
{
if (errorCode != 0)
{
LOG_INFO() << "peer disconnected, code=" << io::error_str(errorCode);
_server.closeConnection(_stream->peer_address().u64());
return false;
}
if (!_lineProtocol.new_data_from_stream(data, size))
{
LOG_INFO() << "stream corrupted";
_server.closeConnection(_stream->peer_address().u64());
return false;
}
return true;
}
private:
io::TcpStream::Ptr _stream;
LineProtocol _lineProtocol;
IWalletApiServer& _server;
};
class HttpApiConnection : public ApiConnection
{
public:
HttpApiConnection(IWalletApiServer& server, IWalletDB::Ptr walletDB, Wallet& wallet, IWalletMessageEndpoint& wnet, io::TcpStream::Ptr&& newStream, WalletApi::ACL acl)
: ApiConnection(walletDB, wallet, wnet, acl)
, _keepalive(false)
, _msgCreator(2000)
, _packer(PACKER_FRAGMENTS_SIZE)
, _server(server)
{
newStream->enable_keepalive(1);
auto peer = newStream->peer_address();
_connection = std::make_unique<HttpConnection>(
peer.u64(),
BaseConnection::inbound,
BIND_THIS_MEMFN(on_request),
10000,
1024,
std::move(newStream)
);
}
virtual ~HttpApiConnection() {}
void serializeMsg(const json& msg) override
{
serialize_json_msg(_body, _packer, msg);
_keepalive = send(_connection, 200, "OK");
}
private:
bool on_request(uint64_t id, const HttpMsgReader::Message& msg)
{
if (msg.what != HttpMsgReader::http_message || !msg.msg)
{
LOG_DEBUG() << "-peer " << io::Address::from_u64(id) << " : " << msg.error_str();
_connection->shutdown();
_server.closeConnection(id);
return false;
}
if (msg.msg->get_path() != "/api/wallet")
{
_keepalive = send(_connection, 404, "Not Found");
}
else
{
_body.clear();
size_t size = 0;
auto data = msg.msg->get_body(size);
LOG_INFO() << "got " << std::string((char*)data, size);
_api.parse((char*)data, size);
}
if (!_keepalive)
{
_connection->shutdown();
_server.closeConnection(id);
}
return _keepalive;
}
bool send(const HttpConnection::Ptr& conn, int code, const char* message)
{
assert(conn);
size_t bodySize = 0;
for (const auto& f : _body) { bodySize += f.size; }
bool ok = _msgCreator.create_response(
_headers,
code,
message,
0,
0,
1,
"application/json",
bodySize
);
if (ok) {
auto result = conn->write_msg(_headers);
if (result && bodySize > 0) {
result = conn->write_msg(_body);
}
if (!result) ok = false;
}
else {
LOG_ERROR() << "cannot create response";
}
_headers.clear();
_body.clear();
return (ok && code == 200);
}
HttpConnection::Ptr _connection;
bool _keepalive;
HttpMsgCreator _msgCreator;
HttpMsgCreator _packer;
io::SerializedMsg _headers;
io::SerializedMsg _body;
IWalletApiServer& _server;
};
io::Reactor& _reactor;
io::TcpServer::Ptr _server;
io::Address _bindAddress;
bool _useHttp;
TlsOptions _tlsOptions;
std::map<uint64_t, std::shared_ptr<ApiConnection>> _connections;
IWalletDB::Ptr _walletDB;
Wallet& _wallet;
IWalletMessageEndpoint& _wnet;
std::vector<uint64_t> _pendingToClose;
WalletApi::ACL _acl;
std::vector<uint32_t> _whitelist;
};
}
int main(int argc, char* argv[])
{
using namespace grimm;
namespace po = boost::program_options;
const auto path = boost::filesystem::system_complete("./logs");
auto logger = grimm::Logger::create(LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, "api_", path.string());
try
{
struct
{
uint16_t port;
std::string walletPath;
std::string nodeURI;
bool useHttp;
Nonnegative<uint32_t> pollPeriod_ms;
bool useAcl;
std::string aclPath;
std::string whitelist;
uint32_t logCleanupPeriod;
} options;
TlsOptions tlsOptions;
io::Address node_addr;
IWalletDB::Ptr walletDB;
io::Reactor::Ptr reactor = io::Reactor::create();
WalletApi::ACL acl;
std::vector<uint32_t> whitelist;
{
po::options_description desc("Wallet API general options");
desc.add_options()
(cli::HELP_FULL, "list of all options")
(cli::PORT_FULL, po::value(&options.port)->default_value(10000), "port to start server on")
(cli::NODE_ADDR_FULL, po::value<std::string>(&options.nodeURI), "address of node")
(cli::WALLET_STORAGE, po::value<std::string>(&options.walletPath)->default_value("wallet.db"), "path to wallet file")
(cli::PASS, po::value<std::string>(), "password for the wallet")
(cli::API_USE_HTTP, po::value<bool>(&options.useHttp)->default_value(false), "use JSON RPC over HTTP")
(cli::IP_WHITELIST, po::value<std::string>(&options.whitelist)->default_value(""), "IP whitelist")
(cli::LOG_CLEANUP_DAYS, po::value<uint32_t>(&options.logCleanupPeriod)->default_value(5), "old logfiles cleanup period(days)")
(cli::NODE_POLL_PERIOD, po::value<Nonnegative<uint32_t>>(&options.pollPeriod_ms)->default_value(Nonnegative<uint32_t>(0)), "Node poll period in milliseconds. Set to 0 to keep connection. Anyway poll period would be no less than the expected rate of blocks if it is less then it will be rounded up to block rate value.")
;
po::options_description authDesc("User authorization options");
authDesc.add_options()
(cli::API_USE_ACL, po::value<bool>(&options.useAcl)->default_value(false), "use Access Control List (ACL)")
(cli::API_ACL_PATH, po::value<std::string>(&options.aclPath)->default_value("wallet_api.acl"), "path to ACL file")
;
po::options_description tlsDesc("TLS protocol options");
tlsDesc.add_options()
(cli::API_USE_TLS, po::value<bool>(&tlsOptions.use)->default_value(false), "use TLS protocol")
(cli::API_TLS_CERT, po::value<std::string>(&tlsOptions.certPath)->default_value("wallet_api.crt"), "path to TLS certificate")
(cli::API_TLS_KEY, po::value<std::string>(&tlsOptions.keyPath)->default_value("wallet_api.key"), "path to TLS private key")
;
desc.add(authDesc);
desc.add(tlsDesc);
desc.add(createRulesOptionsDescription());
po::variables_map vm;
po::store(po::command_line_parser(argc, argv)
.options(desc)
.style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing)
.run(), vm);
if (vm.count(cli::HELP))
{
std::cout << desc << std::endl;
return 0;
}
{
std::ifstream cfg("wallet-api.cfg");
if (cfg)
{
po::store(po::parse_config_file(cfg, desc), vm);
}
}
vm.notify();
getRulesOptions(vm); //todo for assetchain
Rules::get().UpdateChecksum();
LOG_INFO() << "Grimm Wallet API " << PROJECT_VERSION << " (" << BRANCH_NAME << ")";
LOG_INFO() << "Rules signature: " << Rules::get().get_SignatureStr();
if (options.useAcl)
{
if (!(boost::filesystem::exists(options.aclPath) && (acl = loadACL(options.aclPath))))
{
LOG_ERROR() << "ACL file not loaded, path is: " << options.aclPath;
return -1;
}
}
if (tlsOptions.use)
{
if (tlsOptions.certPath.empty() || !boost::filesystem::exists(tlsOptions.certPath))
{
LOG_ERROR() << "TLS certificate not found, path is: " << tlsOptions.certPath;
return -1;
}
if (tlsOptions.keyPath.empty() || !boost::filesystem::exists(tlsOptions.keyPath))
{
LOG_ERROR() << "TLS private key not found, path is: " << tlsOptions.keyPath;
return -1;
}
}
if (!options.whitelist.empty())
{
const auto& items = string_helpers::split(options.whitelist, ',');
for (const auto& item : items)
{
io::Address addr;
if (addr.resolve(item.c_str()))
{
whitelist.push_back(addr.ip());
}
else
{
LOG_ERROR() << "IP address not added to whitelist: " << item;
return -1;
}
}
}
if (vm.count(cli::NODE_ADDR) == 0)
{
LOG_ERROR() << "node address should be specified";
return -1;
}
if (!node_addr.resolve(options.nodeURI.c_str()))
{
LOG_ERROR() << "unable to resolve node address: " << options.nodeURI;
return -1;
}
if (!WalletDB::isInitialized(options.walletPath))
{
LOG_ERROR() << "Wallet not found, path is: " << options.walletPath;
return -1;
}
SecString pass;
if (!grimm::read_wallet_pass(pass, vm))
{
LOG_ERROR() << "Please, provide password for the wallet.";
return -1;
}
walletDB = WalletDB::open(options.walletPath, pass, reactor);
if (!walletDB)
{
LOG_ERROR() << "Wallet not opened.";
return -1;
}
LOG_INFO() << "wallet sucessfully opened...";
}
io::Address listenTo = io::Address().port(options.port);
io::Reactor::Scope scope(*reactor);
io::Reactor::GracefulIntHandler gih(*reactor);
LogRotation logRotation(*reactor, LOG_ROTATION_PERIOD, options.logCleanupPeriod);
Wallet wallet{ walletDB };
auto nnet = std::make_shared<proto::FlyClient::NetworkStd>(wallet);
nnet->m_Cfg.m_PollPeriod_ms = options.pollPeriod_ms.value;
if (nnet->m_Cfg.m_PollPeriod_ms)
{
LOG_INFO() << "Node poll period = " << nnet->m_Cfg.m_PollPeriod_ms << " ms";
uint32_t timeout_ms = std::max(Rules::get().DA.DTarget_s * 1000, nnet->m_Cfg.m_PollPeriod_ms);
if (timeout_ms != nnet->m_Cfg.m_PollPeriod_ms)
{
LOG_INFO() << "Node poll period has been automatically rounded up to block rate: " << timeout_ms << " ms";
}
}
uint32_t responceTime_s = Rules::get().DA.DTarget_s * wallet::kDefaultTxResponseTime;
if (nnet->m_Cfg.m_PollPeriod_ms >= responceTime_s * 1000)
{
LOG_WARNING() << "The \"--node_poll_period\" parameter set to more than " << uint32_t(responceTime_s / 3600) << " hours may cause transaction problems.";
}
nnet->m_Cfg.m_vNodes.push_back(node_addr);
nnet->Connect();
auto wnet = std::make_shared<WalletNetworkViaBbs>(wallet, nnet, walletDB);
wallet.AddMessageEndpoint(wnet);
wallet.SetNodeEndpoint(nnet);
WalletApiServer server(walletDB, wallet, *wnet, *reactor,
listenTo, options.useHttp, acl, tlsOptions, whitelist);
io::Reactor::get_Current().run();
LOG_INFO() << "Done";
}
catch (const std::exception& e)
{
LOG_ERROR() << "EXCEPTION: " << e.what();
}
catch (...)
{
LOG_ERROR() << "NON_STD EXCEPTION";
}
return 0;
}
| [
"[email protected]"
] | |
76898d7a8e60d3a037d48663655b96bd657ee288 | 2fd568388da92949549bc55daf11faf55a5b8bd4 | /PostfixTreeBuilder.cpp | 9c7c91186ec9590b3e5aaf5002ac789ec6eb5d77 | [] | no_license | trujamal/Project6_1 | dddcf9f4cfc200ef3670e8a821202856b7b11b11 | 5f080fc03ee53e309e0250ba8ccc0e36ccab5adf | refs/heads/master | 2020-03-06T21:47:22.974155 | 2018-03-28T05:09:31 | 2018-03-28T05:09:31 | 127,086,590 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,390 | cpp | /**
* @author Jamal Rasool
* @version 1.0
* @date 3/27/18
* @details The driver functions for the logic within the code
*/
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <stack>
#include <exception>
#include "PostfixTreeBuilder.h"
using std::cout;
using std::endl;
/**
* overall algorithim to follow for the code
* postorder(node)
if (node = null)
return
postorder(node.left)
postorder(node.right)
visit(node)
*/
/**
iterativePostorder(node)
s ← empty stack
lastNodeVisited ← null
while (not s.isEmpty() or node ≠ null)
if (node ≠ null)
s.push(node)
node ← node.left
else
peekNode ← s.peek()
// if right child exists and traversing node
// from left child, then move right
if (peekNode.right ≠ null and lastNodeVisited ≠ peekNode.right)
node ← peekNode.right
else
visit(peekNode)
lastNodeVisited ← s.pop()
*/
/**
* Constructor
*/
PostffixTreeNode::PostffixTreeNode() {
}
Number_element_nodes::Number_element_nodes(double number) : number(number) {
}
/**
* Deconstructors
*/
PostffixTreeNode::~PostffixTreeNode() {
}
Number_element_nodes::~Number_element_nodes() {
}
/**
* Processing Commands
*/
void Postfix_builder::processRightParenthesis() {
}
void Postfix_builder::processOperator(char op) {
}
| [
"[email protected]"
] | |
7c3a72aeb4166bbb61fe053321daae8c164aef6e | 154dfd2a2130a3a7731a9a9b431e8295fbf82cd2 | /BZOJ/BZOJ3289.cpp | 6e8f83735815b603ba5e97066b6140cffad2b01d | [] | no_license | ltf0501/Competitive-Programming | 1f898318eaecae14b6e040ffc7e36a9497ee288c | 9660b28d979721f2befcb590182975f10c9b6ac8 | refs/heads/master | 2022-11-20T21:08:45.651706 | 2020-07-23T11:55:05 | 2020-07-23T11:55:05 | 245,600,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,446 | cpp | #include<bits/stdc++.h>
using namespace std;
#define maxn 50010
#define SZ 225
struct P
{
int l,r,block,id;
bool operator < (const P& b)const
{
if(block!=b.block)return block<b.block;
return r<b.r;
}
}q[maxn];
vector<int> v;
int a[maxn],ans[maxn];
int cur_ans=0,n,m;
int bit[maxn];
void update(int x,int d)
{
for(int i=x;i<=n;i+=i&-i)bit[i]+=d;
}
int query(int x)
{
int ret=0;
for(int i=x;i;i-=i&-i)ret+=bit[i];
return ret;
}
void add(int x,bool c)
{
if(c)cur_ans+=query(n)-query(x);
else cur_ans+=query(x-1);
update(x,1);
}
void sub(int x,bool c)
{
if(c)cur_ans-=query(n)-query(x);
else cur_ans-=query(x-1);
update(x,-1);
}
main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&a[i]),v.push_back(a[i]);
sort(v.begin(),v.end());
v.resize(unique(v.begin(),v.end())-v.begin());
for(int i=1;i<=n;i++)a[i]=lower_bound(v.begin(),v.end(),a[i])-v.begin()+1;
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
int l,r;scanf("%d%d",&l,&r);
q[i]={l,r,l/SZ,i};
}
sort(q+1,q+m+1);
for(int i=1,L=1,R=0;i<=m;i++)
{
while(R<q[i].r)add(a[++R],1);
while(L>q[i].l)add(a[--L],0);
while(R>q[i].r)sub(a[R--],1);
while(L<q[i].l)sub(a[L++],0);
ans[q[i].id]=cur_ans;
}
for(int i=1;i<=m;i++)printf("%d\n",ans[i]);
return 0;
}
| [
"[email protected]"
] | |
4bfe1a5c9723a3e82c73b655b3a8ade844be1386 | e5ff6ecfad7e9e79498a3654a73048ebd92e1032 | /ClientTCPIP.hpp | 6f1e306132d9f2793638b9eb3cf6380e0cc49fc8 | [] | no_license | Youw/Berkeley_sockets | 25b29c5da0131fd42f681e94afc9ae31e0604d1c | e560d6be6ae34c65a997274da0d2c1a9c3283391 | refs/heads/master | 2016-08-07T19:40:56.517009 | 2014-03-02T04:57:12 | 2014-03-02T04:57:12 | 17,156,688 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,252 | hpp | /**
* Created 25.02.2014 by Ihor Dutchak (Youw)
* simple TCP IPv4 server (listening) socket for windows, linux and OS X
* You need c++11 compiler or greater to use this source
*/
#ifndef CLIENT_TCP_IP_V4_HPP
#define CLIENT_TCP_IP_V4_HPP
#include <Socket/Socket.hpp>
#include <vector>
#include <string>
#include <utility>
namespace sockets {
using std::string;
using std::vector;
using std::move;
class ClientTCPIP final: public Socket {
//hidden due to logic compatibility
int listen(int backlog) { return 0; }
//hidden due to logic compatibility
Socket accept(sockaddr *addr, socklen_t *addr_len) { return 0; }
public:
ClientTCPIP() {}
ClientTCPIP(const string name, unsigned short port, SockType conn_type = SockType::TCPIPv4v6, unsigned short bind_port = 0) {
connect(name, port, conn_type, bind_port);
}
bool connect(const string name, unsigned short port, SockType conn_type = SockType::TCPIPv4v6, unsigned short bind_port = 0) {
if (0!=Socket::peerPort()) return false;
if (!isInvalid()) closesocket();
addrinfo *result = NULL;
addrinfo hints{ bind_port?AI_PASSIVE:0, int(conn_type), SOCK_STREAM, IPPROTO_TCP };
int iResult = getaddrinfo(name.c_str(), std::to_string(port).c_str(), &hints, &result);
if (iResult != 0) {
return 0;
}
for (auto ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a SOCKET for connecting to server
Socket::socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (isInvalid()) {
continue;
}
if (bind_port) {
sockaddr_in bind_addr{};
bind_addr.sin_family = decltype(bind_addr.sin_family)(ptr->ai_family);
bind_addr.sin_port = htons(bind_port);
int iSetOption = 1;
// if (0 != setsockopt( SOL_SOCKET, SO_REUSEADDR, (char*)&iSetOption, sizeof(iSetOption))) {
// closesocket();
// continue;
// }
if (0 != bind((sockaddr*)&bind_addr, sizeof(bind_addr))) {
closesocket();
continue;
}
}
// Connect to server.
if (!Socket::connect(ptr->ai_addr, (int)ptr->ai_addrlen)) {
closesocket();
continue;
}
break;
}
if (Socket::isInvalid()) {
return false;
}
return true;
}
};
};
#endif //CLIENT_TCP_IP_V4_HPP
| [
"[email protected]"
] | |
f5efba66ec2bc04869b4a26b36597d92d80a36a9 | 66633bc1ad3710654856adbd8f35bc38dc8054a7 | /src/energy/camshift_data.h | a2c9de1f24d6a038a49a05fe2667d0ba7bc1bd7f | [] | no_license | jensengroup/camshift-phaistos | d8d9bd9d000f33ace8203e3109e21f1b6e29089b | 5244b8ac3fae2ab5d1646590bb84fc2925d5ab74 | refs/heads/master | 2016-09-05T16:47:52.226076 | 2013-05-09T09:31:07 | 2013-05-09T09:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 64,082 | h | // camshift_data.h -- Parameters for the camshift energy term.
// This is the parameters from the Camshift 1.35 program,
// which differ from the ones in the actual paper.
//
// Copyright (C) 2011 by Anders Steen Christensen, Wouter Boomsma
//
// This file is part of Phaistos
//
// Phaistos is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Phaistos is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Phaistos. If not, see <http://www.gnu.org/licenses/>.
#ifndef CAMSHIFT_DATA
#define CAMSHIFT_DATA
#include "energy/energy_term.h"
#include <boost/type_traits/is_base_of.hpp>
#include <boost/assign/list_of.hpp>
#include <iostream>
#include <vector>
#include <math.h>
#include <cmath>
#include <string.h>
#include "protein/chain_fb.h"
#include "protein/definitions.h"
#include "energy/energy.h"
#include "energy/camshift.h"
using namespace phaistos;
using namespace definitions;
namespace camshift_constants {
const std::vector<AtomEnum> regular_donor_atom_types = vector_utils::make_vector(H, H1, H2, H3);
const std::vector<AtomEnum> regular_donor_connected_atoms = vector_utils::make_vector(N, N, N, N);
const std::vector<AtomEnum> regular_acceptor_atom_types = vector_utils::make_vector(O, N, OXT);
const std::vector<AtomEnum> regular_acceptor_connected_atoms = vector_utils::make_vector(C, C, C);
const std::vector<ResidueEnum> sc_donor_residues = vector_utils::make_vector(SER, THR, TYR, ASN, ASN, GLN, GLN, HIS, HIS, LYS, LYS, LYS, ARG, ARG, ARG, ARG);
const std::vector<AtomEnum> sc_donor_atoms_types = vector_utils::make_vector(HG, HG1, HH, HD21, HD22, HE21, HE22, HD1, HE2, HZ1, HZ2, HZ3, HH11, HH21, HH12, HH22);
const std::vector<AtomEnum> sc_donor_connected_atoms = vector_utils::make_vector(OG, OG1, OH, ND2, ND2, NE2, NE2, ND1, NE2, NZ, NZ, NZ, NH1, NH1, NH2, NH2);
const std::vector<ResidueEnum> sc_acceptor_residues = vector_utils::make_vector(SER, THR, TYR, ASN, GLN, ASP, ASP, GLU, GLU);
const std::vector<AtomEnum> sc_acceptor_atoms_types = vector_utils::make_vector(OG, OG1, OH, OD1, OE1, OD1, OD2, OE1, OE2);
const std::vector<AtomEnum> sc_acceptor_connected_atoms = vector_utils::make_vector(CB, CB, CZ, CG, CD, CG, CG, CD, CD );
std::vector<double> ss_bond_coefficients = vector_utils::make_vector( 0.011555153204883891 , -2.851700383944911 , -0.10605544569039109 , -1.4131441517517331 , -0.37088135408255857 , 11.361637372067898 );
const std::vector< std::vector<double> > power_minus_3_sp3_coefficients_STD = vector_utils::make_vector(
vector_utils::make_vector( -2.9677854218318016, -10.347270858368276 ,-5.381324807117669 , -70.57316993796852 , 2.7653856090154982 , -14.772311956621978 ),
vector_utils::make_vector( 0.671565238061677, 3.450707081013336 ,1.4552245137358921 , 34.69758894788705 , 1.232025943700639 , 4.8997052958852105 ),
vector_utils::make_vector( -1.6214566324137984, -12.5982466223797 , 2.505391454472044 , -88.71419716149445 , 31.32384112711744 , -14.86605302072972 ),
vector_utils::make_vector( 0.13517999663882513, -3.5664649776195554 , 3.3033813020525264 , 15.271538038229991 , 31.172000909193187 , -4.189887175682491 ),
vector_utils::make_vector( 6.275799974169214, -101.81223165473585 , -0.8774167747629915 , 89.18257287053987 , 0.46315015978232393 , 25.290699879146132 ));
const std::vector< std::vector<double> > power_minus_3_sp2_coefficients_STD = vector_utils::make_vector(
vector_utils::make_vector( -0.20351043093982915, -9.754432952768152 , -14.432589744681705 , -43.34560180380588 , -27.917719815521252 , -1.6619941862134497 ),
vector_utils::make_vector( 1.2355083351941172, -9.628534199158775 , 17.498842030092842 , 78.05125884403317 , 40.25708258918623 , 0.7461717480347501 ),
vector_utils::make_vector( 8.182942738787164, -8.649509334546984 , 9.140798607308529 , 53.27459290093175 , 24.047756828193904 , -9.21507952586192 ));
const std::vector< std::vector<double> > power_minus_3_sp3_coefficients_GLY = vector_utils::make_vector(
vector_utils::make_vector( -3.0168132206326201 , -8.5977612315663663 , -5.8425337663422932 , -71.5911952645416392 , 2.8434093325683931 , 0.0000000000000000 ),
vector_utils::make_vector( 0.6934660792315268 , 3.4918232206732189 , 1.4585048429702292 , 34.9500047871303181 , 1.1159713726365932 , 0.0000000000000000 ),
vector_utils::make_vector( -1.5118058348354597 , -11.6825206167860607 , 1.0705716803535279 , -84.7947603494997537 , 31.2080907624559600 , 0.0000000000000000 ),
vector_utils::make_vector( -0.0116202683261451 , -2.7975315048098603 , 2.9867520336872828 , 15.4156559704698228 , 33.0734988620999530 , 0.0000000000000000 ),
vector_utils::make_vector( 6.0126234618484533 , -90.0455354082495347 , -0.9345985095512087 , 92.2168676719532101 , 2.2352785344174739 , 0.0000000000000000 ));
const std::vector< std::vector<double> > power_minus_3_sp2_coefficients_GLY = vector_utils::make_vector(
vector_utils::make_vector( 0.0261762523847436 , -4.6399330961379093 , -12.2287228009680558 , -35.7631624888671809 , -23.2998679033744480 , 0.0000000000000000 ),
vector_utils::make_vector( 1.7596831881781203 , -24.1547967042352134 , 17.0967107013221487 , 93.8333369962513899 , 45.9211174848769161 , 0.0000000000000000 ),
vector_utils::make_vector( 7.5153250055664857 , -8.1137498172680758 , 8.5922144532888520 , 52.8186525570455032 , 24.2391177129099766 , 0.0000000000000000 ));
const std::vector< std::vector<double> > power_minus_3_sp3_coefficients_PRO = vector_utils::make_vector(
vector_utils::make_vector( -2.8890317947476105 , -11.5701183504619376 , 0.0000000000000000 , 0.0000000000000000 , 0.7454208604152885 , -15.4339191816303973 ),
vector_utils::make_vector( 0.6781449975559071 , 3.8625409177420713 , 0.0000000000000000 , 0.0000000000000000 , 1.5414621184550050 , 4.9592400981560170 ),
vector_utils::make_vector( -1.6775878941427678 , -14.3054724355278484 , 0.0000000000000000 , 0.0000000000000000 , 30.4421396285314216 , -13.2850125698609531 ),
vector_utils::make_vector( 0.1396715168585968 , -3.2341673003651050 , 0.0000000000000000 , 0.0000000000000000 , 31.0048115162175151 , -3.7517901842673012 ),
vector_utils::make_vector( 6.1752519285985095 , -97.7775559481696064 , 0.0000000000000000 , 0.0000000000000000 , -0.1268802813206794 , 23.3408457747261977 ));
const std::vector< std::vector<double> > power_minus_3_sp2_coefficients_PRO = vector_utils::make_vector(
vector_utils::make_vector( -0.0160993947579784 , -10.4773986216893746 , 0.0000000000000000 , 0.0000000000000000 , -29.3726275624834905 , -1.8753940901269193 ),
vector_utils::make_vector( 1.0437019234227876 , -5.6041119442661893 , 0.0000000000000000 , 0.0000000000000000 , 29.9173363348794972 , -4.3841389425860244 ),
vector_utils::make_vector( 8.0417551403179921 , -8.5759150368419235 , 0.0000000000000000 , 0.0000000000000000 , 24.7418252027886290 , -8.6329324566801020 ));
const std::vector< std::vector<double> > power_1_sp3_coefficients_STD = vector_utils::make_vector(
vector_utils::make_vector( 0.0026980777380174 , 0.0340218076597632 , -0.0069550340003526 , -0.0305132227816947 , -0.0149591395830326 , 0.0439204571490100 ),
vector_utils::make_vector( -0.0035562744365679 , -0.0049690317072318 , 0.0116062321032106 , -0.1324913929510944 , -0.0314517184116281 , -0.0111143480007445 ),
vector_utils::make_vector( 0.0093801308883551 , 0.0474206178407343 , -0.0631762765360979 , 0.3450077717420807 , -0.0069306876125918 , 0.0437226469304904 ),
vector_utils::make_vector( 0.0013891776050714 , 0.0041548721344522 , 0.0012358379582019 , 0.0854749530005921 , -0.0624505405391126 , -0.0125878186407877 ),
vector_utils::make_vector( -0.0326841604227400 , 0.3592450001842794 , 0.0129472028747584 , -0.3312136022598206 , -0.0197605274467603 , -0.0793473334154241 ));
const std::vector< std::vector<double> > power_1_sp2_coefficients_STD = vector_utils::make_vector(
vector_utils::make_vector( -0.0060841412003716 , 0.0254618129385003 , 0.0352599885419553 , 0.0402185164270435 , 0.0658225687924841 , 0.0122429462108456 ),
vector_utils::make_vector( -0.0204518866709478 , 0.0257896928598489 , -0.0491207594609957 , -0.2553769514425676 , -0.0809802787963923 , -0.0353701055172424 ),
vector_utils::make_vector( -0.0380542632940253 , 0.0448192447937817 , -0.0283907349785015 , -0.1847889936482979 , -0.1061224078965686 , 0.0309462023985530 ));
const std::vector< std::vector<double> > power_1_sp3_coefficients_GLY = vector_utils::make_vector(
vector_utils::make_vector( 0.0019264717822498 , 0.0309128772661786 , -0.0054203863271885 , -0.0207984006090474 , -0.0151925114594120 , 0.0000000000000000 ),
vector_utils::make_vector( -0.0031883766817039 , -0.0067515429379451 , 0.0121695556187617 , -0.1312017526068961 , -0.0307875129628472 , 0.0000000000000000 ),
vector_utils::make_vector( 0.0084884818340617 , 0.0471440723212129 , -0.0599493431735166 , 0.3297394961000978 , -0.0085599343545507 , 0.0000000000000000 ),
vector_utils::make_vector( 0.0018811759493966 , -0.0014212249014815 , 0.0013844651725935 , 0.0865618582684383 , -0.0690416452389158 , 0.0000000000000000 ),
vector_utils::make_vector( -0.0323830071515205 , 0.3254298524169774 , 0.0090493985377423 , -0.3311425776430222 , -0.0239321306378119 , 0.0000000000000000 ));
const std::vector< std::vector<double> > power_1_sp2_coefficients_GLY = vector_utils::make_vector(
vector_utils::make_vector( -0.0072227598409180 , 0.0120399256858485 , 0.0281910910647572 , 0.0224531804134379 , 0.0527579647292673 , 0.0000000000000000 ),
vector_utils::make_vector( -0.0251184784903051 , 0.0727874760361857 , -0.0591580757827286 , -0.3550118766610906 , -0.0906942068848875 , 0.0000000000000000 ),
vector_utils::make_vector( -0.0346208537782999 , 0.0412070552988399 , -0.0269135224034520 , -0.1633651635005118 , -0.1020419281899392 , 0.0000000000000000 ));
const std::vector< std::vector<double> > power_1_sp3_coefficients_PRO = vector_utils::make_vector(
vector_utils::make_vector( 0.0023438824044885 , 0.0353138525705945 , 0.0000000000000000 , 0.0000000000000000 , -0.0095636282181957 , 0.0451318684682797 ),
vector_utils::make_vector( -0.0037569403178147 , -0.0063922592966343 , 0.0000000000000000 , 0.0000000000000000 , -0.0329767653695871 , -0.0118420722727012 ),
vector_utils::make_vector( 0.0097002786444334 , 0.0538909578174844 , 0.0000000000000000 , 0.0000000000000000 , -0.0036915462015988 , 0.0376911005968920 ),
vector_utils::make_vector( 0.0009191341020309 , 0.0031996855595238 , 0.0000000000000000 , 0.0000000000000000 , -0.0619811254617135 , -0.0114162034368302 ),
vector_utils::make_vector( -0.0327975121680781 , 0.3482810222512587 , 0.0000000000000000 , 0.0000000000000000 , -0.0211073880998749 , -0.0723428687287950 ));
const std::vector< std::vector<double> > power_1_sp2_coefficients_PRO = vector_utils::make_vector(
vector_utils::make_vector( -0.0070155824454568 , 0.0257927879915568 , 0.0000000000000000 , 0.0000000000000000 , 0.0698801251001801 , 0.0110031858176522 ),
vector_utils::make_vector( -0.0190642956009872 , 0.0141752603136959 , 0.0000000000000000 , 0.0000000000000000 , -0.0497685703831869 , -0.0161534287595733 ),
vector_utils::make_vector( -0.0374516166245494 , 0.0469155415729522 , 0.0000000000000000 , 0.0000000000000000 , -0.1080707774201892 , 0.0300655474159266 ));
const std::vector<AtomEnum> extra_distances_atoms_a = boost::assign::list_of(H)(H)(H)(C)(C)(C)(O)(O)(O)(N)(N)(N)(O)(O)(O)(N)(N)(N)(CG)(CG)(CG)(CG)(CG)(CG)(CG)(CA);
const std::vector<AtomEnum> extra_distances_atoms_a_has_CG1 = boost::assign::list_of(H)(H)(H)(C)(C)(C)(O)(O)(O)(N)(N)(N)(O)(O)(O)(N)(N)(N)(CG1)(CG1)(CG1)(CG1)(CG1)(CG1)(CG1)(CA);
const std::vector<int> extra_distances_index_a = boost::assign::list_of(0)(0)(0)(-1)(-1)(-1)(0)(0)(0)(1)(1)(1)(-1)(-1)(-1)(0)(0)(0)(0)(0)(0)(0)(0)(-1)(1)(-1);
const std::vector<AtomEnum> extra_distances_atoms_b = boost::assign::list_of(HA)(C)(CB)(HA)(C)(CB)(HA)(N)(CB)(HA)(N)(CB)(HA)(N)(CB)(HA)(N)(CB)(HA)(N)(C)(C)(N)(CA)(CA)(CA);
const std::vector<int> extra_distances_index_b = boost::assign::list_of(0)(0)(0)(0)(0)(0)(0)(0)(0)(0)(0)(0)(-1)(-1)(-1)(-1)(-1)(-1)(0)(0)(0)(-1)(1)(0)(0)(1);
const std::vector< std::vector<double> > extra_distances_coefficients_STD = boost::assign::list_of
(vector_utils::make_vector( -0.2327537725120168 , -0.7434610853336412 , 0.0647726567487617 , 15.4137967310168911 , 2.1192318433573578 , -1.4828647529928054 ))
(vector_utils::make_vector( 0.4706843408840760 , -2.9678514938888858 , 0.3561690255622046 , -0.5081131040968113 , -0.3422196467049536 , 1.2635546824752146 ))
(vector_utils::make_vector( 0.1105157787599514 , 0.2527170538887184 , 0.4513891758262973 , 4.0841294344719596 , -0.5979143208127689 , -0.7675619677298110 ))
(vector_utils::make_vector( -0.2457149739239131 , -0.5493254061022271 , -0.1247353675950577 , 5.3175934476774236 , 1.4109850862368405 , 0.3151978153183097 ))
(vector_utils::make_vector( 0.6633010877903336 , -4.4043651876098560 , -0.7657827672601321 , -7.0572238382510930 , -1.8892011658375061 , 1.6521006663798627 ))
(vector_utils::make_vector( 0.1545140713173383 , -0.6886219316678216 , -0.1308587691975604 , -0.3235056665379997 , 0.6930223828283818 , -1.2033669179017203 ))
(vector_utils::make_vector( 0.1744758367822920 , -7.0504320420574054 , 0.1035088842582061 , -2.3941223792469768 , -1.3898243212722541 , 0.3167063375483198 ))
(vector_utils::make_vector( -0.4090631481129505 , 2.5129778529365119 , 0.6346262664676826 , 4.2262422240340154 , 1.7159429613823565 , -0.3455520347053589 ))
(vector_utils::make_vector( 0.0299335673716104 , 0.5613172842067488 , 0.0991564655803196 , 1.1221295068053800 , 0.1724716711103781 , 1.2120660376298542 ))
(vector_utils::make_vector( 0.0455485671890059 , -6.1961190017656183 , 0.1243992033405712 , -5.4083632273240712 , -0.2092066411134598 , 0.6101992441063459 ))
(vector_utils::make_vector( -0.2246818754758864 , 0.5916957565713907 , -0.0851907181209131 , 1.0503017607251885 , 1.2968192526928011 , -2.2062331209948525 ))
(vector_utils::make_vector( -0.0349462673775181 , 0.0887912775766414 , -0.0992273711873738 , -1.2712688509122840 , -0.0724524135568374 , 1.1441298857322129 ))
(vector_utils::make_vector( -0.1545062103968241 , 0.9721612856060365 , -0.4524308860083164 , -1.1365341311411681 , -0.5756206289092207 , -0.5670727612993436 ))
(vector_utils::make_vector( -0.2047421411757797 , -0.0910650806222269 , -0.4601405301186629 , -1.2419221807968472 , 0.2337041918213795 , -0.2115382959316337 ))
(vector_utils::make_vector( -0.0351304384086354 , 0.0416089255698555 , 0.0069608179960474 , -2.3622364702632010 , 0.2051320422404827 , 0.0624314523948168 ))
(vector_utils::make_vector( -0.1740476416117606 , 3.0052240947850835 , 1.3906446457831623 , -3.3287316816388861 , 0.0626518943452928 , -1.2740244469784334 ))
(vector_utils::make_vector( -0.1117979386963426 , 0.4661329374761521 , 0.8949211859105343 , -0.9896087901725740 , 0.3919709345295864 , 0.3155754143520899 ))
(vector_utils::make_vector( 0.0189609159083679 , 0.0051997123788217 , -0.0271163471489476 , 2.1847223244122040 , -0.1618807699177759 , -0.1044842614415138 ))
(vector_utils::make_vector( 0.1288138071282316 , -0.8250044235328394 , 0.0271430081218991 , 0.6921567390642597 , 0.0426615014638617 , -0.3201528219430570 ))
(vector_utils::make_vector( -0.0763196898939289 , -0.0433575471816446 , 0.1319915809295447 , 2.8791465161690728 , -0.1113439214177074 , 0.2273767073602392 ))
(vector_utils::make_vector( -0.1053257468091515 , 0.0469573987284508 , -0.0870100953054445 , 1.8044618730922539 , 0.0823026106999565 , -0.1843615877583412 ))
(vector_utils::make_vector( 0.0026591313498802 , -0.0793622958161787 , -0.0520901281365459 , 0.3628150267198967 , 0.0017187447663842 , -0.0786781253506630 ))
(vector_utils::make_vector( 0.0421798433262992 , -0.1619191930514815 , 0.0506248037111852 , -0.2754379070644002 , 0.0777307639166609 , 0.0508142295426293 ))
(vector_utils::make_vector( 0.0042209141405529 , -0.0016555104686380 , 0.0111822175134794 , -0.1476943571603808 , -0.0103181247020340 , 0.0103662738559297 ))
(vector_utils::make_vector( 0.0009935017699962 , 0.0177660859563433 , -0.0039801815004682 , 0.0286774166909111 , -0.0373196371069573 , 0.0036421820103526 ))
(vector_utils::make_vector( -0.0904906735392931 , 0.6891160788369899 , -0.0285187624652892 , -1.2469407664390031 , 0.5263285745529277 , 1.0999049802374714 ));
const std::vector< std::vector<double> > extra_distances_coefficients_GLY = boost::assign::list_of
(vector_utils::make_vector( -0.1629660879578154 , -0.1483797747953240 , 0.0135944020923718 , 8.7668470418514595 , 2.1013204141613575 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.4122232156105253 , -4.2093754717995475 , 0.5119418768961846 , -6.7520934039224638 , 0.3813989161701857 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.0651481396025584 , 0.2987554336382480 , 0.0891024304586266 , 5.6900611480768566 , 0.7835695910792380 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.5298099238829752 , -4.9560248207833411 , -0.9512783189490216 , -8.4671022239089471 , -0.8618283357491325 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0989332703943787 , -7.3344971907267054 , 0.0778165301875332 , -4.6575886335819172 , -0.8408603976060409 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.3374989576241305 , 3.5153174200856250 , 1.0217623617194076 , 3.4703764569864619 , 0.6362337246919650 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.0386912071139531 , -5.2279072056591520 , 0.0624355082482967 , -5.4231033415002017 , -0.1365514601895311 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.0449491497704767 , 2.1436292531610763 , 0.4497397629487193 , 1.1213514406428948 , -0.0124586373093357 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.1476901931001798 , 1.2056681155476945 , -0.3407769528552644 , -2.5179140366808772 , -0.3631720081855059 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.1780502829291453 , -0.1273926966023250 , -0.4324140572337213 , -1.1224459374490521 , 0.2225914090834448 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.0321439328360841 , -0.0121416754740498 , 0.0164976044653692 , -2.2819998469373064 , 0.1328632237671451 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.1467708067264057 , 2.8171413876456652 , 1.1421495179214447 , -3.7811287100029438 , 0.2795179961673692 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.0704203404476200 , 0.4414006003316404 , 0.8694494892505105 , -0.7475809368928292 , 0.4309026191323034 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0173538235824999 , 0.0600870906814004 , -0.0325651428253483 , 2.1044601588681005 , -0.0954738673195357 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.1217622490346982 , -0.9510271084838251 , 0.0289929562593090 , 0.3537814446416290 , 0.1096560053028174 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.0964119730694710 , -0.0116970105092207 , 0.2195153741026231 , 2.1215038224566860 , -0.1739344712760591 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.0905658306998866 , 0.0338832375804748 , -0.0730184384201802 , 1.9813139227624561 , 0.1401973762154448 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0240178060514893 , 0.0879132508231772 , -0.1232098585884028 , 1.0299103523376973 , 0.0526460225780781 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0367706019245998 , -0.0177006872483904 , 0.0122125584239812 , -0.5722059232934242 , -0.0112692563064339 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0040346917842457 , -0.0018201300216423 , 0.0107078420567873 , -0.1536395549761233 , -0.0100843594982366 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0013450652068098 , 0.0164845077572907 , -0.0026208560644205 , 0.0327524943759222 , -0.0375761740996758 , 0.0000000000000000 ))
(vector_utils::make_vector( -0.1203359210267845 , 0.6912473250160516 , -0.0638527469972065 , -1.0492796885051128 , 0.6711163259352118 , 0.0000000000000000 ));
const std::vector< std::vector<double> > extra_distances_coefficients_PRO = boost::assign::list_of
(vector_utils::make_vector( 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 , 0.0000000000000000 ))
(vector_utils::make_vector( 0.0239546070093792 , 0.0550619291101005 , 0.0000000000000000 , 0.0000000000000000 , -0.1309366834384617 , 0.6047780526346567 ))
(vector_utils::make_vector( 0.3639351437239245 , -1.8245109027177915 , 0.0000000000000000 , 0.0000000000000000 , -2.1589940685644833 , 1.0117690661696346 ))
(vector_utils::make_vector( 0.0601703000917738 , -1.1517461485226208 , 0.0000000000000000 , 0.0000000000000000 , 1.4440016177756672 , -0.4773940874763352 ))
(vector_utils::make_vector( 0.0466054255039325 , -7.9758753300570859 , 0.0000000000000000 , 0.0000000000000000 , -0.4737369164625927 , -0.4937453990708136 ))
(vector_utils::make_vector( 0.0608191710231485 , 0.0143416172460093 , 0.0000000000000000 , 0.0000000000000000 , 0.4166166517848814 , 1.2381646264022119 ))
(vector_utils::make_vector( -0.0032264572991822 , 0.1775679744800904 , 0.0000000000000000 , 0.0000000000000000 , 0.3098537727902358 , 0.9686944837680708 ))
(vector_utils::make_vector( -0.3380020580500724 , -7.1442735168864777 , 0.0000000000000000 , 0.0000000000000000 , 0.4825454184870776 , -0.0596234468168744 ))
(vector_utils::make_vector( 0.2101381408560941 , -1.4483086386065451 , 0.0000000000000000 , 0.0000000000000000 , 0.2440395105761634 , -0.0988846037284349 ))
(vector_utils::make_vector( -0.1088596362485086 , -0.1018623188324688 , 0.0000000000000000 , 0.0000000000000000 , 0.0799778073459886 , 0.4910314729394740 ))
(vector_utils::make_vector( -0.1535562092477574 , 0.9541830622950379 , 0.0000000000000000 , 0.0000000000000000 , -0.3530592544539594 , -0.1998448411620676 ))
(vector_utils::make_vector( -0.1617152999613833 , -0.0384508598870689 , 0.0000000000000000 , 0.0000000000000000 , 0.2598647672909007 , -0.2514972530364841 ))
(vector_utils::make_vector( -0.0505202191565388 , 0.0836813644168335 , 0.0000000000000000 , 0.0000000000000000 , 0.2533118226994268 , -0.0657324718258651 ))
(vector_utils::make_vector( -0.1062667395468319 , 2.7549949272350975 , 0.0000000000000000 , 0.0000000000000000 , 0.1927719443770226 , -0.5980128558748155 ))
(vector_utils::make_vector( -0.0340522976217987 , 0.2772182923887471 , 0.0000000000000000 , 0.0000000000000000 , 0.2516512019394374 , 0.3699693528990440 ))
(vector_utils::make_vector( 0.0358332568979297 , -0.0347704326109241 , 0.0000000000000000 , 0.0000000000000000 , -0.2073699162699771 , 0.0312340289707059 ))
(vector_utils::make_vector( 0.1186277785441283 , -0.5677036030926381 , 0.0000000000000000 , 0.0000000000000000 , 0.0794325445084602 , -0.2584041332659406 ))
(vector_utils::make_vector( -0.0881743953243073 , 0.4042955995484044 , 0.0000000000000000 , 0.0000000000000000 , -0.1171540354519404 , 0.2484874316523023 ))
(vector_utils::make_vector( -0.0746941675855248 , 0.3357446539962703 , 0.0000000000000000 , 0.0000000000000000 , -0.0332108269138727 , -0.0766511661101567 ))
(vector_utils::make_vector( 0.0187257774794178 , -0.1100215545273272 , 0.0000000000000000 , 0.0000000000000000 , 0.0023606182148274 , -0.1109009283261021 ))
(vector_utils::make_vector( 0.0290884104137601 , -0.1050780287569367 , 0.0000000000000000 , 0.0000000000000000 , 0.0711681169652281 , -0.0354933744489521 ))
(vector_utils::make_vector( 0.0042967900276731 , -0.0012084724186183 , 0.0000000000000000 , 0.0000000000000000 , -0.0091117155655707 , 0.0070465455445207 ))
(vector_utils::make_vector( 0.0011090333472978 , 0.0159162058946135 , 0.0000000000000000 , 0.0000000000000000 , -0.0382255838118731 , 0.0025660340838680 ))
(vector_utils::make_vector( -0.1514722682827673 , 0.7027407925859808 , 0.0000000000000000 , 0.0000000000000000 , 0.4796895622273615 , 0.3278770960547636 ));
const std::vector< std::vector< std::vector<double> > > h_bond_coefficients_STD = vector_utils::make_vector(
vector_utils::make_vector( vector_utils::make_vector( -0.0000000282031338 , -0.0000051459799364 , -0.0000001002522573 , -0.0000752745753528 , 0.0000084841881732 , 0.0000330236310932 ),
vector_utils::make_vector( -0.0005796092307362 , 0.0014532119467173 , -0.0012311624022499 , -0.0180410727641283 , 0.0039887352818585 , -0.0016325720526212 ),
vector_utils::make_vector( 0.0000686553425565 , -0.0001394025443860 , 0.0001250681663690 , 0.0018754630721178 , -0.0003916994112879 , 0.0001679474713272 )),
vector_utils::make_vector( vector_utils::make_vector( -0.0013889802066820 , 0.0030282694262701 , -0.0142871939850155 , -0.0134281396500305 , -0.0043335916047355 , -0.0066043027709330 ),
vector_utils::make_vector( 0.0001070501148444 , 0.0010660900640405 , 0.0044821168104993 , 0.0003982251798295 , -0.0004836765647620 , 0.0007734107517706 ),
vector_utils::make_vector( -0.0000005551578196 , -0.0001326314352363 , -0.0005105895005538 , -0.0001003438625951 , 0.0000546422621182 , -0.0000318020014415 )),
vector_utils::make_vector( vector_utils::make_vector( 0.0000011417579155 , -0.0000256866868294 , -0.0000054716349377 , -0.0000844009120467 , -0.0000169265202408 , -0.0000179063769460 ),
vector_utils::make_vector( 0.0003083994895787 , -0.0002917964674914 , 0.0002329421369477 , 0.0065627266457234 , -0.0113520436298094 , 0.0011680222668516 ),
vector_utils::make_vector( -0.0000280821315678 , 0.0000327703163447 , -0.0000156712360578 , -0.0006374109394798 , 0.0011652744395562 , -0.0001242807958497 )),
vector_utils::make_vector( vector_utils::make_vector( -0.0017768919557690 , -0.0052441212511289 , 0.0011321302112831 , -0.0155729317173500 , -0.0077359544686689 , 0.0017154808305490 ),
vector_utils::make_vector( 0.0008554647881461 , 0.0034480724272731 , 0.0001720228176968 , 0.0117727937978073 , 0.0057129845096505 , -0.0008403160975657 ),
vector_utils::make_vector( -0.0000814664661662 , -0.0003803280002150 , -0.0000099656455333 , -0.0012193090771868 , -0.0005442838122521 , 0.0001072639494233 )));
const std::vector< std::vector< std::vector<double> > > h_bond_coefficients_GLY= vector_utils::make_vector(
vector_utils::make_vector(vector_utils::make_vector( -0.0000002907998082 , -0.0000070177061944 , -0.0000007273745671 , -0.0000841575845031 , 0.0000098869044542 , 0.0000000000000000 ),
vector_utils::make_vector( -0.0004180100097135 , 0.0006044429279232 , -0.0012923575808506 , -0.0165728030779645 , 0.0046344365289007 , 0.0000000000000000 ),
vector_utils::make_vector( 0.0000524628403872 , -0.0000456608878495 , 0.0001313086596696 , 0.0017066638062792 , -0.0004593446433759 , 0.0000000000000000 )),
vector_utils::make_vector(vector_utils::make_vector( -0.0012570388298104 , 0.0030458713515906 , -0.0148477330964459 , -0.0126117427072834 , -0.0049752912287264 , 0.0000000000000000 ),
vector_utils::make_vector( 0.0001397845684297 , 0.0013572506381385 , 0.0051241668162604 , 0.0018564569337559 , -0.0006142031644329 , 0.0000000000000000 ),
vector_utils::make_vector( -0.0000042557898327 , -0.0001635560693932 , -0.0005738568836810 , -0.0002635919015118 , 0.0000670366993476 , 0.0000000000000000 )),
vector_utils::make_vector(vector_utils::make_vector( 0.0000014725572145 , -0.0000247184070314 , -0.0000060065649580 , -0.0000794896305481 , -0.0000164974714709 , 0.0000000000000000 ),
vector_utils::make_vector( 0.0001921141655518 , -0.0002636912353991 , 0.0000222387717641 , 0.0055338945175952 , -0.0107069106983101 , 0.0000000000000000 ),
vector_utils::make_vector( -0.0000161150368114 , 0.0000302841690449 , 0.0000062936785942 , -0.0005243670721043 , 0.0010977683921230 , 0.0000000000000000 )),
vector_utils::make_vector(vector_utils::make_vector( -0.0018399329804009 , -0.0050053132046419 , 0.0009498252012831 , -0.0132877536077687 , -0.0099267518393381 , 0.0000000000000000 ),
vector_utils::make_vector( 0.0009026529159328 , 0.0030799557668725 , 0.0000924936133315 , 0.0128629377173893 , 0.0060277767350753 , 0.0000000000000000 ),
vector_utils::make_vector( -0.0000829599350187 , -0.0003454358375957 , -0.0000008880923924 , -0.0013345402404848 , -0.0005737432137242 , 0.0000000000000000 )));
const std::vector< std::vector< std::vector<double> > > h_bond_coefficients_PRO = vector_utils::make_vector(
vector_utils::make_vector(vector_utils::make_vector( 0.0000000106947203 , -0.0000066945147632 , 0.0000000000000000 , 0.0000000000000000 , 0.0000089512754299 , 0.0000346923811024 ),
vector_utils::make_vector( -0.0005608301904310 , 0.0019834235716826 , 0.0000000000000000 , 0.0000000000000000 , 0.0044441638082640 , -0.0018972339169418 ),
vector_utils::make_vector( 0.0000672189906481 , -0.0001936593201240 , 0.0000000000000000 , 0.0000000000000000 , -0.0004372503594996 , 0.0001955533087025 )),
vector_utils::make_vector(vector_utils::make_vector( -0.0015128903636177 , 0.0025175897509730 , 0.0000000000000000 , 0.0000000000000000 , -0.0047887658717855 , -0.0068371581160723 ),
vector_utils::make_vector( -0.0000259144335337 , 0.0012989286901516 , 0.0000000000000000 , 0.0000000000000000 , -0.0003294881360286 , 0.0003867080201581 ),
vector_utils::make_vector( 0.0000134161951462 , -0.0001582132333663 , 0.0000000000000000 , 0.0000000000000000 , 0.0000370795205770 , 0.0000096417907864 )),
vector_utils::make_vector(vector_utils::make_vector( 0.0000018908643448 , -0.0000261455624599 , 0.0000000000000000 , 0.0000000000000000 , -0.0000179151464139 , -0.0000185711861684 ),
vector_utils::make_vector( 0.0002190356238162 , -0.0001292765912899 , 0.0000000000000000 , 0.0000000000000000 , -0.0111638832644578 , 0.0010705356847401 ),
vector_utils::make_vector( -0.0000187068507559 , 0.0000161586584846 , 0.0000000000000000 , 0.0000000000000000 , 0.0011469379498378 , -0.0001135069597227 )),
vector_utils::make_vector(vector_utils::make_vector( -0.0018291025863550 , -0.0047665783071595 , 0.0000000000000000 , 0.0000000000000000 , -0.0083926274754037 , 0.0016026400494938 ),
vector_utils::make_vector( 0.0007124126448637 , 0.0034823348669143 , 0.0000000000000000 , 0.0000000000000000 , 0.0057975109256993 , -0.0005457902539527 ),
vector_utils::make_vector( -0.0000661277852664 , -0.0003854114909012 , 0.0000000000000000 , 0.0000000000000000 , -0.0005542868984875 , 0.0000763639059674 )));
// p1, p2, p3, p4, p5, r, s
const std::vector< std::vector<double> > h_bond_parameters = vector_utils::make_vector(
vector_utils::make_vector(-0.403531, 13.914800, -0.421725, -3.080160, 0.987251, 3.000000, -16.500000), //d
vector_utils::make_vector(15.048600, -1.794690, -1.794690, 1.493980, 1.493980, 15.500000, 2.500000), // g1
vector_utils::make_vector(12.151400, -1.122580, -1.122580, 1.309530, 1.309530, 15.500000, 3.000000)); //g2
const std::vector< std::vector< std::vector<double> > > dihedral_angle_data = vector_utils::make_vector(
vector_utils::make_vector(
vector_utils::make_vector(0.3, 0.4, 0.0, 0.1, 3.0),
vector_utils::make_vector(-0.170287, 0.278618, 0.0609298, 2.48692, -3.07025),
vector_utils::make_vector(-0.0244394, -0.137248, 0.0560274, -5.42115, 2.27543)),
vector_utils::make_vector(
vector_utils::make_vector(1.5, -3.0, 0.0, 2.45, -2.7),
vector_utils::make_vector(-0.4, -1.5, 0.7, 4.8, -8.4),
vector_utils::make_vector(0.1, 0.9, 0.6, -6.0, 2.2)),
vector_utils::make_vector(
vector_utils::make_vector(-0.4, -0.3, 0.2, 3.6, -3.4),
vector_utils::make_vector(-0.104686, 0.174676, 0.0639679, 3.51401, -2.82811),
vector_utils::make_vector(0.0343048, 0.0448763, 0.0406634, 3.42026, 4.15534)),
vector_utils::make_vector(
vector_utils::make_vector(-2.1, -1.2, 0.2, 3.2, -2.7),
vector_utils::make_vector(-1.4, 2.2, 0.3, 4.2, -2.5),
vector_utils::make_vector(0.5, 1.2, -0.1, 2.2, 2.9)),
vector_utils::make_vector(
vector_utils::make_vector(0.9, -2.9, -1.2, 2.4, -2.5),
vector_utils::make_vector(-0.7, -0.9, 0.0, 5.1, -8.3),
vector_utils::make_vector(0.1, -0.5, -0.1, 19.9, 11.0)),
vector_utils::make_vector(
vector_utils::make_vector(1.0, 1.8, 0.0, 0.8, 2.5),
vector_utils::make_vector(0.5, 2.0, 0.8, -0.6, 2.6),
vector_utils::make_vector(-0.4, 0.5, 1.1, 8.9, 11.0)));
const std::vector< std::vector<double> > dihedral_angle_coefficients_STD = vector_utils::make_vector(
vector_utils::make_vector( 0.3960648266256248 , 0.4778015421275076 , 0.1404857172922052 , 0.1306176954231868 , -0.0663646004926076 , 0.6368372402015872 ),
vector_utils::make_vector( 0.1769539713756307 , 0.3692802227577077 , 0.2091437872377169 , 0.1913852711909124 , 0.0596866314256868 , 0.7241998961047388 ),
vector_utils::make_vector( -0.0277768847874686 , 0.1878351967457690 , -0.2363656636502869 , 0.2126343233923858 , 0.2778522377186216 , 0.1438778040054098 ));
const std::vector< std::vector<double> > dihedral_angle_coefficients_GLY = vector_utils::make_vector(
vector_utils::make_vector( 0.4864763875098092 , 0.4169098831669225 , 0.2348973929731843 , 0.2576443711017197 , 0.1099509049657858 , 0.0000000000000000 ),
vector_utils::make_vector( 0.2353465526977265 , 0.2842275658626817 , -0.0211099172245951 , 0.1762756929941207 , 0.1410860963149856 , 0.0000000000000000 ),
vector_utils::make_vector( 0.0417890756901886 , 0.0925030379172491 , -0.2358528055654943 , 0.1582805707089231 , 0.4117375204162685 , 0.0000000000000000 ));
const std::vector< std::vector<double> > dihedral_angle_coefficients_PRO = vector_utils::make_vector(
vector_utils::make_vector( 0.4106708555264520 , 0.4819390303506603 , 0.0000000000000000 , 0.0000000000000000 , -0.0141746391470785 , 0.5496765676933106 ),
vector_utils::make_vector( 0.2242677600617599 , 0.4381989380648809 , 0.0000000000000000 , 0.0000000000000000 , 0.1017863282197456 , 0.7898445337153742 ),
vector_utils::make_vector( 0.0579211882516378 , 0.0899445202920860 , 0.0000000000000000 , 0.0000000000000000 , 0.4338489738287987 , 0.1205187987678361 ));
const std::vector< std::vector<double> > side_chain_ALA_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , -3.4713212362 , 0.0 , 0.0 , 0.0 , -4.03371047401e-10)); // CB
const std::vector<AtomEnum> side_chain_ALA_atoms = vector_utils::make_vector( CB);
const std::vector< std::vector<double> > side_chain_ARG_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , -1.03531050923e-11 ), // CB
vector_utils::make_vector( 0.0 , 1.11446737284 , 0.0 , 0.872527453389 , 0.0 , 0.0 ), // CG
vector_utils::make_vector( 0.0 , 0.816244335806 , 0.0 , 0.0 , 0.0 , 0.467044601879 ), // CD
vector_utils::make_vector( -0.0430367846259 , -2.88638408045 , 0.0 , 0.0024324800869 , -0.241574898855 , -3.65950929799 ), // NE
vector_utils::make_vector( 0.0 , 1.23860564144 , 0.0 , 0.0 , 0.0 , 1.63816505265 ), // CZ
vector_utils::make_vector( 0.0191117398481 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 ), // NH2
vector_utils::make_vector( 0.0714607882387 , -1.94562320221 , 0.00858815825385 , -1.61050407974 , 0.0172898471359 , 1.33225475561 ), // HB1
vector_utils::make_vector( 0.0714607882387 , -1.94562320221 , 0.00858815825385 , -1.61050407974 , 0.0172898471359 , 1.33225475561 ), // HB2
vector_utils::make_vector( -0.0239777858545 , -0.24226518653 , -0.0352421962907 , -0.810112759198 , 0.0405181818607 , -0.156830656495 ), // HG1
vector_utils::make_vector( -0.0239777858545 , -0.24226518653 , -0.0352421962907 , -0.810112759198 , 0.0405181818607 , -0.156830656495 ), // HG2
vector_utils::make_vector( -0.00871362712689 , 0.320748206415 , 0.0121352679896 , -0.367063291071 , -0.0337978266234 , -0.204970811794 ), // HD1
vector_utils::make_vector( -0.00871362712689 , 0.320748206415 , 0.0121352679896 , -0.367063291071 , -0.0337978266234 , -0.204970811794 ), // HD2
vector_utils::make_vector( -0.00952853494255 , 1.23493238497 , -0.0173074088574 , -0.423682913363 , 0.0948721028635 , 1.1871343381)); // HE
const std::vector<AtomEnum> side_chain_ARG_atoms = vector_utils::make_vector( CB, CG, CD, NE, CZ, NH2, HB2, HB3, HG2, HG3, HD2, HD3, HE);
const std::vector< std::vector<double> > side_chain_ASN_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , -1.02791434406e-09 ), // CB
vector_utils::make_vector( -0.183170893084 , -13.4402878546 , 0.0 , -2.07590514409 , 0.0 , -2.2441664389 ), // CG
vector_utils::make_vector( -0.0327841254823 , 5.01241677844 , -0.0625137208002 , -0.4411606783 , -0.351623596802 , 0.0 ), // OD1
vector_utils::make_vector( 0.0 , 4.10410138558 , 0.0 , -0.09504336489 , 0.0 , 1.76656371222 ), // ND2
vector_utils::make_vector( 0.100685017355 , 0.676276893808 , 0.0245500105499 , -1.25636964386 , 0.138792958445 , 0.0 ), // HB1
vector_utils::make_vector( 0.100685017355 , 0.676276893808 , 0.0245500105499 , -1.25636964386 , 0.138792958445 , 0.0)); // HB2
const std::vector<AtomEnum> side_chain_ASN_atoms = vector_utils::make_vector( CB, CG, OD1, ND2, HB2, HB3);
const std::vector< std::vector<double> > side_chain_ASP_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 6.57650723449 , 0.0 , -3.86904673479 , 0.0 , -1.82520889657e-09 ), // CB
vector_utils::make_vector( 0.0 , -5.83223852837 , -0.0110423556333 , 4.543565917 , 0.0 , 0.42403040775 ), // CG
vector_utils::make_vector( -0.102593321506 , 1.64152303195 , -0.0778158053208 , -2.85721881167 , -0.196800498214 , -0.572828472065 ), // OD1
vector_utils::make_vector( -0.0972177814601 , 1.67683630389 , 0.00831444407059 , -2.68828144756 , -0.160742255169 , 0.799564949181 ), // OD2
vector_utils::make_vector( 0.121892290619 , -1.77876897637 , 0.0294314938147 , -0.0839806810365 , 0.00881768948368 , 0.0 ), // HB1
vector_utils::make_vector( 0.121892290619 , -1.77876897637 , 0.0294314938147 , -0.0839806810365 , 0.00881768948368 , 0.0)); // HB2
const std::vector<AtomEnum> side_chain_ASP_atoms = vector_utils::make_vector( CB, CG, OD1, OD2, HB2, HB3);
const std::vector< std::vector<double> > side_chain_CYS_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 1.31518529149e-09 ), // CB
vector_utils::make_vector( 0.0 , 0.0 , -0.00718723198401 , -0.989548882578 , -0.122230352072 , 0.0 ), // SG
vector_utils::make_vector( 0.0 , 0.0 , -0.00851619869805 , -2.30327254728 , -0.0245121416492 , 0.0 ), // HB1
vector_utils::make_vector( 0.0 , 0.0 , -0.00851619869805 , -2.30327254728 , -0.0245121416492 , 0.0 ), // HB2
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , -5.30723849196)); // HG1
const std::vector<AtomEnum> side_chain_CYS_atoms = vector_utils::make_vector( CB, SG, HB2, HB3, HG);
const std::vector< std::vector<double> > side_chain_GLN_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , -3.75252018162 , 0.0 , -2.95671985085e-11 ), // CB
vector_utils::make_vector( 0.0 , -0.456614258718 , 0.0 , -4.01550975281 , 0.0 , 17.3023434025 ), // CG
vector_utils::make_vector( 0.0 , 3.58838866256 , 0.0 , 6.90171110302 , 0.0 , -13.8469738198 ), // CD
vector_utils::make_vector( -0.0259782226579 , -1.02403319008 , -0.0870416987021 , -2.8876884785 , 0.0138941490625 , 4.56616558982 ), // OE1
vector_utils::make_vector( 0.00920930895911 , -1.01164987967 , 0.0 , -2.07990347484 , -0.0306655923957 , 3.94693048662 ), // NE2
vector_utils::make_vector( 0.0460136969189 , -2.18090660502 , 0.0038255270431 , -0.538439030258 , -0.126303238513 , 8.81885811057 ), // HB1
vector_utils::make_vector( 0.0460136969189 , -2.18090660502 , 0.0038255270431 , -0.538439030258 , -0.126303238513 , 8.81885811057 ), // HB2
vector_utils::make_vector( -0.0323310812764 , 0.74291817446 , 0.0268177189018 , 0.437708465156 , -0.00141858271069 , -8.82627729932 ), // HG1
vector_utils::make_vector( -0.0323310812764 , 0.74291817446 , 0.0268177189018 , 0.437708465156 , -0.00141858271069 , -8.82627729932)); // HG2
const std::vector<AtomEnum> side_chain_GLN_atoms = vector_utils::make_vector( CB, CG, CD, OE1, NE2, HB2, HB3, HG2, HG3);
const std::vector< std::vector<double> > side_chain_GLU_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , -0.377316229832 , 0.0 , -6.6562578029e-10 ), // CB
vector_utils::make_vector( 0.0 , -2.89342672812 , 0.0 , -4.97041127725 , 0.0 , 0.0 ), // CG
vector_utils::make_vector( 0.0 , 4.50008565016 , 0.0 , 5.29399006331 , 0.0 , -4.78327187836 ), // CD
vector_utils::make_vector( -0.0187234504936 , -1.38309478668 , -0.158967761851 , -2.18374376316 , 0.00611131629348 , 1.33252672237 ), // OE1
vector_utils::make_vector( -0.0240431350563 , -1.31993394802 , -0.107750497661 , -1.81048822194 , 0.139052667261 , 1.13465867345 ), // OE2
vector_utils::make_vector( 0.0534451603877 , -1.203442928 , 0.104330816638 , -1.10196170191 , -0.0804854771338 , 0.0 ), // HB1
vector_utils::make_vector( 0.0534451603877 , -1.203442928 , 0.104330816638 , -1.10196170191 , -0.0804854771338 , 0.0 ), // HB2
vector_utils::make_vector( -0.00843186218028 , 1.01182454146 , 0.068776706444 , 0.498815541224 , -0.0505778188416 , 1.27995595533 ), // HG1
vector_utils::make_vector( -0.00843186218028 , 1.01182454146 , 0.068776706444 , 0.498815541224 , -0.0505778188416 , 1.27995595533)); // HG2
const std::vector<AtomEnum> side_chain_GLU_atoms = vector_utils::make_vector( CB, CG, CD, OE1, OE2, HB2, HB3, HG2, HG3);
//FROM par.gly file
const std::vector< std::vector<double> > side_chain_GLY_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0599289840908 , -3.53032988169 , 0.0304210030403 , 1.38032425626 , 0.465339465619 , 0.0 )); // HA2
const std::vector<AtomEnum> side_chain_GLY_atoms = vector_utils::make_vector( HA2); //Must be HA2 in Phaistos!!
const std::vector< std::vector<double> > side_chain_HIS_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 1.82830325357 , 0.0 , -16.9291535085 , 0.0 , 1.09880622641e-09 ), // CB
vector_utils::make_vector( -0.153075416471 , -2.61944587024 , 0.0 , 2.43340067277 , 0.0 , 0.0 ), // CG
vector_utils::make_vector( 0.0 , -0.419947401913 , 0.0 , -2.88666727557 , 0.0 , 0.0 ), // ND1
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , -3.68870141246 ), // CD2
vector_utils::make_vector( 0.0 , -4.92310183027 , 0.0 , 0.0 , 0.0 , 0.0 ), // NE2
vector_utils::make_vector( 0.066781519345 , -4.50333656372 , 0.022492277865 , 2.86581859294 , 0.0057743713673 , 0.0 ), // HB1
vector_utils::make_vector( 0.066781519345 , -4.50333656372 , 0.022492277865 , 2.86581859294 , 0.0057743713673 , 0.0 ), // HB2
vector_utils::make_vector( 0.0 , 7.9189162559 , -0.0302490130949 , -0.775471589614 , -0.0588563626968 , 2.61568966021 ), // HD1
vector_utils::make_vector( 0.0 , 7.9189162559 , -0.0302490130949 , -0.775471589614 , -0.0588563626968 , 2.61568966021 ), // HD2
vector_utils::make_vector( 0.0 , -2.20280531486 , -0.0142549703918 , 3.2003381435 , 0.0239426526044 , -1.58410948627)); // HE1
const std::vector<AtomEnum> side_chain_HIS_atoms = vector_utils::make_vector( CB, CG, ND1, CD2, NE2, HB2, HB3, HD1, HD2, HE1);
const std::vector< std::vector<double> > side_chain_ILE_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , -1.96481052694e-10 ), // CB
vector_utils::make_vector( 0.0 , -1.66488560778 , 0.0 , 0.0 , 0.0 , 28.0479128104 ), // CG1
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 30.3726662011 ), // CD
vector_utils::make_vector( 0.0 , 1.29700467785 , 0.0 , -4.71851827233 , 0.0 , 22.657752454 ), // HB
vector_utils::make_vector( -0.0111564636628 , 0.0 , -0.000638523964496 , -0.506705876815 , -0.180421602653 , -33.3863363183 ), // HG11
vector_utils::make_vector( -0.0111564636628 , 0.0 , -0.000638523964496 , -0.506705876815 , -0.180421602653 , -33.3863363183)); // HG12
const std::vector<AtomEnum> side_chain_ILE_atoms = vector_utils::make_vector( CB, CG1, CD1, HB, HG12, HG13);
const std::vector< std::vector<double> > side_chain_LEU_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 3.51794597314 , 0.0 , 0.0 , 0.0 , -8.91936991364e-10 ), // CB
vector_utils::make_vector( 0.0 , 3.88613855384 , -0.0712585733415 , -1.83168322005 , 0.0 , 0.0 ), // CG
vector_utils::make_vector( 0.00245439278859 , -3.5176338264 , 0.0203020521122 , -2.00872784258 , -0.238336770306 , 0.0 ), // HB1
vector_utils::make_vector( 0.00245439278859 , -3.5176338264 , 0.0203020521122 , -2.00872784258 , -0.238336770306 , 0.0 ), // HB2
vector_utils::make_vector( 0.0 , -0.709602436933 , 0.00228804372959 , 0.0301226983886 , 0.1279976817 , 0.544387507169)); // HG1
const std::vector<AtomEnum> side_chain_LEU_atoms = vector_utils::make_vector( CB, CG, HB2, HB3, HG);
const std::vector< std::vector<double> > side_chain_LYS_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , -6.30608435036 , 0.0 , 9.75761233655e-10 ), // CB
vector_utils::make_vector( 0.0 , -0.361390657843 , 0.0 , 1.65825293028 , 0.0 , -11.6109579883 ), // CG
vector_utils::make_vector( 0.0 , 1.42931928849 , 0.0 , -0.51010930012 , 0.0 , -0.14317680276 ), // CD
vector_utils::make_vector( 0.0 , -2.14588385153 , 0.0 , 0.0 , 0.0 , -0.701125918268 ), // CE
vector_utils::make_vector( 0.0 , 0.552820632793 , 0.0 , 0.0 , -0.0459614371365 , 0.185543226303 ), // NZ
vector_utils::make_vector( 0.0464037003472 , -1.36084749724 , -0.00655416308051 , 0.0779635914533 , -0.0536679540163 , 0.0 ), // HB1
vector_utils::make_vector( 0.0464037003472 , -1.36084749724 , -0.00655416308051 , 0.0779635914533 , -0.0536679540163 , 0.0 ), // HB2
vector_utils::make_vector( -0.02597340034 , 0.236013218495 , -0.0174148989543 , -0.785687454858 , 0.00151360921447 , 4.47148787915 ), // HG1
vector_utils::make_vector( -0.02597340034 , 0.236013218495 , -0.0174148989543 , -0.785687454858 , 0.00151360921447 , 4.47148787915 ), // HG2
vector_utils::make_vector( -0.0118797877716 , -0.0534136566698 , 0.00767676351305 , 0.0678926181782 , 0.0212682285098 , -0.0186077518884 ), // HD1
vector_utils::make_vector( -0.0118797877716 , -0.0534136566698 , 0.00767676351305 , 0.0678926181782 , 0.0212682285098 , -0.0186077518884 ), // HD2
vector_utils::make_vector( 0.00222526395378 , 0.599469738054 , -0.0125535881158 , -0.0203757793151 , -0.00986667749524 , 0.24546779373 ), // HE1
vector_utils::make_vector( 0.00222526395378 , 0.599469738054 , -0.0125535881158 , -0.0203757793151 , -0.00986667749524 , 0.24546779373)); // HE2
const std::vector<AtomEnum> side_chain_LYS_atoms = vector_utils::make_vector( CB, CG, CD, CE, NZ, HB2, HB3, HG2, HG3, HD2, HD3, HE2, HE3);
const std::vector< std::vector<double> > side_chain_MET_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , -1.10478068502e-09 ), // CB
vector_utils::make_vector( 0.0 , -0.645923355948 , -0.652553325489 , 0.0 , 0.0 , 0.0 ), // CG
vector_utils::make_vector( -0.16364830972 , 2.83511129497 , 0.13644559576 , 1.28231605991 , -0.0427727642165 , -6.35909454157 ), // SD
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , -0.545766241509 , 0.0 , 0.0 ), // CE
vector_utils::make_vector( 0.137756130224 , -3.78151434563 , 0.0148497085195 , -2.24703600476 , -0.0459649511504 , 0.0 ), // HB1
vector_utils::make_vector( 0.137756130224 , -3.78151434563 , 0.0148497085195 , -2.24703600476 , -0.0459649511504 , 0.0 ), // HB2
vector_utils::make_vector( -0.00849847825403 , 0.943125169888 , 0.18339726423 , -0.991317041911 , 0.0799359869328 , 4.30426538868 ), // HG1
vector_utils::make_vector( -0.00849847825403 , 0.943125169888 , 0.18339726423 , -0.991317041911 , 0.0799359869328 , 4.30426538868)); // HG2
const std::vector<AtomEnum> side_chain_MET_atoms = vector_utils::make_vector( CB, CG, SD, CE, HB2, HB3, HG2, HG3);
const std::vector< std::vector<double> > side_chain_PHE_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , -0.0108481964591 , -7.13951201419 , 1.6285523119 , 1.63464800208e-10 ), // CB
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.90720639743 , 0.0 , 0.0 ), // CZ
vector_utils::make_vector( 0.0 , -0.346976381608 , -0.0321609673341 , -0.802154239826 , -0.824840492786 , 0.0 ), // HB1
vector_utils::make_vector( 0.0 , -0.346976381608 , -0.0321609673341 , -0.802154239826 , -0.824840492786 , 0.0)); // HB2
const std::vector<AtomEnum> side_chain_PHE_atoms = vector_utils::make_vector( CB, CZ, HB2, HB3);
//FROM par.pro files
const std::vector< std::vector<double> > side_chain_PRO_data = vector_utils::make_vector(
vector_utils::make_vector( 0.766315854944 , -6.67483104488 , 0.0 , 0.0 , -6.53301390511 , 4.61158587977e-10 ), // CB
vector_utils::make_vector( -1.06933191871 , -4.45177134585 , 0.0 , 0.0 , -9.05663273631 , 37.2196860372 ), // CG
vector_utils::make_vector( 0.513746061748 , -1.50489128089 , 0.0 , 0.0 , -3.77912191871 , 3.97232248492 ), // CD
vector_utils::make_vector( -0.785691570236 , 0.198962501194 , 0.0 , 0.0 , 2.30727040717 , 21.046668963 ), // HB1
vector_utils::make_vector( -0.785691570236 , 0.198962501194 , 0.0 , 0.0 , 2.30727040717 , 21.046668963 ), // HB2
vector_utils::make_vector( 0.644202991836 , 2.03227333337 , 0.0 , 0.0 , 3.81406346752 , -21.4484437153 ), // HG1
vector_utils::make_vector( 0.644202991836 , 2.03227333337 , 0.0 , 0.0 , 3.81406346752 , -21.4484437153 ), // HG2
vector_utils::make_vector( -0.137795776966 , 1.54573355392 , 0.0 , 0.0 , 2.03922840659 , -2.86174390751 ), // HD1
vector_utils::make_vector( -0.137795776966 , 1.54573355392 , 0.0 , 0.0 , 2.03922840659 , -2.86174390751 )); // HD2
const std::vector<AtomEnum> side_chain_PRO_atoms = vector_utils::make_vector( CB, CG, CD, HB2, HB3, HG2, HG3, HD2, HD3);
const std::vector< std::vector<double> > side_chain_SER_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 1.79407270536 , 0.0 , 0.0 , 0.0 , 1.40305678357e-12 ), // CB
vector_utils::make_vector( -0.113051836575 , 0.793923501464 , -0.558025317975 , -8.01062342831 , -3.38102218137 , 0.0 ), // OG
vector_utils::make_vector( 0.0652575203998 , -1.3559362377 , -0.0265320022 , -1.36351244674 , -0.0776100488467 , -4.55176284981 ), // HB1
vector_utils::make_vector( 0.0652575203998 , -1.3559362377 , -0.0265320022 , -1.36351244674 , -0.0776100488467 , -4.55176284981 ), // HB2
vector_utils::make_vector( -0.00878828423241 , 0.0 , 0.458618591127 , 4.4828757499 , 2.98258179417 , 6.08562260172)); // HG1
const std::vector<AtomEnum> side_chain_SER_atoms = vector_utils::make_vector( CB, OG, HB2, HB3, HG);
const std::vector< std::vector<double> > side_chain_THR_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 8.13812368131 , 0.0 , 2.3915263035e-12 ), // CB
vector_utils::make_vector( -0.0535247676171 , -2.00769271973 , 0.0281539908539 , -4.67975420411 , -0.655624096407 , 1.23187775141 ), // OG1
vector_utils::make_vector( 0.0 , 2.80742004172 , 0.0 , 0.0 , 0.0 , 0.0 ), // CG2
vector_utils::make_vector( 0.04445648824 , -1.88339667766 , -0.0463286732656 , -6.9078573272 , 0.475330611684 , 0.0)); // HB
const std::vector<AtomEnum> side_chain_THR_atoms = vector_utils::make_vector( CB, OG1, CG2, HB);
const std::vector< std::vector<double> > side_chain_TRP_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , -3.61890896893e-12 ), // CB
vector_utils::make_vector( 0.0 , 12.3509849143 , 0.0 , 0.0 , 0.0 , 0.0 ), // CD2
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 6.21717953851 ), // NE1
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , -7.9272256977 , 0.0 , 0.0 ), // CE2
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 9.08877429759 , 0.0 , 0.0 ), // CE3
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , -5.04256744009 , 0.0 , -2.93570158516 ), // CZ2
vector_utils::make_vector( 0.00929384945248 , -0.421493841927 , 0.103332157035 , -1.80682074242 , -0.226833124881 , 0.0 ), // HB1
vector_utils::make_vector( 0.00929384945248 , -0.421493841927 , 0.103332157035 , -1.80682074242 , -0.226833124881 , 0.0 ), // HB2
vector_utils::make_vector( -0.215472755574 , 12.5022417653 , -0.401058528252 , -8.51144121319 , 0.0953496726981 , 0.0279604764831 ), // HD1
vector_utils::make_vector( 0.0 , -11.9436476252 , 0.370070105302 , 14.3661544338 , 0.0 , -5.32742492601 ), // HE1
vector_utils::make_vector( -0.387382770229 , 0.0 , -0.297531376905 , -5.7956769123 , 0.0 , -1.18319148206 ), // HE3
vector_utils::make_vector( 0.0 , -7.57517906396 , 0.0 , 0.0 , 0.0 , 1.15100135153 ), // HZ2
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 2.60021425436 ), // HZ3
vector_utils::make_vector( 0.327714650343 , 3.88836256761 , 0.0 , 0.0 , 0.0876171296868 , 0.0 )); // HH2
const std::vector<AtomEnum> side_chain_TRP_atoms = vector_utils::make_vector( CB, CD2, NE1, CE2, CE3, CZ2, HB2, HB3, HD1, HE1, HE3, HZ2, HZ3, HH2);
const std::vector< std::vector<double> > side_chain_TYR_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , -10.6970183542 , 0.0 , 2.83653011196e-12 ), // CB
vector_utils::make_vector( 0.0 , 2.96756007 , 0.0 , 5.09554633209 , 0.0 , 0.0 ), // CG
vector_utils::make_vector( 0.0 , -1.66791262959 , 0.0 , 0.0 , 0.0 , 0.0 ), // CD2
vector_utils::make_vector( 0.0158654945788 , -3.67150867964 , 0.0 , -1.46107158447 , 0.0 , -0.020959848634 ), // OH
vector_utils::make_vector( 0.0 , 4.8082254581 , -0.0116527339907 , 0.457916534236 , -0.0937108309252 , 0.0070312669555 ), // HB1
vector_utils::make_vector( 0.0 , 4.8082254581 , -0.0116527339907 , 0.457916534236 , -0.0937108309252 , 0.0070312669555)); // HB2
const std::vector<AtomEnum> side_chain_TYR_atoms = vector_utils::make_vector( CB, CG, CD2, OH, HB2, HB3);
const std::vector< std::vector<double> > side_chain_VAL_data = vector_utils::make_vector(
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , -1.97923732755 , 0.0 , -5.05953063116e-12 ), // CB
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.349675629467 ), // CG1
vector_utils::make_vector( 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.349675629467 ), // CG2
vector_utils::make_vector( 0.0 , -0.752456959203 , -0.0188545119448 , -4.27891949771 , -0.544414888703 , 0.0 )); // HB
const std::vector<AtomEnum> side_chain_VAL_atoms = vector_utils::make_vector( CB, CG1, CG2, HB);
//COIL -- OK !
const std::vector< std::vector<double> > random_coil_data = vector_utils::make_vector(
vector_utils::make_vector( 4.432847, 52.266440, 8.24, 123.8, 177.1, 19.0, -0.20),
vector_utils::make_vector( 4.350150, 56.240260, 8.23, 120.5, 176.5, 30.3, 1.45),
vector_utils::make_vector( 4.806587, 53.309020, 8.30, 118.7, 175.5, 39.0, 1.15),
vector_utils::make_vector( 4.725179, 54.158222, 8.34, 120.4, 177.2, 40.8, 1.18),
vector_utils::make_vector( 4.650000, 57.791772, 8.32, 118.6, 175.1, 41.8, 2.43),
vector_utils::make_vector( 4.405826, 56.062813, 8.32, 119.8, 176.3, 30.1, 1.57),
vector_utils::make_vector( 4.364552, 56.503798, 8.42, 120.2, 176.1, 29.7, 1.80),
vector_utils::make_vector( 3.970000, 45.486533, 8.33, 108.8, 173.6, 0.0, 1.07),
vector_utils::make_vector( 4.615947, 55.660394, 8.32, 118.2, 175.1, 32.0, 1.20),
vector_utils::make_vector( 4.193333, 61.206185, 8.05, 119.9, 176.8, 37.5, 4.14),
vector_utils::make_vector( 4.402746, 54.957697, 8.16, 121.8, 177.1, 41.9, 1.50),
vector_utils::make_vector( 4.368070, 56.243301, 8.29, 120.4, 176.5, 32.3, 1.55),
vector_utils::make_vector( 4.461933, 55.367000, 8.28, 119.6, 175.5, 32.8, 1.33),
vector_utils::make_vector( 4.430244, 57.646240, 8.30, 120.3, 175.8, 39.3, 1.25),
vector_utils::make_vector( 4.658447, 63.066266, 0.00, 0.0, 176.0, 31.7, 0.60),
vector_utils::make_vector( 4.504638, 58.144025, 8.31, 115.7, 173.7, 62.7, 2.59),
vector_utils::make_vector( 4.324869, 62.542020, 8.15, 113.6, 175.2, 68.1, 3.20),
vector_utils::make_vector( 4.412784, 56.208648, 8.15, 121.3, 175.8, 28.3, 1.64),
vector_utils::make_vector( 4.339301, 57.338180, 8.12, 120.3, 175.7, 38.7, 1.75),
vector_utils::make_vector( 4.086605, 62.512466, 8.03, 119.2, 177.1, 31.7, 3.83));
const std::vector< std::vector<double> > backbone_distances_data_STD = vector_utils::make_vector(
vector_utils::make_vector(0.10495380090732243, 00.000000000, 0.08675460835995771, 00.000000000, -0.35325986523300673, 00.000000000, -0.23275377251201915, 00.000000000, -5.367031470580472e-13, 00.000000000, 0.17447583678230483, 00.000000000, 0.14871171068329672, -0.053296746569885985, 0.03882038067484881, 0.11174638829048561),
vector_utils::make_vector(-0.5514491272711721, -0.317165242562441, -2.2950957826753307, 5.038915848408274, -0.9486055559477894, 00.000000000, 3.9203989031538184, -1.9490589173162214e-10, 7.888410038586696, 6.211182450143531, 3.696581556678636, 0.8900045157214647, 1.0575798185417868, 0.843178315332479, -0.006841941314662635, 0.5577505622026423),
vector_utils::make_vector(-0.7220064276597629, 0.718428078157317, -1.2431488450135015, 00.000000000, 00.000000000, 00.000000000, 1.4040337379295934e-11, 00.000000000, 0.06477265674883699, 0.3561690255620862, -0.5820468821370581, -0.4391425656607752, 00.000000000, 0.3153333333421696, -0.04764241032826434, -0.03674562604899119),
vector_utils::make_vector(-0.9896087901749597, 00.000000000, -3.3287316816428802, 10.74798119339772, -1.6351734790157095, -4.716497136294274e-10, -3.5391268117345294, -15.905456499801042, -2.188220081012427, 1.7859755656813219, 4.226242224034082, 1.0503017607250316, 4.169602548794144, -3.515118468842189, 0.7841272708579441, 0.049269118119305705),
vector_utils::make_vector(-0.0335256937556629, -0.3228718094361184, -0.3565204453816248, 00.000000000, -0.40079984897073373, 00.000000000, -0.34221964670495214, 00.000000000, 00.000000000, -4.0706993336807334e-11, 00.000000000, 00.000000000, 00.000000000, -1.4947525215073552, -0.19452341501188974, -0.8447972445280089),
vector_utils::make_vector(-0.2954355834730914, -0.1651180756238783, 0.41374535951234304, -1.203366917902715, 0.9872423059576032, 3.605111738963296, -0.7675619677317889, 00.000000000, 1.5204107711708694, -5.792235516845152, 1.2120660376313594, 1.1441298857285918, 0.9460462905709635, -2.4318195762095236, 0.129054286671938, 0.11095702467304198));
const std::vector< std::vector<double> > backbone_distances_data_GLY = vector_utils::make_vector(
vector_utils::make_vector(0.06631745549753744, 00.000000000, 0.08053716893343965, 00.000000000, -0.3009441311219224, 00.000000000, -0.16296608795780956, 00.000000000, 3.3857048090857263e-12, 00.000000000, 0.09893327039437384, 00.000000000, 0.13311142001205686, 0.0646256499482128, 0.022134597201919272, 0.10541014389184017),
vector_utils::make_vector(-0.4879557763604076, -0.5317572323214436, -1.7137741845968946, 3.8804893083829817, -1.0573318803614427, 00.000000000, 2.8169776432915232, 1.912141415671544e-10, 6.631387540142962, 6.784605289137453, 3.99731663680024, -1.501909262082764, 0.799569167794496, 1.0488699289637873, -0.0029700727148061976, 0.5482871837173448),
vector_utils::make_vector(-0.679173951206218, 0.701488775320716, -1.060191763327514, 00.000000000, 00.000000000, 00.000000000, 3.6845120223754645e-11, 00.000000000, 0.013594402092441192, 0.5119418768961913, -0.9571200316970434, -0.9095434400348369, 00.000000000, 0.4474430201629445, -0.05667327928869355, -0.07326226743125924),
vector_utils::make_vector(-0.7475809368920289, 00.000000000, -3.781128710004096, 11.66107199740856, -2.1254722731357547, -4.019029640104203e-10, 15.246462442197771, -18.048166285757972, 8.37603666503838, 12.006109837717329, 3.470376456985657, 1.121351440643303, 3.980486576118014, -2.8770605647188794, 0.6644561949367181, -0.07032697207803783),
vector_utils::make_vector(-0.03739789399178936, -0.944159163796027, -0.3017085222427726, 00.000000000, -0.06359569943611086, 00.000000000, 0.38139891617017474, 00.000000000, 00.000000000, 9.832908543176506e-13, 00.000000000, 00.000000000, 00.000000000, -1.2155089757457618, -0.22522194899955364, -0.9356821071921098),
vector_utils::make_vector(00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000));
const std::vector< std::vector<double> > backbone_distances_data_PRO = vector_utils::make_vector(
vector_utils::make_vector(0.029778246799008194, 00.000000000, -0.019426074077176978, 00.000000000, -0.21395261150083003, 00.000000000, 00.000000000, 00.000000000, -1.8801788463747944e-12, 00.000000000, 0.04660542550394054, 00.000000000, 0.20799508398644603, 0.027182338394192495, 0.03319146178253968, 0.11439575857380795),
vector_utils::make_vector(-0.30848010984531415, 0.8047904559494001, -2.0300362133645518, 1.322273879181291, -0.7680868996344696, 00.000000000, 00.000000000, 8.84516624947276e-11, 7.724755040630422, 1.79331128214807, 7.903990757611555, 3.907903162879867, 1.181901936658844, 0.7888303756384959, 0.05881553902472262, 0.5778966638783823),
vector_utils::make_vector(00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000),
vector_utils::make_vector(00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000, 00.000000000),
vector_utils::make_vector(0.05702032123333377, 0.4554951513452361, -0.3650702372708477, 00.000000000, 0.02102645769671279, 00.000000000, 00.000000000, 00.000000000, 00.000000000, -2.1626856169656322e-11, 00.000000000, 00.000000000, 00.000000000, -1.1011533255796955, -0.18369457999328184, -0.860993004604592),
vector_utils::make_vector(-0.24836452024646163, -1.6788780426299816, 0.23735974523480674, -0.47739408747956574, 1.123212364506351, 1.6993985071893223, 00.000000000, 00.000000000, 1.1821666485851137, -4.7668417181918645, 0.9686944837631483, 0.491031472934839, 1.265528030390079, -2.265116669883977, 0.13347911544135715, 0.0968466579437965));
//FLATBTM -- OK!
const std::vector< std::vector<double> > flat_bottom_limit = vector_utils::make_vector(vector_utils::make_vector(0.2732537, 1.1511320, 0.5061659, 2.8999911, 1.2745616, 1.3020818),
vector_utils::make_vector(0.2903572, 1.1457984, 0.5156310, 2.9764442, 1.2908505, 0.0000000),
vector_utils::make_vector(0.2768943, 1.1454787, 0.0000000, 0.0000000, 1.2770539, 1.2910034));
//SCALEHARM -- OK!
const std::vector<double> scale_harmonic_potential = vector_utils::make_vector(0.47, 2.36, 0.62, 4.18, 1.95, 1.91);
//ENDHARM -- OK!
const std::vector<double> end_harmonic_potential = vector_utils::make_vector(4.0, 20.0, 4.0, 20.0, 20.0, 20.0);
}// End namespace camshift_constants
#endif
| [
"[email protected]"
] | |
6722890b06858a27111dcbfceb13054209c31651 | de1b6f42bc9d7b3546ffc0812f113bbdcdbad606 | /TEALDemo/Centipede_Body.cpp | 04b2bd73e558b38bbcaa20a8c64b019456bc0b4c | [] | no_license | Cschnur/Centipede_1980 | e298d4b549498d39ef77abbb69a7a3afa3332271 | d69a4031a7b6b4f88744c5c46b82b91cdec2d35e | refs/heads/master | 2022-03-20T15:01:33.376364 | 2019-12-09T23:36:24 | 2019-12-09T23:36:24 | 226,973,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,629 | cpp | #include "Centipede_Body.h"
#include "Centipede_Head.h"
#include "MushroomManager.h"
#include "MoveState.h"
#include "MoveFSM.h"
#include "MovementCollection.h"
#include "Centipede_Factory.h"
#include "Explosion_Factory.h"
#include "Centipede_Manager.h"
#include "OffsetArray.h"
#include "Color_Manager.h"
Centipede_Body::Centipede_Body()
:active(false)
{
bitmap = ResourceManager::GetTextureBitmap("Master");
colliderSprite = AnimatedSprite(ResourceManager::GetTexture("Master"), 28, 77, (16));
colliderSprite.SetAnimation(70, 73, true, false);
colliderSprite.setOrigin(colliderSprite.getTextureRect().width / (float)2, colliderSprite.getTextureRect().height / (float)2);
colliderSprite.setScale(2, 2);
MainSprite = Color_Manager::ReturnBody();
SetDrawOrder(1000);
SetCollider(colliderSprite, bitmap, true);
}
void Centipede_Body::Initialize(sf::Vector2i start, void *prevSeg, bool hd, int ispeed)
{
Pos = start;
rot = 0;
speed = ispeed;
count = 0;
gridPos = MushroomManager::GridConverter(Pos.x, Pos.y);
RegisterCollision<Centipede_Body>(*this);
active = false;
headless = false;
if (hd) // if you are the first body segment
{
head = (Centipede_Head *)prevSeg;
prev = nullptr;
first = true;
}
else //you are not the first body segment
{
first = false;
head = nullptr;
prev = (Centipede_Body *)prevSeg;
}
next = nullptr;
Centipede_Manager::reportSpawn();
pCurrentState = &MoveFSM::StateTurnDownSwitchToRight;
}
//Returns a pointer to the next segment
Centipede_Body* Centipede_Body::getNext()
{
if (next) return next;
return nullptr;
}
//Return a pointer to the previous segment...only bodies
Centipede_Body* Centipede_Body::getPrev()
{
if (prev) return prev;
return nullptr;
}
//Sets the pointer to the next segment
void Centipede_Body::SetNext(Centipede_Body *nextSeg)
{
next = nextSeg;
}
//Sets the head pointer if you are the first body
void Centipede_Body::SetHead(Centipede_Head *hptr)
{
prev = nullptr;
head = hptr;
}
//Returns the current row position
int Centipede_Body::getRow()
{
return gridPos.x;
}
void Centipede_Body::Update()
{
//if (active) MainSprite.Update();
if (count != 0)
{
//update x, y, and rotation values
Pos.x += speed * (pCurrentState->GetMoveOffsets()->xMove);
Pos.y += speed * (pCurrentState->GetMoveOffsets()->yMove);
//--//
rot += (speed * (pCurrentState->GetMoveOffsets()->rot));
//--//
count--;
}
else if (headless) //when a move is finished then transition into a head, if head is gone
{
if(next) next->MovementUpdate(pCurrentState);
BecomeHead();
}
}
//Pass your last movement to the next segment, then start your new movement
void Centipede_Body::MovementUpdate(const MoveState* state)
{
//active bool keeps the segments from all startign at once
if (next && active) next->MovementUpdate(pCurrentState);
pCurrentState = state;
count = conCount / speed;
active = true;
}
//Set the neccesary values to become a head, wait until current move is finished
void Centipede_Body::HeadDeath()
{
headless = true;
gridPos = MushroomManager::GridConverter(Pos.x, Pos.y);
}
void Centipede_Body::BecomeHead()
{
//Sets the start rotation of a new head, 0 = left, 180 = right
float tmp = 0.0f;
if (pCurrentState->GetMoveOffsets()->xMove > 0) tmp = 180.0f;
pCurrentState = pCurrentState->BreakState(this);
Centipede_Head *h = Centipede_Factory::CreateCentipede_Head(Pos, pCurrentState, next, 0, tmp, speed);
Centipede_Manager::reportSplit(h);
if (next)
{
next->SetHead(h);
next->nowFirst();
}
MarkForDestroy();
}
//This will be called if the body in front of you becomes a head
void Centipede_Body::nowFirst()
{
first = true;
}
void Centipede_Body::Death()
{
if (first)
{
head->SetNext();
}
else prev->SetNext(nullptr);
if (next) next->HeadDeath();
Explosion_Factory::CreateCritterExplosion(Pos);
gridPos = MushroomManager::GridConverter(Pos.x, Pos.y);
gridPos.y += pCurrentState->GetMoveOffsets()->rowOffset;
MushroomManager::MushroomSpawn(gridPos);
Centipede_Manager::reportDeath();
Centipede_Factory::ReportCentipedeBodyDeath(); //scoring
MarkForDestroy();
}
void Centipede_Body::Draw()
{
MainSprite->setRotation(rot);
MainSprite->setPosition(sf::Vector2f(Pos));
colliderSprite.setRotation(rot);
colliderSprite.setPosition(sf::Vector2f(Pos));
WindowManager::MainWindow.draw(*MainSprite);
}
void Centipede_Body::Destroy()
{
DeregisterCollision<Centipede_Body>(*this);
}
void Centipede_Body::Delete()
{
if (next) next->Delete();
Centipede_Manager::reportDelete();
DeregisterCollision<Centipede_Body>(*this);
MarkForDestroy();
}
Centipede_Body::~Centipede_Body()
{
}
| [
"[email protected]"
] | |
39306f7537017380e4980070b1f8337a56e71ad5 | e5720f95696653b496e5f927eac7492bfb9f132c | /lcof/lcof_028/cpp_028/Solution1.h | bf852d98db860feb7f8c1d58bb19a161cbc90973 | [
"MIT"
] | permissive | ooooo-youwillsee/leetcode | 818cca3dd1fd07caf186ab6d41fb8c44f6cc9bdc | 2cabb7e3e2465e33e4c96f0ad363cf6ce6976288 | refs/heads/master | 2022-05-24T15:37:19.652999 | 2022-05-15T01:25:31 | 2022-05-15T01:25:31 | 218,205,693 | 12 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | h | //
// Created by ooooo on 2020/3/18.
//
#ifndef CPP_028__SOLUTION1_H_
#define CPP_028__SOLUTION1_H_
#include "TreeNode.h"
class Solution {
public:
bool dfs(TreeNode *node1, TreeNode *node2) {
if (!node1 && !node2) return true;
if (!node1 || !node2) return false;
return node1->val == node2->val == dfs(node1->left, node2->right) && dfs(node1->right, node2->left);
}
bool isSymmetric(TreeNode *root) {
return dfs(root, root);
}
};
#endif //CPP_028__SOLUTION1_H_
| [
"[email protected]"
] | |
e1dca7d6419fe532e5ea2a68b8c3f553df60940d | 12594acbade434c379b1d8ef47977bf86999ad21 | /Codigo/inc/App/MPU9250.h | 2fdc7ac5e201866f372673d61b6df3ffb76d2920 | [] | no_license | AlejoLovallo/Gimbal | 8671bd117d3b36fe0f3877b8ea6bb2c589ba8778 | b1a9053b4773d31fe5ef18c93e5500f2c85004b7 | refs/heads/master | 2022-11-19T23:28:22.034662 | 2020-07-20T02:43:24 | 2020-07-20T02:43:24 | 198,079,218 | 0 | 1 | null | 2019-07-21T22:42:19 | 2019-07-21T16:21:53 | null | UTF-8 | C++ | false | false | 11,274 | h | #ifndef MPU9250_H
#define MPU9250_H
#include "all.h"
// See also MPU-9250 Register Map and Descriptions, Revision 4.0, RM-MPU-9250A-00, Rev. 1.4, 9/9/2013 for registers not listed in
// above document; the MPU9250 and MPU9150 are virtually identical but the latter has a different register map
//
//Magnetometer Registers
#define AK8963_ADDRESS 0x0C //<< 1
#define AK8963_WHO_AM_I 0x00 // should return 0x48
#define AK8963_INFO 0x01
#define AK8963_ST1 0x02 // data ready status bit 0
#define AK8963_XOUT_L 0x03 // data
#define AK8963_XOUT_H 0x04
#define AK8963_YOUT_L 0x05
#define AK8963_YOUT_H 0x06
#define AK8963_ZOUT_L 0x07
#define AK8963_ZOUT_H 0x08
#define AK8963_ST2 0x09 // Data overflow bit 3 and data read error status bit 2
#define AK8963_CNTL 0x0A // Power down (0000), single-measurement (0001), self-test (1000) and Fuse ROM (1111) modes on bits 3:0
#define AK8963_ASTC 0x0C // Self test control
#define AK8963_I2CDIS 0x0F // I2C disable
#define AK8963_ASAX 0x10 // Fuse ROM x-axis sensitivity adjustment value
#define AK8963_ASAY 0x11 // Fuse ROM y-axis sensitivity adjustment value
#define AK8963_ASAZ 0x12 // Fuse ROM z-axis sensitivity adjustment value
#define SELF_TEST_X_GYRO 0x00
#define SELF_TEST_Y_GYRO 0x01
#define SELF_TEST_Z_GYRO 0x02
/*#define X_FINE_GAIN 0x03 // [7:0] fine gain
#define Y_FINE_GAIN 0x04
#define Z_FINE_GAIN 0x05
#define XA_OFFSET_H 0x06 // User-defined trim values for accelerometer
#define XA_OFFSET_L_TC 0x07
#define YA_OFFSET_H 0x08
#define YA_OFFSET_L_TC 0x09
#define ZA_OFFSET_H 0x0A
#define ZA_OFFSET_L_TC 0x0B */
#define SELF_TEST_X_ACCEL 0x0D
#define SELF_TEST_Y_ACCEL 0x0E
#define SELF_TEST_Z_ACCEL 0x0F
#define SELF_TEST_A 0x10
#define XG_OFFSET_H 0x13 // User-defined trim values for gyroscope
#define XG_OFFSET_L 0x14
#define YG_OFFSET_H 0x15
#define YG_OFFSET_L 0x16
#define ZG_OFFSET_H 0x17
#define ZG_OFFSET_L 0x18
#define SMPLRT_DIV 0x19
#define CONFIG 0x1A
#define GYRO_CONFIG 0x1B
#define ACCEL_CONFIG 0x1C
#define ACCEL_CONFIG2 0x1D
#define LP_ACCEL_ODR 0x1E
#define WOM_THR 0x1F
#define MOT_DUR 0x20 // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
#define ZMOT_THR 0x21 // Zero-motion detection threshold bits [7:0]
#define ZRMOT_DUR 0x22 // Duration counter threshold for zero motion interrupt generation, 16 Hz rate, LSB = 64 ms
#define FIFO_EN 0x23
#define I2C_MST_CTRL 0x24
#define I2C_SLV0_ADDR 0x25
#define I2C_SLV0_REG 0x26
#define I2C_SLV0_CTRL 0x27
#define I2C_SLV1_ADDR 0x28
#define I2C_SLV1_REG 0x29
#define I2C_SLV1_CTRL 0x2A
#define I2C_SLV2_ADDR 0x2B
#define I2C_SLV2_REG 0x2C
#define I2C_SLV2_CTRL 0x2D
#define I2C_SLV3_ADDR 0x2E
#define I2C_SLV3_REG 0x2F
#define I2C_SLV3_CTRL 0x30
#define I2C_SLV4_ADDR 0x31
#define I2C_SLV4_REG 0x32
#define I2C_SLV4_DO 0x33
#define I2C_SLV4_CTRL 0x34
#define I2C_SLV4_DI 0x35
#define I2C_MST_STATUS 0x36
#define INT_PIN_CFG 0x37
#define INT_ENABLE 0x38
#define DMP_INT_STATUS 0x39 // Check DMP interrupt
#define INT_STATUS 0x3A
#define ACCEL_XOUT_H 0x3B
#define ACCEL_XOUT_L 0x3C
#define ACCEL_YOUT_H 0x3D
#define ACCEL_YOUT_L 0x3E
#define ACCEL_ZOUT_H 0x3F
#define ACCEL_ZOUT_L 0x40
#define TEMP_OUT_H 0x41
#define TEMP_OUT_L 0x42
#define GYRO_XOUT_H 0x43
#define GYRO_XOUT_L 0x44
#define GYRO_YOUT_H 0x45
#define GYRO_YOUT_L 0x46
#define GYRO_ZOUT_H 0x47
#define GYRO_ZOUT_L 0x48
#define EXT_SENS_DATA_00 0x49
#define EXT_SENS_DATA_01 0x4A
#define EXT_SENS_DATA_02 0x4B
#define EXT_SENS_DATA_03 0x4C
#define EXT_SENS_DATA_04 0x4D
#define EXT_SENS_DATA_05 0x4E
#define EXT_SENS_DATA_06 0x4F
#define EXT_SENS_DATA_07 0x50
#define EXT_SENS_DATA_08 0x51
#define EXT_SENS_DATA_09 0x52
#define EXT_SENS_DATA_10 0x53
#define EXT_SENS_DATA_11 0x54
#define EXT_SENS_DATA_12 0x55
#define EXT_SENS_DATA_13 0x56
#define EXT_SENS_DATA_14 0x57
#define EXT_SENS_DATA_15 0x58
#define EXT_SENS_DATA_16 0x59
#define EXT_SENS_DATA_17 0x5A
#define EXT_SENS_DATA_18 0x5B
#define EXT_SENS_DATA_19 0x5C
#define EXT_SENS_DATA_20 0x5D
#define EXT_SENS_DATA_21 0x5E
#define EXT_SENS_DATA_22 0x5F
#define EXT_SENS_DATA_23 0x60
#define MOT_DETECT_STATUS 0x61
#define I2C_SLV0_DO 0x63
#define I2C_SLV1_DO 0x64
#define I2C_SLV2_DO 0x65
#define I2C_SLV3_DO 0x66
#define I2C_MST_DELAY_CTRL 0x67
#define SIGNAL_PATH_RESET 0x68
#define MOT_DETECT_CTRL 0x69
#define USER_CTRL 0x6A // Bit 7 enable DMP, bit 3 reset DMP
#define PWR_MGMT_1 0x6B // Device defaults to the SLEEP mode
#define PWR_MGMT_2 0x6C
#define DMP_BANK 0x6D // Activates a specific bank in the DMP
#define DMP_RW_PNT 0x6E // Set read/write pointer to a specific start address in specified DMP bank
#define DMP_REG 0x6F // Register in DMP from which to read or to which to write
#define DMP_REG_1 0x70
#define DMP_REG_2 0x71
#define FIFO_COUNTH 0x72
#define FIFO_COUNTL 0x73
#define FIFO_R_W 0x74
#define WHO_AM_I_MPU9250 0x75 // Should return 0x71
#define XA_OFFSET_H 0x77
#define XA_OFFSET_L 0x78
#define YA_OFFSET_H 0x7A
#define YA_OFFSET_L 0x7B
#define ZA_OFFSET_H 0x7D
#define ZA_OFFSET_L 0x7E
// Using the MSENSR-9250 breakout board, ADO is set to 0
// Seven-bit device address is 110100 for ADO = 0 and 110101 for ADO = 1
//mbed uses the eight-bit device address, so shift seven-bit addresses left by one!
#define ADO 0
#if ADO
#define MPU9250_ADDRESS 0x69 // Device address when ADO = 1
#else
#define MPU9250_ADDRESS 0x68 // Device address when ADO = 0
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct MPU9250_params_t
{
// I2C_HandleTypeDef hi2c; // I2C connected to MPU9250, eq, hi2c1.
uint8_t accel_scale; // AFS_2G, AFS_4G, AFS_8G, AFS_16G
uint8_t gyro_scale; // GFS_250DPS, GFS_500DPS, GFS_1000DPS, GFS_2000DPS
uint8_t mag_scale; // MFS_14BITS or MFS_16BITS, 14-bit or 16-bit magnetometer resolution
uint8_t mag_mode; // Either 8 Hz 0x02) or 100 Hz (0x06) magnetometer data ODR
// scale resolutions per LSB for the sensors
float accel_res;
float gyro_res;
float mag_res;
float deltat; // integration interval for both filter schemes
float q[4]; // vector to hold quaternion
float e_int[3]; // vector to hold integral error for Mahony method
float beta; // compute beta
} MPU9250_params;
typedef struct accel_data_t
{
float x;
float y;
float z;
} accel_data;
typedef struct gyro_data_t
{
float x;
float y;
float z;
} gyro_data;
typedef struct mag_data_t
{
float x;
float y;
float z;
} mag_data;
typedef struct MPU9250_data_t
{
accel_data accel;
gyro_data gyro;
mag_data mag;
float temp;
float q[4];
} MPU9250_data;
typedef struct EulerAngles_t {
float roll, pitch, yaw;
}EulerAngles;
#ifdef __cplusplus
}
#endif
#define Kp 2.0f * 5.0f // these are the free parameters in the Mahony filter and fusion scheme, Kp for proportional feedback, Ki for integral
#define Ki 0.0f
#define GRAVITY -9.81f //Valor de la gravedad (modulo)
#define PI 3.14159265358979323846f
#ifdef __cplusplus
class c_MPU9250
{
private:
//Agregados cosa de que quede mas prolijo respecto a codigo original-----------------------------------
float m_accel_bias[3];
uint8_t m_accel_scale; // AFS_2G, AFS_4G, AFS_8G, AFS_16G
float m_beta; // compute beta
float m_deltat; // integration interval for both filter schemes
float m_e_int[3]; // vector to hold integral error for Mahony method
uint8_t m_gyro_scale; // GFS_250DPS, GFS_500DPS, GFS_1000DPS, GFS_2000DPS
float m_mag_bias[3];
float m_mag_calibration[3]; // Factory mag calibration
uint8_t m_mag_mode; // Either 8 Hz 0x02) or 100 Hz (0x06) magnetometer data ODR
uint8_t m_mag_scale; // MFS_14BITS or MFS_16BITS, 14-bit or 16-bit magnetometer resolution
float m_q[4]; // Estos son los cuaterniones donde se guarda el valor actual del Giroscopo
EulerAngles angulos; // Estos son los angulos de Euler
uint8_t f_get_mag_mode(uint8_t);
void f_init_ak8963(void);
void f_init_mpu9250(void);
// Accelerometer and gyroscope self test; check calibration wrt factory settings
void f_mpu9250_self_test(float * destination); // Should return percent deviation from factory trim values, +/- 14 or less deviation is a pass
void f_reset_mpu9250(void);
public:
// Set initial input parameters
float m_gyro_bias[3];
enum E_ACC_SCALE : uint8_t
{
AFS_2G = 0,
AFS_4G,
AFS_8G,
AFS_16G
};
enum E_GYRO_SCALE : uint8_t
{
GFS_250DPS = 0,
GFS_500DPS,
GFS_1000DPS,
GFS_2000DPS
};
enum E_MAG_SCALE : uint8_t
{
MFS_14BITS = 0, // 0.6 mG per LSB
MFS_16BITS // 0.15 mG per LSB
};
enum E_MAG_HZ : uint8_t
{
MFREQ_8HZ = 0x2, // 8Hz Magnetometer data ODR
MFREQ_100HZ = 0x6 // 100Hz Magnetometer data ODR
};
c_MPU9250();
~c_MPU9250();
// Check for IMU status and initializes both chips
bool init(void);
void f_read_bytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest);
void f_write_byte(uint8_t address, uint8_t subAddress, uint8_t data);
uint8_t f_read_byte(uint8_t address, uint8_t subAddress);
float f_get_accel_res();
float f_get_gyro_res();
float f_get_mag_res();
// Implementation of Sebastian Madgwick's "...efficient orientation filter for... inertial/magnetic sensor arrays"
// (see http://www.x-io.co.uk/category/open-source/ for examples and more details)
// which fuses acceleration, rotation rate, and magnetic moments to produce a quaternion-based estimate of absolute
// device orientation -- which can be converted to yaw, pitch, and roll. Useful for stabilizing quadcopters, etc.
// The performance of the orientation filter is at least as good as conventional Kalman-based filtering algorithms
// but is much less computationally intensive---it can be performed on a 3.3 V Pro Mini operating at 8 MHz!
void madgwick_quaternion_update(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz, float deltat);
// Similar to Madgwick scheme but uses proportional and integral filtering on the error between estimated reference vectors and
// measured ones.
void mahony_quaternion_update(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz, float deltat);
void ToEulerAngles(void);
// Function which accumulates gyro and accelerometer data after device initialization. It calculates the average
// of the at-rest readings and then loads the resulting offsets into accelerometer and gyro bias registers.
void f_calibrate_mpu9250(void);
EulerAngles getAngles(void);
void read_accel_data(accel_data &);
void read_gyro_data(gyro_data &);
void read_mag_data(mag_data &);
void read_temp_data(float &);
};
#endif
#endif
| [
"[email protected]"
] | |
e140ff075846f75c8d140649d16f692268be310c | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/media/audio/audio_manager_base.h | 8b34d9fcf94bd9e5b8a08b6b853c2b25cee37c10 | [
"BSD-3-Clause"
] | permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,995 | h | // 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.
#ifndef MEDIA_AUDIO_AUDIO_MANAGER_BASE_H_
#define MEDIA_AUDIO_AUDIO_MANAGER_BASE_H_
#include <string>
#include <utility>
#include "base/compiler_specific.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/observer_list.h"
#include "base/synchronization/lock.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_output_dispatcher.h"
#if defined(OS_WIN)
#include "base/win/scoped_com_initializer.h"
#endif
namespace base {
class Thread;
}
namespace media {
class AudioOutputDispatcher;
// AudioManagerBase provides AudioManager functions common for all platforms.
class MEDIA_EXPORT AudioManagerBase : public AudioManager {
public:
// Name of the generic "default" device.
static const char kDefaultDeviceName[];
// Unique Id of the generic "default" device.
static const char kDefaultDeviceId[];
virtual ~AudioManagerBase();
virtual scoped_refptr<base::MessageLoopProxy> GetMessageLoop() OVERRIDE;
virtual scoped_refptr<base::MessageLoopProxy> GetWorkerLoop() OVERRIDE;
virtual string16 GetAudioInputDeviceModel() OVERRIDE;
virtual void ShowAudioInputSettings() OVERRIDE;
virtual void GetAudioInputDeviceNames(
media::AudioDeviceNames* device_names) OVERRIDE;
virtual AudioOutputStream* MakeAudioOutputStream(
const AudioParameters& params,
const std::string& input_device_id) OVERRIDE;
virtual AudioInputStream* MakeAudioInputStream(
const AudioParameters& params, const std::string& device_id) OVERRIDE;
virtual AudioOutputStream* MakeAudioOutputStreamProxy(
const AudioParameters& params,
const std::string& input_device_id) OVERRIDE;
// Called internally by the audio stream when it has been closed.
virtual void ReleaseOutputStream(AudioOutputStream* stream);
virtual void ReleaseInputStream(AudioInputStream* stream);
// Creates the output stream for the |AUDIO_PCM_LINEAR| format. The legacy
// name is also from |AUDIO_PCM_LINEAR|.
virtual AudioOutputStream* MakeLinearOutputStream(
const AudioParameters& params) = 0;
// Creates the output stream for the |AUDIO_PCM_LOW_LATENCY| format.
// |input_device_id| is used by unified IO to open the correct input device.
virtual AudioOutputStream* MakeLowLatencyOutputStream(
const AudioParameters& params, const std::string& input_device_id) = 0;
// Creates the input stream for the |AUDIO_PCM_LINEAR| format. The legacy
// name is also from |AUDIO_PCM_LINEAR|.
virtual AudioInputStream* MakeLinearInputStream(
const AudioParameters& params, const std::string& device_id) = 0;
// Creates the input stream for the |AUDIO_PCM_LOW_LATENCY| format.
virtual AudioInputStream* MakeLowLatencyInputStream(
const AudioParameters& params, const std::string& device_id) = 0;
// Listeners will be notified on the AudioManager::GetMessageLoop() loop.
virtual void AddOutputDeviceChangeListener(
AudioDeviceListener* listener) OVERRIDE;
virtual void RemoveOutputDeviceChangeListener(
AudioDeviceListener* listener) OVERRIDE;
virtual AudioParameters GetDefaultOutputStreamParameters() OVERRIDE;
virtual AudioParameters GetInputStreamParameters(
const std::string& device_id) OVERRIDE;
protected:
AudioManagerBase();
// Shuts down the audio thread and releases all the audio output dispatchers
// on the audio thread. All audio streams should be freed before Shutdown()
// is called. This must be called in the destructor of every AudioManagerBase
// implementation.
void Shutdown();
void SetMaxOutputStreamsAllowed(int max) { max_num_output_streams_ = max; }
// Called by each platform specific AudioManager to notify output state change
// listeners that a state change has occurred. Must be called from the audio
// thread.
void NotifyAllOutputDeviceChangeListeners();
// Returns the preferred hardware audio output parameters for opening output
// streams. If the users inject a valid |input_params|, each AudioManager
// will decide if they should return the values from |input_params| or the
// default hardware values. If the |input_params| is invalid, it will return
// the default hardware audio parameters.
virtual AudioParameters GetPreferredOutputStreamParameters(
const AudioParameters& input_params) = 0;
// Get number of input or output streams.
int input_stream_count() { return num_input_streams_; }
int output_stream_count() { return num_output_streams_; }
private:
struct DispatcherParams;
typedef ScopedVector<DispatcherParams> AudioOutputDispatchers;
class CompareByParams;
// Called by Shutdown().
void ShutdownOnAudioThread();
// Max number of open output streams, modified by
// SetMaxOutputStreamsAllowed().
int max_num_output_streams_;
// Max number of open input streams.
int max_num_input_streams_;
// Number of currently open output streams.
int num_output_streams_;
// Number of currently open input streams.
int num_input_streams_;
// Track output state change listeners.
ObserverList<AudioDeviceListener> output_listeners_;
// Thread used to interact with audio streams created by this audio manager.
scoped_ptr<base::Thread> audio_thread_;
mutable base::Lock audio_thread_lock_;
// The message loop of the audio thread this object runs on. Used for internal
// tasks which run on the audio thread even after Shutdown() has been started
// and GetMessageLoop() starts returning NULL.
scoped_refptr<base::MessageLoopProxy> message_loop_;
// Map of cached AudioOutputDispatcher instances. Must only be touched
// from the audio thread (no locking).
AudioOutputDispatchers output_dispatchers_;
DISALLOW_COPY_AND_ASSIGN(AudioManagerBase);
};
} // namespace media
#endif // MEDIA_AUDIO_AUDIO_MANAGER_BASE_H_
| [
"[email protected]"
] | |
127ee2e48da3fbcbbdf324feaa19be6417b6d2a9 | 5a44ac1d396160dc12dbf33f05847383917d32bd | /Step1/Step1/Animal.h | b6fba7f7b644c2fef136d25f3fe0a28e5dcd6b83 | [] | no_license | lechris1/cse335Steps | ad60597bfc99f63ba409488c7df6b15b6941904f | 2ffda274f66b9cd35083f10ee2f159ac42ee10f2 | refs/heads/master | 2021-01-22T06:45:04.349492 | 2017-09-06T19:40:58 | 2017-09-06T19:40:58 | 102,297,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | h | /**
* \file Animal.h
*
* \author Christopher Le
*
* Class that describes an animal.
*/
#pragma once
/**
* Describes a single animal.
*/
class CAnimal
{
public:
CAnimal();
virtual ~CAnimal();
/** Display an animal. */
virtual void DisplayAnimal() {};
virtual int NumEyes();
};
| [
"[email protected]"
] | |
df4bd65b9d12d49b27f6f5de370ca6f4f382df8f | 888afc08ee61d96591fab755158179ae0cb9ea6e | /src/model/stick2d.h | 8aedb987e4718fa3b21570833ee25054ce9230ca | [
"MIT"
] | permissive | JeffGos/hawkings | 4c90ed9ff93f0e7d1b0d97b7f6f0781aa9caa97f | bb2dfb48b53a1b97f1b02fc2dd53fdc88f747bf3 | refs/heads/master | 2020-03-19T10:00:54.618770 | 2018-06-23T22:29:35 | 2018-06-23T22:29:35 | 133,155,122 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 453 | h | #ifndef STICK2D_H
#define STICK2D_H
#include "point2d.h"
using namespace std;
namespace hawkings {
class Stick2D {
public:
Stick2D(Point2D vect1, Point2D vect2, int magnitude);
void setMagnitude(int m);
Point2D getX() { return this->point1; }
Point2D getY() { return this->point2; }
int getMagnitude() { return this->magnitude; }
protected:
Point2D point1;
Point2D point2;
int magnitude;
private:
};
}
#endif | [
"[email protected]"
] | |
56d9b0429a16de8edf76fca07cf784be7552eba2 | 17066d4b72c4b3f87a058b42763ebcd232fbed72 | /src/public/pool/chunk.cpp | 1adc7db45ee84ae0f9d2a0cd869fde6acb161526 | [] | no_license | yulefox/elf_iocp | 4ef34f10e0201358315aad27256e5c2316efc620 | 2d3faf87b7f9eff4ac60a132ddaa7c8f9e4bbd41 | refs/heads/master | 2021-01-02T22:45:32.470948 | 2012-02-17T08:54:53 | 2012-02-17T08:54:53 | 3,404,790 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,309 | cpp | #include "chunk.h"
#include <assert.h>
#include <Winsock2.h>
#include "pool.h"
#define CHUNK_INIT_SIZE 64
struct chunk_t {
size_t count; /* bulb count */
size_t pos_wr; /* pointer to writen position of bulb_wr */
size_t pos_rd; /* pointer to read position of bulb_rd */
struct bulb_t *head; /* pointer to head bulb */
struct bulb_t *bulb_wr; /* pointer to current writen bulb */
struct bulb_t *bulb_rd; /* pointer to current read bulb */
};
/* 与 WSABUF 兼容 */
struct bulb_t {
size_t size; /* WSABUFF 此为 u_long 类型 */
void *buf;
struct bulb_t *prev; /* previous of the head is a tail */
struct bulb_t *next;
};
/** return pointer to the new bulb */
static struct bulb_t *chunk_bulb_alloc(struct bulb_t *b, size_t init_size);
static void chunk_bulb_free(struct bulb_t *b);
struct chunk_t *
chunk_create(size_t init_size)
{
struct chunk_t *c;
c = (struct chunk_t *)pool_alloc(sizeof(*c));
c->pos_wr = c->pos_rd = 0;
c->count = 1;
c->head = c->bulb_wr = c->bulb_rd =
chunk_bulb_alloc(NULL, init_size ? init_size : CHUNK_INIT_SIZE);
return c;
}
void
chunk_destroy(struct chunk_t *c)
{
struct bulb_t *b, *p;
assert(c);
b = c->head;
while (b != NULL) {
p = b;
b = b->next;
chunk_bulb_free(p);
}
pool_free(c);
}
int
chunk_append(struct chunk_t *c, void *buf, size_t size)
{
register struct bulb_t *cb; /* curent writen bulb */
register size_t cp, cr, cw; /* curent position, remain size, writen size */
register size_t rem; /* remain size */
assert(c && buf);
cb = c->bulb_wr;
cp = c->pos_wr;
cr = cb->size - cp;
rem = size;
cw = min(cr, rem);
memcpy((char *)(cb->buf) + cp, buf, cw);
if (cr >= rem) { /* enough */
c->pos_wr += cw;
} else {
while ((rem -= cw) > 0) {
buf = (char *)buf + cw;
cb = chunk_bulb_alloc(cb, 0);
++(c->count);
cr = cb->size;
cw = min(cr, rem);
memcpy(cb->buf, buf, cw);
}
c->pos_wr = cw;
c->bulb_wr = cb;
}
return 0;
}
int
chunk_retrive(struct chunk_t *c, void *buf, size_t size)
{
register struct bulb_t *cb; /* curent read bulb */
register size_t cp, cr, cd; /* curent position, remain size, read size */
register size_t rem; /* remain size */
assert(c && buf);
cb = c->bulb_rd;
if (cb == NULL) return -1;
cp = c->pos_rd;
cr = cb->size - cp;
rem = size;
cd = min(cr, rem);
memcpy(buf, (char *)(cb->buf) + cp, cd);
if (cr > rem) { /* enough */
c->pos_rd += cd;
} else {
while ((rem -= cd) > 0) {
buf = (char *)buf + cd;
cb = cb->next;
if (cb == NULL) return -1;
cr = cb->size;
cd = min(cr, rem);
memcpy(buf, cb->buf, cd);
}
c->pos_rd = cd;
c->bulb_rd = cb;
}
return 0;
}
int
chunk_set(struct chunk_t *c, void *buf, size_t size)
{
register struct bulb_t *cb;
assert(c && buf);
cb = c->head;
assert(size < cb->size);
memcpy(cb->buf, buf, size);
return 0;
}
int
chunk_get(struct chunk_t *c, void *buf, size_t size)
{
register struct bulb_t *cb;
assert(c && buf);
cb = c->head;
assert(size < cb->size);
memcpy(buf, cb->buf, size);
return 0;
}
int
chunk_buffers(struct chunk_t *c, struct _WSABUF **bufs, size_t *count)
{
size_t i = 0;
struct bulb_t *b;
assert(c);
b = c->head;
*count = c->count;
*bufs = (struct _WSABUF *)pool_alloc(sizeof(**bufs) * (*count));
while (b != NULL) {
((*bufs)[i]).buf = (char *)(b->buf);
((*bufs)[i]).len = (u_long)(b->size);
b = b->next;
++i;
}
((*bufs)[i - 1]).len = (u_long)(c->pos_wr);
return 0;
}
struct bulb_t *
chunk_bulb_alloc(struct bulb_t *b, size_t size)
{
struct bulb_t *n;
n = (struct bulb_t *)pool_alloc(sizeof(*n));
n->next = NULL;
if (b == NULL) {
n->size = size;
} else {
b->next = n;
n->size = b->size << 1;
}
n->prev = b;
n->buf = pool_alloc(n->size);
return n;
}
void
chunk_bulb_free(struct bulb_t *b)
{
assert(b);
pool_free(b->buf);
pool_free(b);
}
| [
"[email protected]"
] | |
6432cd6370ad3ea3f76a407b2ae51de0aee75450 | 743fd3facb10be5a847771b032881b6047d6dad4 | /thirdparty/general/GameNetworkingSockets-1.3.0/src/steamnetworkingsockets/clientlib/steamnetworkingsockets_connections.h | 981aa124c9bea8e341c5b05e2ed348faa2d321a1 | [
"BSD-3-Clause"
] | permissive | Xarvie/filesystem | 0c4661399eb4fee459ed9a8763fbc3af0172a8ec | d14586cbabbdedf5f8fcd32f5e66687e4d5e8e3b | refs/heads/master | 2023-06-13T05:52:31.642520 | 2021-07-06T16:14:57 | 2021-07-06T16:14:57 | 378,916,158 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43,700 | h | //====== Copyright Valve Corporation, All rights reserved. ====================
#ifndef STEAMNETWORKINGSOCKETS_CONNECTIONS_H
#define STEAMNETWORKINGSOCKETS_CONNECTIONS_H
#pragma once
#include "../steamnetworkingsockets_internal.h"
#ifndef STEAMNETWORKINGSOCKETS_OPENSOURCE
#include "../steamdatagram_internal.h"
#include <steam/steamdatagram_tickets.h>
#endif
#include "../steamnetworking_statsutils.h"
#include <tier1/utlhashmap.h>
#include "steamnetworkingsockets_lowlevel.h"
#include "../steamnetworkingsockets_thinker.h"
#include "keypair.h"
#include "crypto.h"
#include "crypto_25519.h"
#include <tier0/memdbgoff.h>
#include <steamnetworkingsockets_messages.pb.h>
#include <tier0/memdbgon.h>
#include "steamnetworkingsockets_snp.h"
struct SteamNetConnectionStatusChangedCallback_t;
class ISteamNetworkingSocketsSerialized;
class CGameNetworkingUI_ConnectionState;
namespace SteamNetworkingSocketsLib {
const SteamNetworkingMicroseconds k_usecConnectRetryInterval = k_nMillion/2;
const SteamNetworkingMicroseconds k_usecFinWaitTimeout = 5*k_nMillion;
typedef char ConnectionEndDebugMsg[ k_cchSteamNetworkingMaxConnectionCloseReason ];
typedef char ConnectionTypeDescription_t[64];
class CSteamNetworkingSockets;
class CSteamNetworkingMessages;
class CSteamNetworkConnectionBase;
class CSteamNetworkConnectionP2P;
class CSharedSocket;
class CConnectionTransport;
struct SNPAckSerializerHelper;
struct CertAuthScope;
enum EUnsignedCert
{
k_EUnsignedCert_Disallow,
k_EUnsignedCert_AllowWarn,
k_EUnsignedCert_Allow,
};
// Fixed size byte array that automatically wipes itself upon destruction.
// Used for storage of secret keys, etc.
template <int N>
class AutoWipeFixedSizeBuffer
{
public:
enum { k_nSize = N };
uint8 m_buf[ N ];
// You can wipe before destruction if you want
inline void Wipe() { SecureZeroMemory( m_buf, N ); }
// Wipe on destruction
inline ~AutoWipeFixedSizeBuffer() { Wipe(); }
};
/// In various places, we need a key in a map of remote connections.
struct RemoteConnectionKey_t
{
SteamNetworkingIdentity m_identity;
uint32 m_unConnectionID;
// NOTE: If we assume that peers are well behaved, then we
// could just use the connection ID, which is a random number.
// but let's not assume that. In fact, if we really need to
// protect against malicious clients we might have to include
// some random private data so that they don't know how our hash
// function works. We'll assume for now that this isn't a problem
struct Hash { uint32 operator()( const RemoteConnectionKey_t &x ) const { return SteamNetworkingIdentityHash{}( x.m_identity ) ^ x.m_unConnectionID; } };
inline bool operator ==( const RemoteConnectionKey_t &x ) const
{
return m_unConnectionID == x.m_unConnectionID && m_identity == x.m_identity;
}
};
/// Base class for connection-type-specific context structure
struct SendPacketContext_t
{
inline SendPacketContext_t( SteamNetworkingMicroseconds usecNow, const char *pszReason ) : m_usecNow( usecNow ), m_pszReason( pszReason ) {}
const SteamNetworkingMicroseconds m_usecNow;
int m_cbMaxEncryptedPayload;
const char *m_pszReason; // Why are we sending this packet?
};
/// Context used when receiving a data packet
struct RecvPacketContext_t
{
//
// Must be filled in by transport
//
/// Current time
SteamNetworkingMicroseconds m_usecNow;
/// What transport is receiving this packet?
CConnectionTransport *m_pTransport;
/// Jitter measurement, if present
//int m_usecTimeSinceLast;
//
// Output of DecryptDataChunk
//
/// Expanded packet number
int64 m_nPktNum;
/// Pointer to decrypted data. Will either point to to the caller's original packet,
/// if the packet was not encrypted, or m_decrypted, if it was encrypted and we
/// decrypted it
const void *m_pPlainText;
/// Size of plaintext
int m_cbPlainText;
// Temporary buffer to hold decrypted data, if we were actually encrypted
uint8 m_decrypted[ k_cbSteamNetworkingSocketsMaxPlaintextPayloadRecv ];
};
template<typename TStatsMsg>
struct SendPacketContext : SendPacketContext_t
{
inline SendPacketContext( SteamNetworkingMicroseconds usecNow, const char *pszReason ) : SendPacketContext_t( usecNow, pszReason ) {}
uint32 m_nFlags; // Message flags that we need to set.
TStatsMsg msg; // Type-specific stats message
int m_cbMsgSize; // Size of message
int m_cbTotalSize; // Size needed in the header, including the serialized size field
void SlamFlagsAndCalcSize()
{
SetStatsMsgFlagsIfNotImplied( msg, m_nFlags );
m_cbTotalSize = m_cbMsgSize = ProtoMsgByteSize( msg );
if ( m_cbMsgSize > 0 )
m_cbTotalSize += VarIntSerializedSize( (uint32)m_cbMsgSize );
}
bool Serialize( byte *&p )
{
if ( m_cbTotalSize <= 0 )
return false;
// Serialize the stats size, var-int encoded
byte *pOut = SerializeVarInt( p, uint32( m_cbMsgSize ) );
// Serialize the actual message
pOut = msg.SerializeWithCachedSizesToArray( pOut );
// Make sure we wrote the number of bytes we expected
if ( pOut != p + m_cbTotalSize )
{
// ABORT!
AssertMsg( false, "Size mismatch after serializing inline stats blob" );
return false;
}
// Advance pointer
p = pOut;
return true;
}
void CalcMaxEncryptedPayloadSize( size_t cbHdrReserve, CSteamNetworkConnectionBase *pConnection );
};
/// Replace internal states that are not visible outside of the API with
/// the corresponding state that we show the the application.
inline ESteamNetworkingConnectionState CollapseConnectionStateToAPIState( ESteamNetworkingConnectionState eState )
{
// All the hidden internal states are assigned negative values
if ( eState < 0 )
return k_ESteamNetworkingConnectionState_None;
return eState;
}
/// We use one global lock to protect all queues of
/// received messages. (On connections and poll groups!)
extern ShortDurationLock g_lockAllRecvMessageQueues;
/////////////////////////////////////////////////////////////////////////////
//
// CSteamNetworkPollGroup
//
/////////////////////////////////////////////////////////////////////////////
class CSteamNetworkPollGroup;
struct PollGroupLock : Lock<RecursiveTimedMutexImpl> {
PollGroupLock() : Lock<RecursiveTimedMutexImpl>( "pollgroup", LockDebugInfo::k_nFlag_PollGroup ) {}
};
using PollGroupScopeLock = ScopeLock<PollGroupLock>;
class CSteamNetworkPollGroup
{
public:
CSteamNetworkPollGroup( CSteamNetworkingSockets *pInterface );
~CSteamNetworkPollGroup();
PollGroupLock m_lock;
/// What interface is responsible for this listen socket?
CSteamNetworkingSockets *const m_pSteamNetworkingSocketsInterface;
/// Linked list of messages received through any connection on this listen socket
SteamNetworkingMessageQueue m_queueRecvMessages;
/// Index into the global list
HSteamNetPollGroup m_hPollGroupSelf;
/// List of connections that are in this poll group
CUtlVector<CSteamNetworkConnectionBase *> m_vecConnections;
void AssignHandleAndAddToGlobalTable();
};
/////////////////////////////////////////////////////////////////////////////
//
// CSteamNetworkListenSocketBase
//
/////////////////////////////////////////////////////////////////////////////
/// Abstract base class for a listen socket that can accept connections.
class CSteamNetworkListenSocketBase
{
public:
/// Destroy the listen socket, and all of its accepted connections
virtual void Destroy();
/// Called when we receive a connection attempt, to setup the linkage.
bool BAddChildConnection( CSteamNetworkConnectionBase *pConn, SteamNetworkingErrMsg &errMsg );
/// This gets called on an accepted connection before it gets destroyed
virtual void AboutToDestroyChildConnection( CSteamNetworkConnectionBase *pConn );
virtual bool APIGetAddress( SteamNetworkingIPAddr *pAddress );
/// Map of child connections
CUtlHashMap<RemoteConnectionKey_t, CSteamNetworkConnectionBase *, std::equal_to<RemoteConnectionKey_t>, RemoteConnectionKey_t::Hash > m_mapChildConnections;
/// Index into the global list
HSteamListenSocket m_hListenSocketSelf;
/// What interface is responsible for this listen socket?
CSteamNetworkingSockets *const m_pSteamNetworkingSocketsInterface;
/// Configuration options that will apply to all connections accepted through this listen socket
ConnectionConfig m_connectionConfig;
/// Symmetric mode
inline bool BSymmetricMode() const { return m_connectionConfig.m_SymmetricConnect.Get() != 0; }
virtual bool BSupportsSymmetricMode();
/// For legacy interface.
#ifdef STEAMNETWORKINGSOCKETS_STEAMCLIENT
std::unique_ptr<CSteamNetworkPollGroup> m_pLegacyPollGroup;
#endif
protected:
CSteamNetworkListenSocketBase( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface );
virtual ~CSteamNetworkListenSocketBase(); // hidden destructor, don't call directly. Use Destroy()
bool BInitListenSocketCommon( int nOptions, const SteamNetworkingConfigValue_t *pOptions, SteamDatagramErrMsg &errMsg );
};
/////////////////////////////////////////////////////////////////////////////
//
// CSteamNetworkConnectionBase
//
/////////////////////////////////////////////////////////////////////////////
struct ConnectionLock : Lock<RecursiveTimedMutexImpl> {
ConnectionLock() : Lock<RecursiveTimedMutexImpl>( "connection", LockDebugInfo::k_nFlag_Connection ) {}
};
struct ConnectionScopeLock : ScopeLock<ConnectionLock>
{
ConnectionScopeLock() = default;
ConnectionScopeLock( ConnectionLock &lock, const char *pszTag = nullptr ) : ScopeLock<ConnectionLock>( lock, pszTag ) {}
ConnectionScopeLock( CSteamNetworkConnectionBase &conn, const char *pszTag = nullptr );
void Lock( ConnectionLock &lock, const char *pszTag = nullptr ) { ScopeLock<ConnectionLock>::Lock( lock, pszTag ); }
void Lock( CSteamNetworkConnectionBase &conn, const char *pszTag = nullptr );
};
/// Abstract interface for a connection to a remote host over any underlying
/// transport. Most of the common functionality for implementing reliable
/// connections on top of unreliable datagrams, connection quality measurement,
/// etc is implemented here.
class CSteamNetworkConnectionBase : public ILockableThinker< ConnectionLock >
{
public:
//
// API entry points
//
/// Called when we close the connection locally
void APICloseConnection( int nReason, const char *pszDebug, bool bEnableLinger );
/// Send a message
EResult APISendMessageToConnection( const void *pData, uint32 cbData, int nSendFlags, int64 *pOutMessageNumber );
/// Send a message. Returns the assigned message number, or a negative EResult value
int64 APISendMessageToConnection( CSteamNetworkingMessage *pMsg, SteamNetworkingMicroseconds usecNow, bool *pbThinkImmediately = nullptr );
/// Flush any messages queued for Nagle
EResult APIFlushMessageOnConnection();
/// Receive the next message(s)
int APIReceiveMessages( SteamNetworkingMessage_t **ppOutMessages, int nMaxMessages );
/// Accept a connection. This will involve sending a message
/// to the client, and calling ConnectionState_Connected on the connection
/// to transition it to the connected state.
EResult APIAcceptConnection();
virtual EResult AcceptConnection( SteamNetworkingMicroseconds usecNow );
/// Fill in quick connection stats
void APIGetQuickConnectionStatus( SteamNetworkingQuickConnectionStatus &stats );
/// Fill in detailed connection stats
virtual void APIGetDetailedConnectionStatus( SteamNetworkingDetailedConnectionStatus &stats, SteamNetworkingMicroseconds usecNow );
/// Hook to allow connections to customize message sending.
/// (E.g. loopback.)
virtual int64 _APISendMessageToConnection( CSteamNetworkingMessage *pMsg, SteamNetworkingMicroseconds usecNow, bool *pbThinkImmediately );
//
// Accessor
//
// Get/set user data
inline int64 GetUserData() const
{
// User data is locked when we create a connection!
Assert( m_connectionConfig.m_ConnectionUserData.IsSet() );
return m_connectionConfig.m_ConnectionUserData.m_data;
}
void SetUserData( int64 nUserData );
// Get/set name
inline const char *GetAppName() const { return m_szAppName; }
void SetAppName( const char *pszName );
// Debug description
inline const char *GetDescription() const { return m_szDescription; }
/// When something changes that goes into the description, call this to rebuild the description
void SetDescription();
/// High level state of the connection
ESteamNetworkingConnectionState GetState() const { return m_eConnectionState; }
ESteamNetworkingConnectionState GetWireState() const { return m_eConnectionWireState; }
/// Check if the connection is 'connected' from the perspective of the wire protocol.
/// (The wire protocol doesn't care about local states such as linger)
bool BStateIsConnectedForWirePurposes() const { return m_eConnectionWireState == k_ESteamNetworkingConnectionState_Connected; }
/// Return true if the connection is still "active" in some way.
bool BStateIsActive() const
{
return
m_eConnectionWireState == k_ESteamNetworkingConnectionState_Connecting
|| m_eConnectionWireState == k_ESteamNetworkingConnectionState_FindingRoute
|| m_eConnectionWireState == k_ESteamNetworkingConnectionState_Connected;
}
/// Reason connection ended
ESteamNetConnectionEnd GetConnectionEndReason() const { return m_eEndReason; }
const char *GetConnectionEndDebugString() const { return m_szEndDebug; }
/// When did we enter the current state?
inline SteamNetworkingMicroseconds GetTimeEnteredConnectionState() const { return m_usecWhenEnteredConnectionState; }
/// Fill in connection details
void ConnectionPopulateInfo( SteamNetConnectionInfo_t &info ) const;
//
// Lifetime management
//
/// Schedule destruction at the next possible opportunity
void ConnectionQueueDestroy();
static void ProcessDeletionList();
/// Free up all resources. Close sockets, etc
virtual void FreeResources();
/// Nuke all transports
virtual void DestroyTransport();
//
// Connection state machine
// Functions to transition to the specified state.
//
void ConnectionState_ProblemDetectedLocally( ESteamNetConnectionEnd eReason, PRINTF_FORMAT_STRING const char *pszFmt, ... ) FMTFUNCTION( 3, 4 );
void ConnectionState_ClosedByPeer( int nReason, const char *pszDebug );
void ConnectionState_FindingRoute( SteamNetworkingMicroseconds usecNow );
bool BConnectionState_Connecting( SteamNetworkingMicroseconds usecNow, SteamNetworkingErrMsg &errMsg );
void ConnectionState_Connected( SteamNetworkingMicroseconds usecNow );
void ConnectionState_FinWait();
//
// Misc internal stuff
//
/// What interface is responsible for this connection?
CSteamNetworkingSockets *const m_pSteamNetworkingSocketsInterface;
/// Current active transport for this connection.
/// MIGHT BE NULL in certain failure / edge cases!
/// Might change during the connection lifetime.
CConnectionTransport *m_pTransport;
/// Our public handle
HSteamNetConnection m_hConnectionSelf;
/// Who is on the other end? This might be invalid if we don't know yet. (E.g. direct UDP connections.)
SteamNetworkingIdentity m_identityRemote;
/// Who are we?
SteamNetworkingIdentity m_identityLocal;
/// The listen socket through which we were accepted, if any.
CSteamNetworkListenSocketBase *m_pParentListenSocket;
/// What poll group are we assigned to?
CSteamNetworkPollGroup *m_pPollGroup;
/// Assign poll group
void SetPollGroup( CSteamNetworkPollGroup *pPollGroup );
/// Remove us from the poll group we are in (if any)
void RemoveFromPollGroup();
/// Was this connection initiated locally (we are the "client") or remotely (we are the "server")?
/// In *most* use cases, "server" connections have a listen socket, but not always.
bool m_bConnectionInitiatedRemotely;
/// Our handle in our parent's m_listAcceptedConnections (if we were accepted on a listen socket)
int m_hSelfInParentListenSocketMap;
// Linked list of received messages
SteamNetworkingMessageQueue m_queueRecvMessages;
/// The unique 64-bit end-to-end connection ID. Each side picks 32 bits
uint32 m_unConnectionIDLocal;
uint32 m_unConnectionIDRemote;
/// Track end-to-end stats for this connection.
LinkStatsTracker<LinkStatsTrackerEndToEnd> m_statsEndToEnd;
/// When we accept a connection, they will send us a timestamp we should send back
/// to them, so that they can estimate the ping
uint64 m_ulHandshakeRemoteTimestamp;
SteamNetworkingMicroseconds m_usecWhenReceivedHandshakeRemoteTimestamp;
/// Connection configuration
ConnectionConfig m_connectionConfig;
/// The reason code for why the connection was closed.
ESteamNetConnectionEnd m_eEndReason;
ConnectionEndDebugMsg m_szEndDebug;
/// MTU values for this connection
int m_cbMTUPacketSize = 0;
int m_cbMaxPlaintextPayloadSend = 0;
int m_cbMaxMessageNoFragment = 0;
int m_cbMaxReliableMessageSegment = 0;
void UpdateMTUFromConfig();
// Each connection is protected by a lock. The actual lock to use is IThinker::m_pLock.
// Almost all connections use this default lock. (A few special cases use a different lock
// so that they are locked at the same time as other objects.)
ConnectionLock m_defaultLock;
void _AssertLocksHeldByCurrentThread( const char *pszFile, int line, const char *pszTag = nullptr ) const
{
SteamNetworkingGlobalLock::_AssertHeldByCurrentThread( pszFile, line, pszTag );
m_pLock->_AssertHeldByCurrentThread( pszFile, line );
}
/// Expand the packet number, and decrypt the data chunk.
/// Returns true if everything is OK and we should continue
/// processing the packet
bool DecryptDataChunk( uint16 nWireSeqNum, int cbPacketSize, const void *pChunk, int cbChunk, RecvPacketContext_t &ctx );
/// Decode the plaintext. Returns false if the packet seems corrupt or bogus, or should abort further
/// processing.
bool ProcessPlainTextDataChunk( int usecTimeSinceLast, RecvPacketContext_t &ctx );
/// Called when we receive an (end-to-end) packet with a sequence number
void RecvNonDataSequencedPacket( int64 nPktNum, SteamNetworkingMicroseconds usecNow );
// Called from SNP to update transmit/receive speeds
void UpdateSpeeds( int nTXSpeed, int nRXSpeed );
/// Called when the async process to request a cert has failed.
void CertRequestFailed( ESteamNetConnectionEnd nConnectionEndReason, const char *pszMsg );
bool BHasLocalCert() const { return m_msgSignedCertLocal.has_cert(); }
void SetLocalCert( const CMsgSteamDatagramCertificateSigned &msgSignedCert, const CECSigningPrivateKey &keyPrivate, bool bCertHasIdentity );
void InterfaceGotCert();
bool SNP_BHasAnyBufferedRecvData() const
{
return !m_receiverState.m_bufReliableStream.empty();
}
bool SNP_BHasAnyUnackedSentReliableData() const
{
return m_senderState.m_cbPendingReliable > 0 || m_senderState.m_cbSentUnackedReliable > 0;
}
/// Return true if we have any reason to send a packet. This doesn't mean we have the bandwidth
/// to send it now, it just means we would like to send something ASAP
inline bool SNP_WantsToSendPacket() const
{
return m_receiverState.TimeWhenFlushAcks() < INT64_MAX || SNP_TimeWhenWantToSendNextPacket() < INT64_MAX;
}
/// Send a data packet now, even if we don't have the bandwidth available. Returns true if a packet was
/// sent successfully, false if there was a problem. This will call SendEncryptedDataChunk to do the work
bool SNP_SendPacket( CConnectionTransport *pTransport, SendPacketContext_t &ctx );
/// Record that we sent a non-data packet. This is so that if the peer acks,
/// we can record it as a ping
void SNP_SentNonDataPacket( CConnectionTransport *pTransport, int cbPkt, SteamNetworkingMicroseconds usecNow );
/// Called after the connection state changes. Default behavior is to notify
/// the active transport, if any
virtual void ConnectionStateChanged( ESteamNetworkingConnectionState eOldState );
/// Called to post a callback
int m_nSupressStateChangeCallbacks;
void PostConnectionStateChangedCallback( ESteamNetworkingConnectionState eOldAPIState, ESteamNetworkingConnectionState eNewAPIState );
void QueueEndToEndAck( bool bImmediate, SteamNetworkingMicroseconds usecNow )
{
if ( bImmediate )
{
m_receiverState.QueueFlushAllAcks( k_nThinkTime_ASAP );
SetNextThinkTimeASAP();
}
else
{
QueueFlushAllAcks( usecNow + k_usecMaxDataAckDelay );
}
}
void QueueFlushAllAcks( SteamNetworkingMicroseconds usecWhen )
{
m_receiverState.QueueFlushAllAcks( usecWhen );
EnsureMinThinkTime( m_receiverState.TimeWhenFlushAcks() );
}
inline const CMsgSteamDatagramSessionCryptInfoSigned &GetSignedCryptLocal() { return m_msgSignedCryptLocal; }
inline const CMsgSteamDatagramCertificateSigned &GetSignedCertLocal() { return m_msgSignedCertLocal; }
inline bool BCertHasIdentity() const { return m_bCertHasIdentity; }
inline bool BCryptKeysValid() const { return m_bCryptKeysValid; }
/// Called when we send an end-to-end connect request
void SentEndToEndConnectRequest( SteamNetworkingMicroseconds usecNow )
{
// Reset timeout/retry for this reply. But if it fails, we'll start
// the whole handshake over again. It keeps the code simpler, and the
// challenge value has a relatively short expiry anyway.
m_usecWhenSentConnectRequest = usecNow;
EnsureMinThinkTime( usecNow + k_usecConnectRetryInterval );
}
/// Symmetric mode
inline bool BSymmetricMode() const { return m_connectionConfig.m_SymmetricConnect.Get() != 0; }
virtual bool BSupportsSymmetricMode();
// Check the certs, save keys, etc
bool BRecvCryptoHandshake( const CMsgSteamDatagramCertificateSigned &msgCert, const CMsgSteamDatagramSessionCryptInfoSigned &msgSessionInfo, bool bServer );
bool BFinishCryptoHandshake( bool bServer );
/// Check state of connection. Check for timeouts, and schedule time when we
/// should think next
void CheckConnectionStateAndSetNextThinkTime( SteamNetworkingMicroseconds usecNow );
/// Same as CheckConnectionStateAndSetNextThinkTime, but can be called when we don't
/// already have the global lock. If we can take the necessary locks now, without
/// blocking, then we'll go ahead and take action now. If we cannot, we will
/// just schedule a wakeup call
void CheckConnectionStateOrScheduleWakeUp( SteamNetworkingMicroseconds usecNow );
// Upcasts. So we don't have to compile with RTTI
virtual CSteamNetworkConnectionP2P *AsSteamNetworkConnectionP2P();
/// Check if this connection is an internal connection for the
/// ISteamMessages interface. The messages layer *mostly* works
/// on top of the sockets system, but in a few places we need
/// to break the abstraction and do things other clients of the
/// API could not do easily
inline bool IsConnectionForMessagesSession() const { return m_connectionConfig.m_LocalVirtualPort.Get() == k_nVirtualPort_Messages; }
/// Time when we would like to send our next connection diagnostics
/// update. This is initialized the first time we enter the "connecting"
/// state and we are on a platform that wants those updates.
/// Once we wish to stop sending them, we set it to "never"
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_DIAGNOSTICSUI
SteamNetworkingMicroseconds m_usecWhenNextDiagnosticsUpdate;
void CheckScheduleDiagnosticsUpdateASAP();
/// Fill out diagnostics message to send to steam client with current state of the
/// connection, and also schedule the next check, if the connection is active.
virtual void ConnectionPopulateDiagnostics( ESteamNetworkingConnectionState eOldState, CGameNetworkingUI_ConnectionState &msgConnectionState, SteamNetworkingMicroseconds usecNow );
#else
inline void CheckScheduleDiagnosticsUpdateASAP() {}
static constexpr SteamNetworkingMicroseconds m_usecWhenNextDiagnosticsUpdate = k_nThinkTime_Never;
#endif
/// Timestamp when we were created
SteamNetworkingMicroseconds m_usecWhenCreated;
protected:
CSteamNetworkConnectionBase( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface, ConnectionScopeLock &scopeLock );
virtual ~CSteamNetworkConnectionBase(); // hidden destructor, don't call directly. Use ConnectionQueueDestroy()
/// Initialize connection bookkeeping
bool BInitConnection( SteamNetworkingMicroseconds usecNow, int nOptions, const SteamNetworkingConfigValue_t *pOptions, SteamDatagramErrMsg &errMsg );
/// Called from BInitConnection, to start obtaining certs, etc
virtual void InitConnectionCrypto( SteamNetworkingMicroseconds usecNow );
/// Name assigned by app (for debugging)
char m_szAppName[ k_cchSteamNetworkingMaxConnectionDescription ];
/// More complete debug description (for debugging)
char m_szDescription[ k_cchSteamNetworkingMaxConnectionDescription ];
/// Set the connection description. Should include the connection type and peer address.
virtual void GetConnectionTypeDescription( ConnectionTypeDescription_t &szDescription ) const = 0;
/// Misc periodic processing.
/// Called from within CheckConnectionStateAndSetNextThinkTime.
/// Will be called in any connection state.
virtual void ThinkConnection( SteamNetworkingMicroseconds usecNow );
/// Called from the connection Think() state machine, for connections that have been
/// initiated locally and that are in the connecting state.
///
/// Should return the next time when it needs to be woken up. Or it can set the next
/// think time directly, if it is awkward to return. That is slightly
/// less efficient.
///
/// Base class sends connect requests (including periodic retry) through the current
/// transport.
virtual SteamNetworkingMicroseconds ThinkConnection_ClientConnecting( SteamNetworkingMicroseconds usecNow );
/// Called from the connection Think() state machine, when the connection is in the finding
/// route state. The connection should return the next time when it needs to be woken up.
/// Or it can set the next think time directly, if it is awkward to return. That is slightly
/// less efficient.
virtual SteamNetworkingMicroseconds ThinkConnection_FindingRoute( SteamNetworkingMicroseconds usecNow );
/// Called when a timeout is detected
void ConnectionTimedOut( SteamNetworkingMicroseconds usecNow );
/// Called when a timeout is detected to tried to provide a more specific error
/// message.
virtual void ConnectionGuessTimeoutReason( ESteamNetConnectionEnd &nReasonCode, ConnectionEndDebugMsg &msg, SteamNetworkingMicroseconds usecNow );
/// Called when we receive a complete message. Should allocate a message object and put it into the proper queues
bool ReceivedMessage( const void *pData, int cbData, int64 nMsgNum, int nFlags, SteamNetworkingMicroseconds usecNow );
void ReceivedMessage( CSteamNetworkingMessage *pMsg );
/// Timestamp when we last sent an end-to-end connection request packet
SteamNetworkingMicroseconds m_usecWhenSentConnectRequest;
//
// Crypto
//
void ClearCrypto();
bool BThinkCryptoReady( SteamNetworkingMicroseconds usecNow );
void SetLocalCertUnsigned();
void ClearLocalCrypto();
void FinalizeLocalCrypto();
void SetCryptoCipherList();
// Remote cert and crypt info. We need to hand on to the original serialized version briefly
std::string m_sCertRemote;
std::string m_sCryptRemote;
CMsgSteamDatagramCertificate m_msgCertRemote;
CMsgSteamDatagramSessionCryptInfo m_msgCryptRemote;
bool m_bRemoteCertHasTrustedCASignature; // Could expand this to an enum of different states
// Local crypto info for this connection
CECSigningPrivateKey m_keyPrivate; // Private key corresponding to our cert. We'll wipe this in FinalizeLocalCrypto, as soon as we've locked in the crypto properties we're going to use
CECKeyExchangePrivateKey m_keyExchangePrivateKeyLocal;
CMsgSteamDatagramSessionCryptInfo m_msgCryptLocal;
CMsgSteamDatagramSessionCryptInfoSigned m_msgSignedCryptLocal;
CMsgSteamDatagramCertificateSigned m_msgSignedCertLocal;
bool m_bCertHasIdentity; // Does the cert contain the identity we will use for this connection?
ESteamNetworkingSocketsCipher m_eNegotiatedCipher;
// AES keys used in each direction
bool m_bCryptKeysValid;
AES_GCM_EncryptContext m_cryptContextSend;
AES_GCM_DecryptContext m_cryptContextRecv;
// Initialization vector for AES-GCM. These are combined with
// the packet number so that the effective IV is unique per
// packet. We use a 96-bit IV, which is what TLS uses (RFC5288),
// what NIST recommends (https://dl.acm.org/citation.cfm?id=2206251),
// and what makes GCM the most efficient.
AutoWipeFixedSizeBuffer<12> m_cryptIVSend;
AutoWipeFixedSizeBuffer<12> m_cryptIVRecv;
/// Check if the remote cert (m_msgCertRemote) is acceptable. If not, return the
/// appropriate connection code and error message. If pCACertAuthScope is NULL, the
/// cert is not signed. (The base class will check if this is allowed.) If pCACertAuthScope
/// is present, the cert was signed and the chain of trust has been verified, and the CA trust
/// chain has authorized the specified rights.
virtual ESteamNetConnectionEnd CheckRemoteCert( const CertAuthScope *pCACertAuthScope, SteamNetworkingErrMsg &errMsg );
/// Called when we the remote host presents us with an unsigned cert.
virtual EUnsignedCert AllowRemoteUnsignedCert();
/// Called to decide if we want to try to proceed without a signed cert for ourselves
virtual EUnsignedCert AllowLocalUnsignedCert();
//
// "SNP" - Steam Networking Protocol. (Sort of audacious to stake out this acronym, don't you think...?)
// The layer that does end-to-end reliability and bandwidth estimation
//
void SNP_InitializeConnection( SteamNetworkingMicroseconds usecNow );
void SNP_ShutdownConnection();
int64 SNP_SendMessage( CSteamNetworkingMessage *pSendMessage, SteamNetworkingMicroseconds usecNow, bool *pbThinkImmediately );
SteamNetworkingMicroseconds SNP_ThinkSendState( SteamNetworkingMicroseconds usecNow );
SteamNetworkingMicroseconds SNP_GetNextThinkTime( SteamNetworkingMicroseconds usecNow );
SteamNetworkingMicroseconds SNP_TimeWhenWantToSendNextPacket() const;
void SNP_PrepareFeedback( SteamNetworkingMicroseconds usecNow );
void SNP_ReceiveUnreliableSegment( int64 nMsgNum, int nOffset, const void *pSegmentData, int cbSegmentSize, bool bLastSegmentInMessage, SteamNetworkingMicroseconds usecNow );
bool SNP_ReceiveReliableSegment( int64 nPktNum, int64 nSegBegin, const uint8 *pSegmentData, int cbSegmentSize, SteamNetworkingMicroseconds usecNow );
int SNP_ClampSendRate();
void SNP_PopulateDetailedStats( SteamDatagramLinkStats &info );
void SNP_PopulateQuickStats( SteamNetworkingQuickConnectionStatus &info, SteamNetworkingMicroseconds usecNow );
void SNP_RecordReceivedPktNum( int64 nPktNum, SteamNetworkingMicroseconds usecNow, bool bScheduleAck );
EResult SNP_FlushMessage( SteamNetworkingMicroseconds usecNow );
/// Accumulate "tokens" into our bucket base on the current calculated send rate
void SNP_TokenBucket_Accumulate( SteamNetworkingMicroseconds usecNow );
/// Mark a packet as dropped
void SNP_SenderProcessPacketNack( int64 nPktNum, SNPInFlightPacket_t &pkt, const char *pszDebug );
/// Check in flight packets. Expire any that need to be, and return the time when the
/// next one that is not yet expired will be expired.
SteamNetworkingMicroseconds SNP_SenderCheckInFlightPackets( SteamNetworkingMicroseconds usecNow );
SSNPSenderState m_senderState;
SSNPReceiverState m_receiverState;
/// Bandwidth estimation data
SSendRateData m_sendRateData; // FIXME Move this to transport!
/// Called from SNP layer when it decodes a packet that serves as a ping measurement
virtual void ProcessSNPPing( int msPing, RecvPacketContext_t &ctx );
private:
void SNP_GatherAckBlocks( SNPAckSerializerHelper &helper, SteamNetworkingMicroseconds usecNow );
uint8 *SNP_SerializeAckBlocks( const SNPAckSerializerHelper &helper, uint8 *pOut, const uint8 *pOutEnd, SteamNetworkingMicroseconds usecNow );
uint8 *SNP_SerializeStopWaitingFrame( uint8 *pOut, const uint8 *pOutEnd, SteamNetworkingMicroseconds usecNow );
void SetState( ESteamNetworkingConnectionState eNewState, SteamNetworkingMicroseconds usecNow );
ESteamNetworkingConnectionState m_eConnectionState;
/// State of the connection as our peer would observe it.
/// (Certain local state transitions are not meaningful.)
///
/// Differs from m_eConnectionState in two ways:
/// - Linger is not used. Instead, to the peer we are "connected."
/// - When the local connection state transitions
/// from ProblemDetectedLocally or ClosedByPeer to FinWait,
/// when the application closes the connection, this value
/// will not change. It will retain the previous state,
/// so that while we are in the FinWait state, we can send
/// appropriate cleanup messages.
ESteamNetworkingConnectionState m_eConnectionWireState;
/// Timestamp when we entered the current state. Used for various
/// timeouts.
SteamNetworkingMicroseconds m_usecWhenEnteredConnectionState;
// !DEBUG! Log of packets we sent.
#ifdef SNP_ENABLE_PACKETSENDLOG
struct PacketSendLog
{
// State before we sent anything
SteamNetworkingMicroseconds m_usecTime;
int m_cbPendingReliable;
int m_cbPendingUnreliable;
int m_nPacketGaps;
float m_fltokens;
int64 m_nPktNumNextPendingAck;
SteamNetworkingMicroseconds m_usecNextPendingAckTime;
int64 m_nMaxPktRecv;
int64 m_nMinPktNumToSendAcks;
int m_nAckBlocksNeeded;
// What we sent
int m_nAckBlocksSent;
int64 m_nAckEnd;
int m_nReliableSegmentsRetry;
int m_nSegmentsSent;
int m_cbSent;
};
std_vector<PacketSendLog> m_vecSendLog;
#endif
// Implements IThinker.
// Connections must not override this, or call it directly.
// Do any periodic work in ThinkConnection()
virtual void Think( SteamNetworkingMicroseconds usecNow ) override final;
};
/// Abstract base class for sending end-to-end data for a connection.
///
/// Many connection classes only have one transport, but some may
/// may have more than one transport, and dynamically switch between
/// them. (E.g. it will try local LAN, NAT piercing, then fallback to relay)
class CConnectionTransport
{
public:
/// The connection we were created to service. A given transport object
/// is always created for a single connection (and that will not change,
/// hence this is a reference and not a pointer). However, a connection may
/// create more than one transport.
CSteamNetworkConnectionBase &m_connection;
/// Use this function to actually delete the object. Do not use operator delete
void TransportDestroySelfNow();
/// Free up transport resources. Called just before destruction. If you have cleanup
/// that might involved calling virtual methods, do it in here
virtual void TransportFreeResources();
/// Called by SNP pacing layer, when it has some data to send and there is bandwidth available.
/// The derived class should setup a context, reserving the space it needs, and then call SNP_SendPacket.
/// Returns true if a packet was sent successfully, false if there was a problem.
virtual bool SendDataPacket( SteamNetworkingMicroseconds usecNow ) = 0;
/// Connection will call this to ask the transport to surround the
/// "chunk" with the appropriate framing, and route it to the
/// appropriate host. A "chunk" might contain a mix of reliable
/// and unreliable data. We use the same framing for data
/// payloads for all connection types. Return value is
/// the number of bytes written to the network layer, UDP/IP
/// header is not included.
///
/// ctx is whatever the transport passed to SNP_SendPacket, if the
/// connection initiated the sending of the packet
virtual int SendEncryptedDataChunk( const void *pChunk, int cbChunk, SendPacketContext_t &ctx ) = 0;
/// Return true if we are currently able to send end-to-end messages.
virtual bool BCanSendEndToEndConnectRequest() const;
virtual bool BCanSendEndToEndData() const = 0;
virtual void SendEndToEndConnectRequest( SteamNetworkingMicroseconds usecNow );
virtual void SendEndToEndStatsMsg( EStatsReplyRequest eRequest, SteamNetworkingMicroseconds usecNow, const char *pszReason ) = 0;
virtual void TransportPopulateConnectionInfo( SteamNetConnectionInfo_t &info ) const;
virtual void GetDetailedConnectionStatus( SteamNetworkingDetailedConnectionStatus &stats, SteamNetworkingMicroseconds usecNow );
#ifdef STEAMNETWORKINGSOCKETS_ENABLE_DIAGNOSTICSUI
virtual void TransportPopulateDiagnostics( CGameNetworkingUI_ConnectionState &msgConnectionState, SteamNetworkingMicroseconds usecNow );
#endif
/// Called when the connection state changes. Some transports need to do stuff
virtual void TransportConnectionStateChanged( ESteamNetworkingConnectionState eOldState );
/// Called when a timeout is detected to tried to provide a more specific error
/// message
virtual void TransportGuessTimeoutReason( ESteamNetConnectionEnd &nReasonCode, ConnectionEndDebugMsg &msg, SteamNetworkingMicroseconds usecNow );
// Some accessors for commonly needed info
inline ESteamNetworkingConnectionState ConnectionState() const { return m_connection.GetState(); }
inline ESteamNetworkingConnectionState ConnectionWireState() const { return m_connection.GetWireState(); }
inline uint32 ConnectionIDLocal() const { return m_connection.m_unConnectionIDLocal; }
inline uint32 ConnectionIDRemote() const { return m_connection.m_unConnectionIDRemote; }
inline CSteamNetworkListenSocketBase *ListenSocket() const { return m_connection.m_pParentListenSocket; }
inline const SteamNetworkingIdentity &IdentityLocal() const { return m_connection.m_identityLocal; }
inline const SteamNetworkingIdentity &IdentityRemote() const { return m_connection.m_identityRemote; }
inline const char *ConnectionDescription() const { return m_connection.GetDescription(); }
void _AssertLocksHeldByCurrentThread( const char *pszFile, int line, const char *pszTag = nullptr ) const
{
m_connection._AssertLocksHeldByCurrentThread( pszFile, line, pszTag );
}
// Useful so we can use ScheduledMethodThinkerLockable
bool TryLock() { return m_connection.TryLock(); }
void Unlock() { m_connection.Unlock(); }
protected:
inline CConnectionTransport( CSteamNetworkConnectionBase &conn ) : m_connection( conn ) {}
virtual ~CConnectionTransport() {} // Destructor protected -- use TransportDestroySelfNow()
};
// Delayed inline
inline ConnectionScopeLock::ConnectionScopeLock( CSteamNetworkConnectionBase &conn, const char *pszTag ) : ScopeLock<ConnectionLock>( *conn.m_pLock, pszTag ) {}
inline void ConnectionScopeLock::Lock( CSteamNetworkConnectionBase &conn, const char *pszTag ) { ScopeLock<ConnectionLock>::Lock( *conn.m_pLock, pszTag ); }
/// Dummy loopback/pipe connection that doesn't actually do any network work.
/// For these types of connections, the distinction between connection and transport
/// is not really useful
class CSteamNetworkConnectionPipe final : public CSteamNetworkConnectionBase, public CConnectionTransport
{
public:
/// Create a pair of loopback connections that are immediately connected to each other
/// No callbacks are posted.
static bool APICreateSocketPair( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface, CSteamNetworkConnectionPipe **pOutConnections, const SteamNetworkingIdentity pIdentity[2] );
/// Create a pair of loopback connections that act like normal connections, but use internal transport.
/// The two connections will be placed in the "connecting" state, and will go through the ordinary
/// state machine.
///
/// The client connection is returned.
static CSteamNetworkConnectionPipe *CreateLoopbackConnection(
CSteamNetworkingSockets *pClientInstance, int nOptions, const SteamNetworkingConfigValue_t *pOptions,
CSteamNetworkListenSocketBase *pListenSocket,
SteamNetworkingErrMsg &errMsg,
ConnectionScopeLock &scopeLock );
/// The guy who is on the other end.
CSteamNetworkConnectionPipe *m_pPartner;
// CSteamNetworkConnectionBase overrides
virtual int64 _APISendMessageToConnection( CSteamNetworkingMessage *pMsg, SteamNetworkingMicroseconds usecNow, bool *pbThinkImmediately ) override;
virtual EResult AcceptConnection( SteamNetworkingMicroseconds usecNow ) override;
virtual void InitConnectionCrypto( SteamNetworkingMicroseconds usecNow ) override;
virtual EUnsignedCert AllowRemoteUnsignedCert() override;
virtual EUnsignedCert AllowLocalUnsignedCert() override;
virtual void GetConnectionTypeDescription( ConnectionTypeDescription_t &szDescription ) const override;
virtual void DestroyTransport() override;
virtual void ConnectionStateChanged( ESteamNetworkingConnectionState eOldState ) override;
// CConnectionTransport
virtual bool SendDataPacket( SteamNetworkingMicroseconds usecNow ) override;
virtual bool BCanSendEndToEndConnectRequest() const override;
virtual bool BCanSendEndToEndData() const override;
virtual void SendEndToEndConnectRequest( SteamNetworkingMicroseconds usecNow ) override;
virtual void SendEndToEndStatsMsg( EStatsReplyRequest eRequest, SteamNetworkingMicroseconds usecNow, const char *pszReason ) override;
virtual int SendEncryptedDataChunk( const void *pChunk, int cbChunk, SendPacketContext_t &ctx ) override;
virtual void TransportPopulateConnectionInfo( SteamNetConnectionInfo_t &info ) const override;
private:
// Use CreateSocketPair!
CSteamNetworkConnectionPipe( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface, const SteamNetworkingIdentity &identity, ConnectionScopeLock &scopeLock );
virtual ~CSteamNetworkConnectionPipe();
/// Setup the server side of a loopback connection
bool BBeginAccept( CSteamNetworkListenSocketBase *pListenSocket, SteamNetworkingMicroseconds usecNow, SteamDatagramErrMsg &errMsg );
/// Act like we sent a sequenced packet
void FakeSendStats( SteamNetworkingMicroseconds usecNow, int cbPktSize );
};
// Had to delay this until CSteamNetworkConnectionBase was defined
template<typename TStatsMsg>
inline void SendPacketContext<TStatsMsg>::CalcMaxEncryptedPayloadSize( size_t cbHdrReserve, CSteamNetworkConnectionBase *pConnection )
{
Assert( m_cbTotalSize >= 0 );
m_cbMaxEncryptedPayload = pConnection->m_cbMTUPacketSize - (int)cbHdrReserve - m_cbTotalSize;
Assert( m_cbMaxEncryptedPayload >= 0 );
}
/////////////////////////////////////////////////////////////////////////////
//
// Misc globals
//
/////////////////////////////////////////////////////////////////////////////
extern CUtlHashMap<uint16, CSteamNetworkConnectionBase *, std::equal_to<uint16>, Identity<uint16> > g_mapConnections;
extern CUtlHashMap<int, CSteamNetworkPollGroup *, std::equal_to<int>, Identity<int> > g_mapPollGroups;
// All of the tables above are projected by the same lock, since we expect to only access it briefly
struct TableLock : Lock<RecursiveMutexImpl> {
TableLock() : Lock<RecursiveMutexImpl>( "table", LockDebugInfo::k_nFlag_Table ) {}
};
using TableScopeLock = ScopeLock<TableLock>;
extern TableLock g_tables_lock;
// This table is protected by the global lock
extern CUtlHashMap<int, CSteamNetworkListenSocketBase *, std::equal_to<int>, Identity<int> > g_mapListenSockets;
extern bool BCheckGlobalSpamReplyRateLimit( SteamNetworkingMicroseconds usecNow );
extern CSteamNetworkConnectionBase *GetConnectionByHandle( HSteamNetConnection sock, ConnectionScopeLock &scopeLock );
extern CSteamNetworkPollGroup *GetPollGroupByHandle( HSteamNetPollGroup hPollGroup, PollGroupScopeLock &scopeLock, const char *pszLockTag );
inline CSteamNetworkConnectionBase *FindConnectionByLocalID( uint32 nLocalConnectionID, ConnectionScopeLock &scopeLock )
{
// We use the wire connection ID as the API handle, so these two operations
// are currently the same.
return GetConnectionByHandle( HSteamNetConnection( nLocalConnectionID ), scopeLock );
}
} // namespace SteamNetworkingSocketsLib
#endif // STEAMNETWORKINGSOCKETS_CONNECTIONS_H
| [
"[email protected]"
] | |
9f44e267309e7be03b52a8e33c45771030aedbd3 | e5e0d729f082999a9bec142611365b00f7bfc684 | /tensorflow/stream_executor/cuda/cuda_runtime_10_0.inc | 9b912330512ba8704d66296732774fa810e7915c | [
"Apache-2.0"
] | permissive | NVIDIA/tensorflow | ed6294098c7354dfc9f09631fc5ae22dbc278138 | 7cbba04a2ee16d21309eefad5be6585183a2d5a9 | refs/heads/r1.15.5+nv23.03 | 2023-08-16T22:25:18.037979 | 2023-08-03T22:09:23 | 2023-08-03T22:09:23 | 263,748,045 | 763 | 117 | Apache-2.0 | 2023-07-03T15:45:19 | 2020-05-13T21:34:32 | C++ | UTF-8 | C++ | false | false | 68,880 | inc | // Auto-generated, do not edit.
extern "C" {
extern __host__ cudaError_t CUDARTAPI cudaDeviceReset(void) {
using FuncPtr = cudaError_t(CUDARTAPI *)();
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceReset");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr();
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaDeviceSynchronize(void) {
using FuncPtr = cudaError_t(CUDARTAPI *)();
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceSynchronize");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr();
}
extern __host__ cudaError_t CUDARTAPI cudaDeviceSetLimit(enum cudaLimit limit,
size_t value) {
using FuncPtr = cudaError_t(CUDARTAPI *)(enum cudaLimit, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceSetLimit");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(limit, value);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaDeviceGetLimit(size_t *pValue, enum cudaLimit limit) {
using FuncPtr = cudaError_t(CUDARTAPI *)(size_t *, enum cudaLimit);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceGetLimit");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pValue, limit);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaDeviceGetCacheConfig(enum cudaFuncCache *pCacheConfig) {
using FuncPtr = cudaError_t(CUDARTAPI *)(enum cudaFuncCache *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceGetCacheConfig");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pCacheConfig);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaDeviceGetStreamPriorityRange(int *leastPriority, int *greatestPriority) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *, int *);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaDeviceGetStreamPriorityRange");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(leastPriority, greatestPriority);
}
extern __host__ cudaError_t CUDARTAPI
cudaDeviceSetCacheConfig(enum cudaFuncCache cacheConfig) {
using FuncPtr = cudaError_t(CUDARTAPI *)(enum cudaFuncCache);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceSetCacheConfig");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(cacheConfig);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaDeviceGetSharedMemConfig(enum cudaSharedMemConfig *pConfig) {
using FuncPtr = cudaError_t(CUDARTAPI *)(enum cudaSharedMemConfig *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceGetSharedMemConfig");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pConfig);
}
extern __host__ cudaError_t CUDARTAPI
cudaDeviceSetSharedMemConfig(enum cudaSharedMemConfig config) {
using FuncPtr = cudaError_t(CUDARTAPI *)(enum cudaSharedMemConfig);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceSetSharedMemConfig");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(config);
}
extern __host__ cudaError_t CUDARTAPI
cudaDeviceGetByPCIBusId(int *device, const char *pciBusId) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *, const char *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceGetByPCIBusId");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(device, pciBusId);
}
extern __host__ cudaError_t CUDARTAPI cudaDeviceGetPCIBusId(char *pciBusId,
int len,
int device) {
using FuncPtr = cudaError_t(CUDARTAPI *)(char *, int, int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceGetPCIBusId");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pciBusId, len, device);
}
extern __host__ cudaError_t CUDARTAPI
cudaIpcGetEventHandle(cudaIpcEventHandle_t *handle, cudaEvent_t event) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaIpcEventHandle_t *, cudaEvent_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaIpcGetEventHandle");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(handle, event);
}
extern __host__ cudaError_t CUDARTAPI
cudaIpcOpenEventHandle(cudaEvent_t *event, cudaIpcEventHandle_t handle) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaEvent_t *, cudaIpcEventHandle_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaIpcOpenEventHandle");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(event, handle);
}
extern __host__ cudaError_t CUDARTAPI
cudaIpcGetMemHandle(cudaIpcMemHandle_t *handle, void *devPtr) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaIpcMemHandle_t *, void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaIpcGetMemHandle");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(handle, devPtr);
}
extern __host__ cudaError_t CUDARTAPI cudaIpcOpenMemHandle(
void **devPtr, cudaIpcMemHandle_t handle, unsigned int flags) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(void **, cudaIpcMemHandle_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaIpcOpenMemHandle");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, handle, flags);
}
extern __host__ cudaError_t CUDARTAPI cudaIpcCloseMemHandle(void *devPtr) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaIpcCloseMemHandle");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr);
}
extern __CUDA_DEPRECATED __host__ cudaError_t CUDARTAPI cudaThreadExit(void) {
using FuncPtr = cudaError_t(CUDARTAPI *)();
static auto func_ptr = LoadSymbol<FuncPtr>("cudaThreadExit");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr();
}
extern __CUDA_DEPRECATED __host__ cudaError_t CUDARTAPI
cudaThreadSynchronize(void) {
using FuncPtr = cudaError_t(CUDARTAPI *)();
static auto func_ptr = LoadSymbol<FuncPtr>("cudaThreadSynchronize");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr();
}
extern __CUDA_DEPRECATED __host__ cudaError_t CUDARTAPI
cudaThreadSetLimit(enum cudaLimit limit, size_t value) {
using FuncPtr = cudaError_t(CUDARTAPI *)(enum cudaLimit, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaThreadSetLimit");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(limit, value);
}
extern __CUDA_DEPRECATED __host__ cudaError_t CUDARTAPI
cudaThreadGetLimit(size_t *pValue, enum cudaLimit limit) {
using FuncPtr = cudaError_t(CUDARTAPI *)(size_t *, enum cudaLimit);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaThreadGetLimit");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pValue, limit);
}
extern __CUDA_DEPRECATED __host__ cudaError_t CUDARTAPI
cudaThreadGetCacheConfig(enum cudaFuncCache *pCacheConfig) {
using FuncPtr = cudaError_t(CUDARTAPI *)(enum cudaFuncCache *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaThreadGetCacheConfig");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pCacheConfig);
}
extern __CUDA_DEPRECATED __host__ cudaError_t CUDARTAPI
cudaThreadSetCacheConfig(enum cudaFuncCache cacheConfig) {
using FuncPtr = cudaError_t(CUDARTAPI *)(enum cudaFuncCache);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaThreadSetCacheConfig");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(cacheConfig);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaGetLastError(void) {
using FuncPtr = cudaError_t(CUDARTAPI *)();
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetLastError");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr();
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaPeekAtLastError(void) {
using FuncPtr = cudaError_t(CUDARTAPI *)();
static auto func_ptr = LoadSymbol<FuncPtr>("cudaPeekAtLastError");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr();
}
extern __host__ __cudart_builtin__ const char *CUDARTAPI
cudaGetErrorName(cudaError_t error) {
using FuncPtr = const char *(CUDARTAPI *)(cudaError_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetErrorName");
if (!func_ptr) return "cudaGetErrorName symbol not found.";
return func_ptr(error);
}
extern __host__ __cudart_builtin__ const char *CUDARTAPI
cudaGetErrorString(cudaError_t error) {
using FuncPtr = const char *(CUDARTAPI *)(cudaError_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetErrorString");
if (!func_ptr) return "cudaGetErrorString symbol not found.";
return func_ptr(error);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaGetDeviceCount(int *count) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetDeviceCount");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(count);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaGetDeviceProperties(struct cudaDeviceProp *prop, int device) {
using FuncPtr = cudaError_t(CUDARTAPI *)(struct cudaDeviceProp *, int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetDeviceProperties");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(prop, device);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaDeviceGetAttribute(int *value, enum cudaDeviceAttr attr, int device) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *, enum cudaDeviceAttr, int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceGetAttribute");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(value, attr, device);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaDeviceGetP2PAttribute(int *value, enum cudaDeviceP2PAttr attr,
int srcDevice, int dstDevice) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(int *, enum cudaDeviceP2PAttr, int, int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceGetP2PAttribute");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(value, attr, srcDevice, dstDevice);
}
extern __host__ cudaError_t CUDARTAPI
cudaChooseDevice(int *device, const struct cudaDeviceProp *prop) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(int *, const struct cudaDeviceProp *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaChooseDevice");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(device, prop);
}
extern __host__ cudaError_t CUDARTAPI cudaSetDevice(int device) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaSetDevice");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(device);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaGetDevice(int *device) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetDevice");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(device);
}
extern __host__ cudaError_t CUDARTAPI cudaSetValidDevices(int *device_arr,
int len) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *, int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaSetValidDevices");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(device_arr, len);
}
extern __host__ cudaError_t CUDARTAPI cudaSetDeviceFlags(unsigned int flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaSetDeviceFlags");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(flags);
}
extern __host__ cudaError_t CUDARTAPI cudaGetDeviceFlags(unsigned int *flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(unsigned int *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetDeviceFlags");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(flags);
}
extern __host__ cudaError_t CUDARTAPI cudaStreamCreate(cudaStream_t *pStream) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamCreate");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pStream);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaStreamCreateWithFlags(cudaStream_t *pStream, unsigned int flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t *, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamCreateWithFlags");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pStream, flags);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaStreamCreateWithPriority(cudaStream_t *pStream, unsigned int flags,
int priority) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t *, unsigned int, int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamCreateWithPriority");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pStream, flags, priority);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaStreamGetPriority(cudaStream_t hStream, int *priority) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t, int *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamGetPriority");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(hStream, priority);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaStreamGetFlags(cudaStream_t hStream, unsigned int *flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t, unsigned int *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamGetFlags");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(hStream, flags);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaStreamDestroy(cudaStream_t stream) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamDestroy");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(stream);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI cudaStreamWaitEvent(
cudaStream_t stream, cudaEvent_t event, unsigned int flags) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(cudaStream_t, cudaEvent_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamWaitEvent");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(stream, event, flags);
}
extern __host__ cudaError_t CUDARTAPI
cudaStreamAddCallback(cudaStream_t stream, cudaStreamCallback_t callback,
void *userData, unsigned int flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t, cudaStreamCallback_t,
void *, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamAddCallback");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(stream, callback, userData, flags);
}
extern __host__ cudaError_t CUDARTAPI
cudaStreamSynchronize(cudaStream_t stream) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamSynchronize");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(stream);
}
extern __host__ cudaError_t CUDARTAPI cudaStreamQuery(cudaStream_t stream) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamQuery");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(stream);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaStreamAttachMemAsync(cudaStream_t stream, void *devPtr,
size_t length __dv(0),
unsigned int flags __dv(cudaMemAttachSingle)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(cudaStream_t, void *, size_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamAttachMemAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(stream, devPtr, length, flags);
}
extern __host__ cudaError_t CUDARTAPI cudaStreamIsCapturing(
cudaStream_t stream, enum cudaStreamCaptureStatus *pCaptureStatus) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(cudaStream_t, enum cudaStreamCaptureStatus *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamIsCapturing");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(stream, pCaptureStatus);
}
extern __host__ cudaError_t CUDARTAPI cudaEventCreate(cudaEvent_t *event) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaEvent_t *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaEventCreate");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(event);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaEventCreateWithFlags(cudaEvent_t *event, unsigned int flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaEvent_t *, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaEventCreateWithFlags");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(event, flags);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaEventRecord(cudaEvent_t event, cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaEvent_t, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaEventRecord");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(event, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaEventQuery(cudaEvent_t event) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaEvent_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaEventQuery");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(event);
}
extern __host__ cudaError_t CUDARTAPI cudaEventSynchronize(cudaEvent_t event) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaEvent_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaEventSynchronize");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(event);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaEventDestroy(cudaEvent_t event) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaEvent_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaEventDestroy");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(event);
}
extern __host__ cudaError_t CUDARTAPI cudaEventElapsedTime(float *ms,
cudaEvent_t start,
cudaEvent_t end) {
using FuncPtr = cudaError_t(CUDARTAPI *)(float *, cudaEvent_t, cudaEvent_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaEventElapsedTime");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(ms, start, end);
}
extern __host__ cudaError_t CUDARTAPI cudaImportExternalMemory(
cudaExternalMemory_t *extMem_out,
const struct cudaExternalMemoryHandleDesc *memHandleDesc) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
cudaExternalMemory_t *, const struct cudaExternalMemoryHandleDesc *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaImportExternalMemory");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(extMem_out, memHandleDesc);
}
extern __host__ cudaError_t CUDARTAPI cudaExternalMemoryGetMappedBuffer(
void **devPtr, cudaExternalMemory_t extMem,
const struct cudaExternalMemoryBufferDesc *bufferDesc) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(void **, cudaExternalMemory_t,
const struct cudaExternalMemoryBufferDesc *);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaExternalMemoryGetMappedBuffer");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, extMem, bufferDesc);
}
extern __host__ cudaError_t CUDARTAPI cudaExternalMemoryGetMappedMipmappedArray(
cudaMipmappedArray_t *mipmap, cudaExternalMemory_t extMem,
const struct cudaExternalMemoryMipmappedArrayDesc *mipmapDesc) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
cudaMipmappedArray_t *, cudaExternalMemory_t,
const struct cudaExternalMemoryMipmappedArrayDesc *);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaExternalMemoryGetMappedMipmappedArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(mipmap, extMem, mipmapDesc);
}
extern __host__ cudaError_t CUDARTAPI
cudaDestroyExternalMemory(cudaExternalMemory_t extMem) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaExternalMemory_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDestroyExternalMemory");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(extMem);
}
extern __host__ cudaError_t CUDARTAPI cudaImportExternalSemaphore(
cudaExternalSemaphore_t *extSem_out,
const struct cudaExternalSemaphoreHandleDesc *semHandleDesc) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(cudaExternalSemaphore_t *,
const struct cudaExternalSemaphoreHandleDesc *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaImportExternalSemaphore");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(extSem_out, semHandleDesc);
}
extern __host__ cudaError_t CUDARTAPI cudaSignalExternalSemaphoresAsync(
const cudaExternalSemaphore_t *extSemArray,
const struct cudaExternalSemaphoreSignalParams *paramsArray,
unsigned int numExtSems, cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const cudaExternalSemaphore_t *,
const struct cudaExternalSemaphoreSignalParams *,
unsigned int, cudaStream_t);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaSignalExternalSemaphoresAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(extSemArray, paramsArray, numExtSems, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaWaitExternalSemaphoresAsync(
const cudaExternalSemaphore_t *extSemArray,
const struct cudaExternalSemaphoreWaitParams *paramsArray,
unsigned int numExtSems, cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const cudaExternalSemaphore_t *,
const struct cudaExternalSemaphoreWaitParams *,
unsigned int, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaWaitExternalSemaphoresAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(extSemArray, paramsArray, numExtSems, stream);
}
extern __host__ cudaError_t CUDARTAPI
cudaDestroyExternalSemaphore(cudaExternalSemaphore_t extSem) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaExternalSemaphore_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDestroyExternalSemaphore");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(extSem);
}
extern __host__ cudaError_t CUDARTAPI
cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim, void **args,
size_t sharedMem, cudaStream_t stream) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const void *, dim3, dim3, void **,
size_t, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaLaunchKernel");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(func, gridDim, blockDim, args, sharedMem, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaLaunchCooperativeKernel(
const void *func, dim3 gridDim, dim3 blockDim, void **args,
size_t sharedMem, cudaStream_t stream) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const void *, dim3, dim3, void **,
size_t, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaLaunchCooperativeKernel");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(func, gridDim, blockDim, args, sharedMem, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaLaunchCooperativeKernelMultiDevice(
struct cudaLaunchParams *launchParamsList, unsigned int numDevices,
unsigned int flags __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(struct cudaLaunchParams *,
unsigned int, unsigned int);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaLaunchCooperativeKernelMultiDevice");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(launchParamsList, numDevices, flags);
}
extern __host__ cudaError_t CUDARTAPI
cudaFuncSetCacheConfig(const void *func, enum cudaFuncCache cacheConfig) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const void *, enum cudaFuncCache);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaFuncSetCacheConfig");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(func, cacheConfig);
}
extern __host__ cudaError_t CUDARTAPI
cudaFuncSetSharedMemConfig(const void *func, enum cudaSharedMemConfig config) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const void *, enum cudaSharedMemConfig);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaFuncSetSharedMemConfig");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(func, config);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaFuncGetAttributes(struct cudaFuncAttributes *attr, const void *func) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(struct cudaFuncAttributes *, const void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaFuncGetAttributes");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(attr, func);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaFuncSetAttribute(const void *func, enum cudaFuncAttribute attr, int value) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const void *, enum cudaFuncAttribute, int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaFuncSetAttribute");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(func, attr, value);
}
extern __CUDA_DEPRECATED __host__ cudaError_t CUDARTAPI
cudaSetDoubleForDevice(double *d) {
using FuncPtr = cudaError_t(CUDARTAPI *)(double *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaSetDoubleForDevice");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(d);
}
extern __CUDA_DEPRECATED __host__ cudaError_t CUDARTAPI
cudaSetDoubleForHost(double *d) {
using FuncPtr = cudaError_t(CUDARTAPI *)(double *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaSetDoubleForHost");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(d);
}
extern __host__ cudaError_t CUDARTAPI cudaLaunchHostFunc(cudaStream_t stream,
cudaHostFn_t fn,
void *userData) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaStream_t, cudaHostFn_t, void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaLaunchHostFunc");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(stream, fn, userData);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaOccupancyMaxActiveBlocksPerMultiprocessor(int *numBlocks, const void *func,
int blockSize,
size_t dynamicSMemSize) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *, const void *, int, size_t);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaOccupancyMaxActiveBlocksPerMultiprocessor");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(numBlocks, func, blockSize, dynamicSMemSize);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags(int *numBlocks,
const void *func,
int blockSize,
size_t dynamicSMemSize,
unsigned int flags) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(int *, const void *, int, size_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>(
"cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(numBlocks, func, blockSize, dynamicSMemSize, flags);
}
extern __host__ cudaError_t CUDARTAPI
cudaConfigureCall(dim3 gridDim, dim3 blockDim, size_t sharedMem __dv(0),
cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(dim3, dim3, size_t, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaConfigureCall");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(gridDim, blockDim, sharedMem, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaSetupArgument(const void *arg,
size_t size,
size_t offset) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const void *, size_t, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaSetupArgument");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(arg, size, offset);
}
extern __host__ cudaError_t CUDARTAPI cudaLaunch(const void *func) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaLaunch");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(func);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI cudaMallocManaged(
void **devPtr, size_t size, unsigned int flags __dv(cudaMemAttachGlobal)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void **, size_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMallocManaged");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, size, flags);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaMalloc(void **devPtr, size_t size) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void **, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMalloc");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, size);
}
extern __host__ cudaError_t CUDARTAPI cudaMallocHost(void **ptr, size_t size) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void **, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMallocHost");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(ptr, size);
}
extern __host__ cudaError_t CUDARTAPI cudaMallocPitch(void **devPtr,
size_t *pitch,
size_t width,
size_t height) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void **, size_t *, size_t, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMallocPitch");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, pitch, width, height);
}
extern __host__ cudaError_t CUDARTAPI cudaMallocArray(
cudaArray_t *array, const struct cudaChannelFormatDesc *desc, size_t width,
size_t height __dv(0), unsigned int flags __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaArray_t *,
const struct cudaChannelFormatDesc *,
size_t, size_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMallocArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(array, desc, width, height, flags);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaFree(void *devPtr) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaFree");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr);
}
extern __host__ cudaError_t CUDARTAPI cudaFreeHost(void *ptr) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaFreeHost");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(ptr);
}
extern __host__ cudaError_t CUDARTAPI cudaFreeArray(cudaArray_t array) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaArray_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaFreeArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(array);
}
extern __host__ cudaError_t CUDARTAPI
cudaFreeMipmappedArray(cudaMipmappedArray_t mipmappedArray) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaMipmappedArray_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaFreeMipmappedArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(mipmappedArray);
}
extern __host__ cudaError_t CUDARTAPI cudaHostAlloc(void **pHost, size_t size,
unsigned int flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void **, size_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaHostAlloc");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pHost, size, flags);
}
extern __host__ cudaError_t CUDARTAPI cudaHostRegister(void *ptr, size_t size,
unsigned int flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, size_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaHostRegister");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(ptr, size, flags);
}
extern __host__ cudaError_t CUDARTAPI cudaHostUnregister(void *ptr) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaHostUnregister");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(ptr);
}
extern __host__ cudaError_t CUDARTAPI
cudaHostGetDevicePointer(void **pDevice, void *pHost, unsigned int flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void **, void *, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaHostGetDevicePointer");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pDevice, pHost, flags);
}
extern __host__ cudaError_t CUDARTAPI cudaHostGetFlags(unsigned int *pFlags,
void *pHost) {
using FuncPtr = cudaError_t(CUDARTAPI *)(unsigned int *, void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaHostGetFlags");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pFlags, pHost);
}
extern __host__ cudaError_t CUDARTAPI
cudaMalloc3D(struct cudaPitchedPtr *pitchedDevPtr, struct cudaExtent extent) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(struct cudaPitchedPtr *, struct cudaExtent);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMalloc3D");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pitchedDevPtr, extent);
}
extern __host__ cudaError_t CUDARTAPI
cudaMalloc3DArray(cudaArray_t *array, const struct cudaChannelFormatDesc *desc,
struct cudaExtent extent, unsigned int flags __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaArray_t *,
const struct cudaChannelFormatDesc *,
struct cudaExtent, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMalloc3DArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(array, desc, extent, flags);
}
extern __host__ cudaError_t CUDARTAPI cudaMallocMipmappedArray(
cudaMipmappedArray_t *mipmappedArray,
const struct cudaChannelFormatDesc *desc, struct cudaExtent extent,
unsigned int numLevels, unsigned int flags __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
cudaMipmappedArray_t *, const struct cudaChannelFormatDesc *,
struct cudaExtent, unsigned int, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMallocMipmappedArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(mipmappedArray, desc, extent, numLevels, flags);
}
extern __host__ cudaError_t CUDARTAPI cudaGetMipmappedArrayLevel(
cudaArray_t *levelArray, cudaMipmappedArray_const_t mipmappedArray,
unsigned int level) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
cudaArray_t *, cudaMipmappedArray_const_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetMipmappedArrayLevel");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(levelArray, mipmappedArray, level);
}
extern __host__ cudaError_t CUDARTAPI
cudaMemcpy3D(const struct cudaMemcpy3DParms *p) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const struct cudaMemcpy3DParms *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy3D");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(p);
}
extern __host__ cudaError_t CUDARTAPI
cudaMemcpy3DPeer(const struct cudaMemcpy3DPeerParms *p) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const struct cudaMemcpy3DPeerParms *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy3DPeer");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(p);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI cudaMemcpy3DAsync(
const struct cudaMemcpy3DParms *p, cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const struct cudaMemcpy3DParms *, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy3DAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(p, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpy3DPeerAsync(
const struct cudaMemcpy3DPeerParms *p, cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const struct cudaMemcpy3DPeerParms *,
cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy3DPeerAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(p, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaMemGetInfo(size_t *free,
size_t *total) {
using FuncPtr = cudaError_t(CUDARTAPI *)(size_t *, size_t *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemGetInfo");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(free, total);
}
extern __host__ cudaError_t CUDARTAPI
cudaArrayGetInfo(struct cudaChannelFormatDesc *desc, struct cudaExtent *extent,
unsigned int *flags, cudaArray_t array) {
using FuncPtr = cudaError_t(CUDARTAPI *)(struct cudaChannelFormatDesc *,
struct cudaExtent *, unsigned int *,
cudaArray_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaArrayGetInfo");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(desc, extent, flags, array);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpy(void *dst, const void *src,
size_t count,
enum cudaMemcpyKind kind) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, const void *, size_t,
enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, src, count, kind);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpyPeer(void *dst, int dstDevice,
const void *src,
int srcDevice,
size_t count) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(void *, int, const void *, int, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyPeer");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, dstDevice, src, srcDevice, count);
}
extern __host__ cudaError_t CUDARTAPI
cudaMemcpyToArray(cudaArray_t dst, size_t wOffset, size_t hOffset,
const void *src, size_t count, enum cudaMemcpyKind kind) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
cudaArray_t, size_t, size_t, const void *, size_t, enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyToArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, wOffset, hOffset, src, count, kind);
}
extern __host__ cudaError_t CUDARTAPI
cudaMemcpyFromArray(void *dst, cudaArray_const_t src, size_t wOffset,
size_t hOffset, size_t count, enum cudaMemcpyKind kind) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, cudaArray_const_t, size_t,
size_t, size_t, enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyFromArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, src, wOffset, hOffset, count, kind);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpyArrayToArray(
cudaArray_t dst, size_t wOffsetDst, size_t hOffsetDst,
cudaArray_const_t src, size_t wOffsetSrc, size_t hOffsetSrc, size_t count,
enum cudaMemcpyKind kind __dv(cudaMemcpyDeviceToDevice)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(cudaArray_t, size_t, size_t, cudaArray_const_t,
size_t, size_t, size_t, enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyArrayToArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, wOffsetDst, hOffsetDst, src, wOffsetSrc, hOffsetSrc,
count, kind);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpy2D(void *dst, size_t dpitch,
const void *src,
size_t spitch, size_t width,
size_t height,
enum cudaMemcpyKind kind) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, size_t, const void *, size_t,
size_t, size_t, enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy2D");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, dpitch, src, spitch, width, height, kind);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpy2DToArray(
cudaArray_t dst, size_t wOffset, size_t hOffset, const void *src,
size_t spitch, size_t width, size_t height, enum cudaMemcpyKind kind) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(cudaArray_t, size_t, size_t, const void *,
size_t, size_t, size_t, enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy2DToArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, wOffset, hOffset, src, spitch, width, height, kind);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpy2DFromArray(
void *dst, size_t dpitch, cudaArray_const_t src, size_t wOffset,
size_t hOffset, size_t width, size_t height, enum cudaMemcpyKind kind) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(void *, size_t, cudaArray_const_t, size_t,
size_t, size_t, size_t, enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy2DFromArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, dpitch, src, wOffset, hOffset, width, height, kind);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpy2DArrayToArray(
cudaArray_t dst, size_t wOffsetDst, size_t hOffsetDst,
cudaArray_const_t src, size_t wOffsetSrc, size_t hOffsetSrc, size_t width,
size_t height, enum cudaMemcpyKind kind __dv(cudaMemcpyDeviceToDevice)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaArray_t, size_t, size_t,
cudaArray_const_t, size_t, size_t,
size_t, size_t, enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy2DArrayToArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, wOffsetDst, hOffsetDst, src, wOffsetSrc, hOffsetSrc,
width, height, kind);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpyToSymbol(
const void *symbol, const void *src, size_t count, size_t offset __dv(0),
enum cudaMemcpyKind kind __dv(cudaMemcpyHostToDevice)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const void *, const void *, size_t,
size_t, enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyToSymbol");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(symbol, src, count, offset, kind);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpyFromSymbol(
void *dst, const void *symbol, size_t count, size_t offset __dv(0),
enum cudaMemcpyKind kind __dv(cudaMemcpyDeviceToHost)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, const void *, size_t, size_t,
enum cudaMemcpyKind);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyFromSymbol");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, symbol, count, offset, kind);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaMemcpyAsync(void *dst, const void *src, size_t count,
enum cudaMemcpyKind kind, cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, const void *, size_t,
enum cudaMemcpyKind, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, src, count, kind, stream);
}
extern __host__ cudaError_t CUDARTAPI
cudaMemcpyPeerAsync(void *dst, int dstDevice, const void *src, int srcDevice,
size_t count, cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, int, const void *, int,
size_t, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyPeerAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, dstDevice, src, srcDevice, count, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpyToArrayAsync(
cudaArray_t dst, size_t wOffset, size_t hOffset, const void *src,
size_t count, enum cudaMemcpyKind kind, cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(cudaArray_t, size_t, size_t, const void *,
size_t, enum cudaMemcpyKind, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyToArrayAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, wOffset, hOffset, src, count, kind, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpyFromArrayAsync(
void *dst, cudaArray_const_t src, size_t wOffset, size_t hOffset,
size_t count, enum cudaMemcpyKind kind, cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(void *, cudaArray_const_t, size_t, size_t,
size_t, enum cudaMemcpyKind, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyFromArrayAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, src, wOffset, hOffset, count, kind, stream);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI cudaMemcpy2DAsync(
void *dst, size_t dpitch, const void *src, size_t spitch, size_t width,
size_t height, enum cudaMemcpyKind kind, cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(void *, size_t, const void *, size_t, size_t,
size_t, enum cudaMemcpyKind, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy2DAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, dpitch, src, spitch, width, height, kind, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpy2DToArrayAsync(
cudaArray_t dst, size_t wOffset, size_t hOffset, const void *src,
size_t spitch, size_t width, size_t height, enum cudaMemcpyKind kind,
cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaArray_t, size_t, size_t,
const void *, size_t, size_t, size_t,
enum cudaMemcpyKind, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy2DToArrayAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, wOffset, hOffset, src, spitch, width, height, kind,
stream);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpy2DFromArrayAsync(
void *dst, size_t dpitch, cudaArray_const_t src, size_t wOffset,
size_t hOffset, size_t width, size_t height, enum cudaMemcpyKind kind,
cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, size_t, cudaArray_const_t,
size_t, size_t, size_t, size_t,
enum cudaMemcpyKind, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpy2DFromArrayAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, dpitch, src, wOffset, hOffset, width, height, kind,
stream);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpyToSymbolAsync(
const void *symbol, const void *src, size_t count, size_t offset,
enum cudaMemcpyKind kind, cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const void *, const void *, size_t, size_t,
enum cudaMemcpyKind, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyToSymbolAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(symbol, src, count, offset, kind, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaMemcpyFromSymbolAsync(
void *dst, const void *symbol, size_t count, size_t offset,
enum cudaMemcpyKind kind, cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, const void *, size_t, size_t,
enum cudaMemcpyKind, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemcpyFromSymbolAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(dst, symbol, count, offset, kind, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaMemset(void *devPtr, int value,
size_t count) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, int, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemset");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, value, count);
}
extern __host__ cudaError_t CUDARTAPI cudaMemset2D(void *devPtr, size_t pitch,
int value, size_t width,
size_t height) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, size_t, int, size_t, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemset2D");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, pitch, value, width, height);
}
extern __host__ cudaError_t CUDARTAPI cudaMemset3D(
struct cudaPitchedPtr pitchedDevPtr, int value, struct cudaExtent extent) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(struct cudaPitchedPtr, int, struct cudaExtent);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemset3D");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pitchedDevPtr, value, extent);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI cudaMemsetAsync(
void *devPtr, int value, size_t count, cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, int, size_t, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemsetAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, value, count, stream);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaMemset2DAsync(void *devPtr, size_t pitch, int value, size_t width,
size_t height, cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void *, size_t, int, size_t, size_t,
cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemset2DAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, pitch, value, width, height, stream);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaMemset3DAsync(struct cudaPitchedPtr pitchedDevPtr, int value,
struct cudaExtent extent, cudaStream_t stream __dv(0)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(struct cudaPitchedPtr, int,
struct cudaExtent, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemset3DAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pitchedDevPtr, value, extent, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaGetSymbolAddress(void **devPtr,
const void *symbol) {
using FuncPtr = cudaError_t(CUDARTAPI *)(void **, const void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetSymbolAddress");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, symbol);
}
extern __host__ cudaError_t CUDARTAPI cudaGetSymbolSize(size_t *size,
const void *symbol) {
using FuncPtr = cudaError_t(CUDARTAPI *)(size_t *, const void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetSymbolSize");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(size, symbol);
}
extern __host__ cudaError_t CUDARTAPI
cudaMemPrefetchAsync(const void *devPtr, size_t count, int dstDevice,
cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const void *, size_t, int, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemPrefetchAsync");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, count, dstDevice, stream);
}
extern __host__ cudaError_t CUDARTAPI
cudaMemAdvise(const void *devPtr, size_t count, enum cudaMemoryAdvise advice,
int device) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const void *, size_t,
enum cudaMemoryAdvise, int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemAdvise");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, count, advice, device);
}
extern __host__ cudaError_t CUDARTAPI cudaMemRangeGetAttribute(
void *data, size_t dataSize, enum cudaMemRangeAttribute attribute,
const void *devPtr, size_t count) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
void *, size_t, enum cudaMemRangeAttribute, const void *, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemRangeGetAttribute");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(data, dataSize, attribute, devPtr, count);
}
extern __host__ cudaError_t CUDARTAPI cudaMemRangeGetAttributes(
void **data, size_t *dataSizes, enum cudaMemRangeAttribute *attributes,
size_t numAttributes, const void *devPtr, size_t count) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(void **, size_t *, enum cudaMemRangeAttribute *,
size_t, const void *, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaMemRangeGetAttributes");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(data, dataSizes, attributes, numAttributes, devPtr, count);
}
extern __host__ cudaError_t CUDARTAPI cudaPointerGetAttributes(
struct cudaPointerAttributes *attributes, const void *ptr) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(struct cudaPointerAttributes *, const void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaPointerGetAttributes");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(attributes, ptr);
}
extern __host__ cudaError_t CUDARTAPI
cudaDeviceCanAccessPeer(int *canAccessPeer, int device, int peerDevice) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *, int, int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceCanAccessPeer");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(canAccessPeer, device, peerDevice);
}
extern __host__ cudaError_t CUDARTAPI
cudaDeviceEnablePeerAccess(int peerDevice, unsigned int flags) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceEnablePeerAccess");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(peerDevice, flags);
}
extern __host__ cudaError_t CUDARTAPI
cudaDeviceDisablePeerAccess(int peerDevice) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDeviceDisablePeerAccess");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(peerDevice);
}
extern __host__ cudaError_t CUDARTAPI
cudaGraphicsUnregisterResource(cudaGraphicsResource_t resource) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaGraphicsResource_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGraphicsUnregisterResource");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(resource);
}
extern __host__ cudaError_t CUDARTAPI cudaGraphicsResourceSetMapFlags(
cudaGraphicsResource_t resource, unsigned int flags) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(cudaGraphicsResource_t, unsigned int);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGraphicsResourceSetMapFlags");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(resource, flags);
}
extern __host__ cudaError_t CUDARTAPI cudaGraphicsMapResources(
int count, cudaGraphicsResource_t *resources, cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(int, cudaGraphicsResource_t *, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGraphicsMapResources");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(count, resources, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaGraphicsUnmapResources(
int count, cudaGraphicsResource_t *resources, cudaStream_t stream __dv(0)) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(int, cudaGraphicsResource_t *, cudaStream_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGraphicsUnmapResources");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(count, resources, stream);
}
extern __host__ cudaError_t CUDARTAPI cudaGraphicsResourceGetMappedPointer(
void **devPtr, size_t *size, cudaGraphicsResource_t resource) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(void **, size_t *, cudaGraphicsResource_t);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaGraphicsResourceGetMappedPointer");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(devPtr, size, resource);
}
extern __host__ cudaError_t CUDARTAPI cudaGraphicsSubResourceGetMappedArray(
cudaArray_t *array, cudaGraphicsResource_t resource,
unsigned int arrayIndex, unsigned int mipLevel) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
cudaArray_t *, cudaGraphicsResource_t, unsigned int, unsigned int);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaGraphicsSubResourceGetMappedArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(array, resource, arrayIndex, mipLevel);
}
extern __host__ cudaError_t CUDARTAPI
cudaGraphicsResourceGetMappedMipmappedArray(
cudaMipmappedArray_t *mipmappedArray, cudaGraphicsResource_t resource) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(cudaMipmappedArray_t *, cudaGraphicsResource_t);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaGraphicsResourceGetMappedMipmappedArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(mipmappedArray, resource);
}
extern __host__ cudaError_t CUDARTAPI cudaGetChannelDesc(
struct cudaChannelFormatDesc *desc, cudaArray_const_t array) {
using FuncPtr = cudaError_t(CUDARTAPI *)(struct cudaChannelFormatDesc *,
cudaArray_const_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetChannelDesc");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(desc, array);
}
extern __host__ cudaError_t CUDARTAPI cudaBindTexture(
size_t *offset, const struct textureReference *texref, const void *devPtr,
const struct cudaChannelFormatDesc *desc, size_t size __dv(UINT_MAX)) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
size_t *, const struct textureReference *, const void *,
const struct cudaChannelFormatDesc *, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaBindTexture");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(offset, texref, devPtr, desc, size);
}
extern __host__ cudaError_t CUDARTAPI
cudaBindTexture2D(size_t *offset, const struct textureReference *texref,
const void *devPtr, const struct cudaChannelFormatDesc *desc,
size_t width, size_t height, size_t pitch) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
size_t *, const struct textureReference *, const void *,
const struct cudaChannelFormatDesc *, size_t, size_t, size_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaBindTexture2D");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(offset, texref, devPtr, desc, width, height, pitch);
}
extern __host__ cudaError_t CUDARTAPI cudaBindTextureToArray(
const struct textureReference *texref, cudaArray_const_t array,
const struct cudaChannelFormatDesc *desc) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
const struct textureReference *, cudaArray_const_t,
const struct cudaChannelFormatDesc *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaBindTextureToArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(texref, array, desc);
}
extern __host__ cudaError_t CUDARTAPI
cudaBindTextureToMipmappedArray(const struct textureReference *texref,
cudaMipmappedArray_const_t mipmappedArray,
const struct cudaChannelFormatDesc *desc) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
const struct textureReference *, cudaMipmappedArray_const_t,
const struct cudaChannelFormatDesc *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaBindTextureToMipmappedArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(texref, mipmappedArray, desc);
}
extern __host__ cudaError_t CUDARTAPI
cudaUnbindTexture(const struct textureReference *texref) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const struct textureReference *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaUnbindTexture");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(texref);
}
extern __host__ cudaError_t CUDARTAPI cudaGetTextureAlignmentOffset(
size_t *offset, const struct textureReference *texref) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(size_t *, const struct textureReference *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetTextureAlignmentOffset");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(offset, texref);
}
extern __host__ cudaError_t CUDARTAPI cudaGetTextureReference(
const struct textureReference **texref, const void *symbol) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const struct textureReference **, const void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetTextureReference");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(texref, symbol);
}
extern __host__ cudaError_t CUDARTAPI cudaBindSurfaceToArray(
const struct surfaceReference *surfref, cudaArray_const_t array,
const struct cudaChannelFormatDesc *desc) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
const struct surfaceReference *, cudaArray_const_t,
const struct cudaChannelFormatDesc *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaBindSurfaceToArray");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(surfref, array, desc);
}
extern __host__ cudaError_t CUDARTAPI cudaGetSurfaceReference(
const struct surfaceReference **surfref, const void *symbol) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(const struct surfaceReference **, const void *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetSurfaceReference");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(surfref, symbol);
}
extern __host__ cudaError_t CUDARTAPI cudaCreateTextureObject(
cudaTextureObject_t *pTexObject, const struct cudaResourceDesc *pResDesc,
const struct cudaTextureDesc *pTexDesc,
const struct cudaResourceViewDesc *pResViewDesc) {
using FuncPtr = cudaError_t(CUDARTAPI *)(
cudaTextureObject_t *, const struct cudaResourceDesc *,
const struct cudaTextureDesc *, const struct cudaResourceViewDesc *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaCreateTextureObject");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pTexObject, pResDesc, pTexDesc, pResViewDesc);
}
extern __host__ cudaError_t CUDARTAPI
cudaDestroyTextureObject(cudaTextureObject_t texObject) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaTextureObject_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDestroyTextureObject");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(texObject);
}
extern __host__ cudaError_t CUDARTAPI cudaGetTextureObjectResourceDesc(
struct cudaResourceDesc *pResDesc, cudaTextureObject_t texObject) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(struct cudaResourceDesc *, cudaTextureObject_t);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaGetTextureObjectResourceDesc");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pResDesc, texObject);
}
extern __host__ cudaError_t CUDARTAPI cudaGetTextureObjectTextureDesc(
struct cudaTextureDesc *pTexDesc, cudaTextureObject_t texObject) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(struct cudaTextureDesc *, cudaTextureObject_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetTextureObjectTextureDesc");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pTexDesc, texObject);
}
extern __host__ cudaError_t CUDARTAPI cudaGetTextureObjectResourceViewDesc(
struct cudaResourceViewDesc *pResViewDesc, cudaTextureObject_t texObject) {
using FuncPtr = cudaError_t(CUDARTAPI *)(struct cudaResourceViewDesc *,
cudaTextureObject_t);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaGetTextureObjectResourceViewDesc");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pResViewDesc, texObject);
}
extern __host__ cudaError_t CUDARTAPI cudaCreateSurfaceObject(
cudaSurfaceObject_t *pSurfObject, const struct cudaResourceDesc *pResDesc) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaSurfaceObject_t *,
const struct cudaResourceDesc *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaCreateSurfaceObject");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pSurfObject, pResDesc);
}
extern __host__ cudaError_t CUDARTAPI
cudaDestroySurfaceObject(cudaSurfaceObject_t surfObject) {
using FuncPtr = cudaError_t(CUDARTAPI *)(cudaSurfaceObject_t);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDestroySurfaceObject");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(surfObject);
}
extern __host__ cudaError_t CUDARTAPI cudaGetSurfaceObjectResourceDesc(
struct cudaResourceDesc *pResDesc, cudaSurfaceObject_t surfObject) {
using FuncPtr =
cudaError_t(CUDARTAPI *)(struct cudaResourceDesc *, cudaSurfaceObject_t);
static auto func_ptr =
LoadSymbol<FuncPtr>("cudaGetSurfaceObjectResourceDesc");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(pResDesc, surfObject);
}
extern __host__ cudaError_t CUDARTAPI cudaDriverGetVersion(int *driverVersion) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaDriverGetVersion");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(driverVersion);
}
extern __host__ __cudart_builtin__ cudaError_t CUDARTAPI
cudaRuntimeGetVersion(int *runtimeVersion) {
using FuncPtr = cudaError_t(CUDARTAPI *)(int *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaRuntimeGetVersion");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(runtimeVersion);
}
extern __host__ cudaError_t CUDARTAPI cudaGetExportTable(
const void **ppExportTable, const cudaUUID_t *pExportTableId) {
using FuncPtr = cudaError_t(CUDARTAPI *)(const void **, const cudaUUID_t *);
static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetExportTable");
if (!func_ptr) return GetSymbolNotFoundError();
return func_ptr(ppExportTable, pExportTableId);
}
} // extern "C"
| [
"[email protected]"
] | |
544048b7383e4bcb591e51ea4fa889e5c5069dcb | 519ba257f91e55a03e54bbf69021dc18162d6af9 | /include/topo/MapArranger.h | 88f79817d11066365b3d5baaec9995b85b34176e | [] | no_license | wf-hahaha/topology_map | c433b86a91fe8971c4fb8ffaf78581b3f9e61de2 | b90343053285b996ac1c64b58c0f300ce18d760c | refs/heads/master | 2020-08-08T00:29:07.634223 | 2019-06-16T10:45:43 | 2019-06-16T10:45:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,524 | h | //
// Created by stumbo on 18-5-21.
//
#ifndef TOPOLOGY_MAP_MAPARRANGER_H
#define TOPOLOGY_MAP_MAPARRANGER_H
#include "TopoTools.h"
#include "MapCollection.h"
#include "NodeCollection.h"
/**
* @brief The surface class of the Topo map core
* contain a NodeCollection and a MapCollection.
*/
class MapArranger {
public:
// constructor of MapArranger, a name is required to assign name
explicit MapArranger(const std::string & mapName = topo::getCurrentTimeString());
// tell the core that we arrive at a new NodeInstance
void arriveInstance(NodeInstance *instance, gateId arriveAt, double odomX, double odomY,
double yaw);
// tell the core that the robot moves through a gate
void moveThroughGate(gateId gate);
// get the size of maps
size_t getMapNumbers();
// sort the maps according the confidence.
void sortByConfidence(size_t topCount = 0);
// input according to a JSON structure
bool readFromJSON(const JSobj & obj);
// input according to a JSON structure in string format
bool readFromStr(const std::string & str);
// convert the built possibile maps into JSON structure
JSobj toJS(size_t mapCount = 0);
// turn the whold map into a str in JSON format
string toString(size_t mapCount = 0);
// load the file according to the file name
bool reloadFromFile(const std::string & fileName);
// clean everything, data, ptrs
void selfClean();
size_t experienceNum() {
return experiences;
}
const string &getMapName() const {
return mapName;
}
void setMapName(const string & mapName) {
MapArranger::mapName = mapName;
}
const NodeCollection &getNodeCollection() const {
return nodeCollection;
}
MapCollection & getMapCollection() {
return mapCollection;
}
void addInstanceDirectly(NodeInstance * ins) {
nodeCollection.addInstanceDirectly(ins);
}
/// this is used for UI building mode
void addTopoNodeDirectly(TopoNode * node) {
mapCollection.addNodeDirectly(node);
}
void addTopoEdgeDirectly(TopoEdge * edge) {
mapCollection.addEdgeDirectly(edge);
}
private:
/// the NodeInstance that has moved through
size_t experiences = 0;
/// the NodeCollection
NodeCollection nodeCollection;
/// the MapCollection
MapCollection mapCollection;
/// name of the whole map
std::string mapName;
};
#endif //TOPOLOGY_MAP_MAPARRANGER_H
| [
"[email protected]"
] | |
47fae48be81c3d10684adbb71c3a8bea594df5d9 | a9f939815ee6dab0a892c03af8fbe6ea2b656c3d | /22 Static Cube Mapping/SkyEffect.cpp | bfaf227cd38b5e4858a9bb2ab2469b7937800c1e | [
"MIT"
] | permissive | CZZLEGEND/DirectX11-With-Windows-SDK | bb19fbf6dd350b1bd2a034f0f6329ec02d3495f6 | 8f5cd984d4c29688bd40d76fa897e0a0922a220f | refs/heads/master | 2020-05-15T22:41:45.830084 | 2019-04-18T13:54:04 | 2019-04-18T13:54:04 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,946 | cpp | #include "Effects.h"
#include "d3dUtil.h"
#include "EffectHelper.h" // 必须晚于Effects.h和d3dUtil.h包含
#include "DXTrace.h"
#include "Vertex.h"
using namespace DirectX;
using namespace std::experimental;
//
// SkyEffect::Impl 需要先于SkyEffect的定义
//
class SkyEffect::Impl : public AlignedType<SkyEffect::Impl>
{
public:
//
// 这些结构体对应HLSL的结构体。需要按16字节对齐
//
struct CBChangesEveryFrame
{
DirectX::XMMATRIX worldViewProj;
};
public:
// 必须显式指定
Impl() : m_IsDirty() {}
~Impl() = default;
public:
CBufferObject<0, CBChangesEveryFrame> m_CBFrame; // 每帧绘制的常量缓冲区
BOOL m_IsDirty; // 是否有值变更
std::vector<CBufferBase*> m_pCBuffers; // 统一管理上面所有的常量缓冲区
ComPtr<ID3D11VertexShader> m_pSkyVS;
ComPtr<ID3D11PixelShader> m_pSkyPS;
ComPtr<ID3D11InputLayout> m_pVertexPosLayout;
ComPtr<ID3D11ShaderResourceView> m_pTextureCube; // 天空盒纹理
};
//
// SkyEffect
//
namespace
{
// SkyEffect单例
static SkyEffect * g_pInstance = nullptr;
}
SkyEffect::SkyEffect()
{
if (g_pInstance)
throw std::exception("SkyEffect is a singleton!");
g_pInstance = this;
pImpl = std::make_unique<SkyEffect::Impl>();
}
SkyEffect::~SkyEffect()
{
}
SkyEffect::SkyEffect(SkyEffect && moveFrom) noexcept
{
pImpl.swap(moveFrom.pImpl);
}
SkyEffect & SkyEffect::operator=(SkyEffect && moveFrom) noexcept
{
pImpl.swap(moveFrom.pImpl);
return *this;
}
SkyEffect & SkyEffect::Get()
{
if (!g_pInstance)
throw std::exception("SkyEffect needs an instance!");
return *g_pInstance;
}
bool SkyEffect::InitAll(ComPtr<ID3D11Device> device)
{
if (!device)
return false;
if (!pImpl->m_pCBuffers.empty())
return true;
if (!RenderStates::IsInit())
throw std::exception("RenderStates need to be initialized first!");
ComPtr<ID3DBlob> blob;
// ******************
// 创建顶点着色器
//
HR(CreateShaderFromFile(L"HLSL\\Sky_VS.cso", L"HLSL\\Sky_VS.hlsl", "VS", "vs_5_0", blob.ReleaseAndGetAddressOf()));
HR(device->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, pImpl->m_pSkyVS.GetAddressOf()));
// 创建顶点布局
HR(device->CreateInputLayout(VertexPos::inputLayout, ARRAYSIZE(VertexPos::inputLayout),
blob->GetBufferPointer(), blob->GetBufferSize(), pImpl->m_pVertexPosLayout.GetAddressOf()));
// ******************
// 创建像素着色器
//
HR(CreateShaderFromFile(L"HLSL\\Sky_PS.cso", L"HLSL\\Sky_PS.hlsl", "PS", "ps_5_0", blob.ReleaseAndGetAddressOf()));
HR(device->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, pImpl->m_pSkyPS.GetAddressOf()));
pImpl->m_pCBuffers.assign({
&pImpl->m_CBFrame,
});
// 创建常量缓冲区
for (auto& pBuffer : pImpl->m_pCBuffers)
{
HR(pBuffer->CreateBuffer(device));
}
// 设置调试对象名
D3D11SetDebugObjectName(pImpl->m_pVertexPosLayout.Get(), "SkyEffect.VertexPosTexLayout");
D3D11SetDebugObjectName(pImpl->m_pCBuffers[0]->cBuffer.Get(), "SkyEffect.CBFrame");
D3D11SetDebugObjectName(pImpl->m_pSkyVS.Get(), "SkyEffect.Sky_VS");
D3D11SetDebugObjectName(pImpl->m_pSkyPS.Get(), "SkyEffect.Sky_PS");
return true;
}
void SkyEffect::SetRenderDefault(ComPtr<ID3D11DeviceContext> deviceContext)
{
deviceContext->IASetInputLayout(pImpl->m_pVertexPosLayout.Get());
deviceContext->VSSetShader(pImpl->m_pSkyVS.Get(), nullptr, 0);
deviceContext->PSSetShader(pImpl->m_pSkyPS.Get(), nullptr, 0);
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
deviceContext->GSSetShader(nullptr, nullptr, 0);
deviceContext->RSSetState(RenderStates::RSNoCull.Get());
deviceContext->PSSetSamplers(0, 1, RenderStates::SSLinearWrap.GetAddressOf());
deviceContext->OMSetDepthStencilState(RenderStates::DSSLessEqual.Get(), 0);
deviceContext->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF);
}
void XM_CALLCONV SkyEffect::SetWorldViewProjMatrix(DirectX::FXMMATRIX W, DirectX::CXMMATRIX V, DirectX::CXMMATRIX P)
{
auto& cBuffer = pImpl->m_CBFrame;
cBuffer.data.worldViewProj = XMMatrixTranspose(W * V * P);
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void XM_CALLCONV SkyEffect::SetWorldViewProjMatrix(DirectX::FXMMATRIX WVP)
{
auto& cBuffer = pImpl->m_CBFrame;
cBuffer.data.worldViewProj = XMMatrixTranspose(WVP);
pImpl->m_IsDirty = cBuffer.isDirty = true;
}
void SkyEffect::SetTextureCube(ComPtr<ID3D11ShaderResourceView> m_pTextureCube)
{
pImpl->m_pTextureCube = m_pTextureCube;
}
void SkyEffect::Apply(ComPtr<ID3D11DeviceContext> deviceContext)
{
auto& pCBuffers = pImpl->m_pCBuffers;
// 将缓冲区绑定到渲染管线上
pCBuffers[0]->BindVS(deviceContext);
// 设置SRV
deviceContext->PSSetShaderResources(0, 1, pImpl->m_pTextureCube.GetAddressOf());
if (pImpl->m_IsDirty)
{
pImpl->m_IsDirty = false;
for (auto& pCBuffer : pCBuffers)
{
pCBuffer->UpdateBuffer(deviceContext);
}
}
}
| [
"[email protected]"
] | |
62c4b7f9379fc4fa4e43890921cfd6bb8130fa81 | 3abe45130d4f614f68c6551b59014a20d3470b58 | /src/libzerocoin/CoinSpend.h | 2703c3b6f41b1b781429b6177e732e50f8a051ed | [
"MIT"
] | permissive | dre060/YAADI | faab94150263848ef16fe6a865cff7d2a7893e00 | cdb07c723f559ce883e33d64bce55b6ee5539142 | refs/heads/main | 2023-05-17T15:01:43.672809 | 2021-06-06T04:23:41 | 2021-06-06T04:23:41 | 374,243,648 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,157 | h | /**
* @file CoinSpend.h
*
* @brief CoinSpend class for the Zerocoin library.
*
* @author Ian Miers, Christina Garman and Matthew Green
* @date June 2013
*
* @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license This project is released under the MIT license.
**/
// Copyright (c) 2017-2018 The PIVX developers
// Copyright (c) 2018 The yaadi developers
#ifndef COINSPEND_H_
#define COINSPEND_H_
#include <streams.h>
#include <utilstrencodings.h>
#include "Accumulator.h"
#include "AccumulatorProofOfKnowledge.h"
#include "Coin.h"
#include "Commitment.h"
#include "Params.h"
#include "SerialNumberSignatureOfKnowledge.h"
#include "SpendType.h"
#include "bignum.h"
#include "pubkey.h"
#include "serialize.h"
namespace libzerocoin
{
/** The complete proof needed to spend a zerocoin.
* Composes together a proof that a coin is accumulated
* and that it has a given serial number.
*/
class CoinSpend
{
public:
//! \param paramsV1 - if this is a V1 zerocoin, then use params that existed with initial modulus, ignored otherwise
//! \param paramsV2 - params that begin when V2 zerocoins begin on the yaadi network
//! \param strm - a serialized CoinSpend
template <typename Stream>
CoinSpend(const ZerocoinParams* paramsV1, const ZerocoinParams* paramsV2, Stream& strm) :
accumulatorPoK(¶msV2->accumulatorParams),
serialNumberSoK(paramsV1),
commitmentPoK(¶msV1->serialNumberSoKCommitmentGroup, ¶msV2->accumulatorParams.accumulatorPoKCommitmentGroup)
{
Stream strmCopy = strm;
strm >> *this;
//Need to reset some parameters if v2
int serialVersion = ExtractVersionFromSerial(coinSerialNumber);
if (serialVersion >= PrivateCoin::PUBKEY_VERSION) {
accumulatorPoK = AccumulatorProofOfKnowledge(¶msV2->accumulatorParams);
serialNumberSoK = SerialNumberSignatureOfKnowledge(paramsV2);
commitmentPoK = CommitmentProofOfKnowledge(¶msV2->serialNumberSoKCommitmentGroup, ¶msV2->accumulatorParams.accumulatorPoKCommitmentGroup);
strmCopy >> *this;
}
}
/**Generates a proof spending a zerocoin.
*
* To use this, provide an unspent PrivateCoin, the latest Accumulator
* (e.g from the most recent Bitcoin block) containing the public part
* of the coin, a witness to that, and whatever medeta data is needed.
*
* Once constructed, this proof can be serialized and sent.
* It is validated simply be calling validate.
* @warning Validation only checks that the proof is correct
* @warning for the specified values in this class. These values must be validated
* Clients ought to check that
* 1) params is the right params
* 2) the accumulator actually is in some block
* 3) that the serial number is unspent
* 4) that the transaction
*
* @param p cryptographic parameters
* @param coin The coin to be spend
* @param a The current accumulator containing the coin
* @param witness The witness showing that the accumulator contains the coin
* @param a hash of the partial transaction that contains this coin spend
* @throw ZerocoinException if the process fails
*/
CoinSpend(const ZerocoinParams* paramsCoin, const ZerocoinParams* paramsAcc, const PrivateCoin& coin, Accumulator& a, const uint32_t& checksum,
const AccumulatorWitness& witness, const uint256& ptxHash, const SpendType& spendType);
/** Returns the serial number of the coin spend by this proof.
*
* @return the coin's serial number
*/
const CBigNum& getCoinSerialNumber() const { return this->coinSerialNumber; }
/**Gets the denomination of the coin spent in this proof.
*
* @return the denomination
*/
CoinDenomination getDenomination() const { return this->denomination; }
/**Gets the checksum of the accumulator used in this proof.
*
* @return the checksum
*/
uint32_t getAccumulatorChecksum() const { return this->accChecksum; }
/**Gets the txout hash used in this proof.
*
* @return the txout hash
*/
uint256 getTxOutHash() const { return ptxHash; }
CBigNum getAccCommitment() const { return accCommitmentToCoinValue; }
CBigNum getSerialComm() const { return serialCommitmentToCoinValue; }
uint8_t getVersion() const { return version; }
CPubKey getPubKey() const { return pubkey; }
SpendType getSpendType() const { return spendType; }
std::vector<unsigned char> getSignature() const { return vchSig; }
static std::vector<unsigned char> ParseSerial(CDataStream& s);
const uint256 signatureHash() const;
bool Verify(const Accumulator& a, bool verifyParams = true) const;
bool HasValidSerial(ZerocoinParams* params) const;
bool HasValidSignature() const;
CBigNum CalculateValidSerial(ZerocoinParams* params);
std::string ToString() const;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(denomination);
READWRITE(ptxHash);
READWRITE(accChecksum);
READWRITE(accCommitmentToCoinValue);
READWRITE(serialCommitmentToCoinValue);
READWRITE(coinSerialNumber);
READWRITE(accumulatorPoK);
READWRITE(serialNumberSoK);
READWRITE(commitmentPoK);
try {
READWRITE(version);
READWRITE(pubkey);
READWRITE(vchSig);
READWRITE(spendType);
} catch (...) {
version = 1;
}
}
private:
CoinDenomination denomination;
uint32_t accChecksum;
uint256 ptxHash;
CBigNum accCommitmentToCoinValue;
CBigNum serialCommitmentToCoinValue;
CBigNum coinSerialNumber;
AccumulatorProofOfKnowledge accumulatorPoK;
SerialNumberSignatureOfKnowledge serialNumberSoK;
CommitmentProofOfKnowledge commitmentPoK;
uint8_t version;
//As of version 2
CPubKey pubkey;
std::vector<unsigned char> vchSig;
SpendType spendType;
};
} /* namespace libzerocoin */
#endif /* COINSPEND_H_ */
| [
"[email protected]"
] | |
f14688f955dcb8529e8965429a10b9823d528cf2 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_3122_git-2.9.5.cpp | 4727ac2ac91cc346037eb90f52a9de25799f8511 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 474 | cpp | static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
{
#ifdef NO_IPV6
static char ip[INET_ADDRSTRLEN];
#else
static char ip[INET6_ADDRSTRLEN];
#endif
switch (family) {
#ifndef NO_IPV6
case AF_INET6:
inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
break;
#endif
case AF_INET:
inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
break;
default:
xsnprintf(ip, sizeof(ip), "<unknown>");
}
return ip;
} | [
"[email protected]"
] | |
8f17d4c79bd33f3695c48e9ea3bfacf0dc40ad81 | 4da928f16d1ca218332673dce24f7b9d694d98e2 | /ModelProcessor/ModelProcessor.cpp | 02466016e7b37e45f1479bb1bb8aa74a169894f5 | [] | no_license | haoxiner/PhantomSword | b7c92c86120ad0a149a4c9c53b94645f2a39f01e | f7c34b477f2be7cf1007e00bfd7cad34f7224989 | refs/heads/master | 2021-01-11T01:30:21.919340 | 2016-10-14T04:04:56 | 2016-10-14T04:04:56 | 70,698,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,525 | cpp |
#include <glm/gtc/matrix_transform.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <fstream>
#include <sstream>
#include <random>
#include <queue>
#include <map>
#include <vector>
#include <iostream>
glm::mat4 world2RootBone;
glm::mat4 rootBone2World;
std::vector<glm::mat4> *boneTransform;
std::map<std::string, int> boneMap;
std::vector<glm::mat4> *boneMatrix;
std::map<std::string, aiNodeAnim*> keyFrameMap;
glm::mat4 makeMat4FromMat4(aiMatrix4x4 m)
{
return glm::mat4(
m.a1, m.b1, m.c1, m.d1,
m.a2, m.b2, m.c2, m.d2,
m.a3, m.b3, m.c3, m.d3,
m.a4, m.b4, m.c4, m.d4);
}
glm::mat4 makeMat4FromMat3(aiMatrix3x3 m)
{
return glm::mat4(
m.a1, m.b1, m.c1, 0.0f,
m.a2, m.b2, m.c2, 0.0f,
m.a3, m.b3, m.c3, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
void exportTextures(aiScene *scene)
{
if (scene)
{
std::cout << "Number Of Meshes: " << scene->mNumMeshes << std::endl;
std::cout << scene->mNumTextures << std::endl;
for (int i = 0; i < scene->mNumTextures; i++)
{
std::string filename = "D:/";
std::ostringstream oss;
oss << i;
filename += oss.str();
filename += ".jpg";
std::ofstream file(filename, std::ios::binary);
file.write((char*)scene->mTextures[i]->pcData, scene->mTextures[i]->mWidth);
file.close();
}
}
}
void CalcMaxBonesPerVertex(aiScene *scene)
{
if (scene)
{
std::cout << "Number Of Meshes: " << scene->mNumMeshes << std::endl;
for (int i = 0; i < scene->mNumMeshes; i++)
{
auto mesh = scene->mMeshes[i];
std::map<int, int> total;
for (int j = 0; j < mesh->mNumBones; j++)
{
auto bone = mesh->mBones[j];
for (int k = 0; k < bone->mNumWeights; k++)
{
total[bone->mWeights[k].mVertexId]++;
}
}
int max = -1000;
for (auto p : total)
{
max = std::max(max, p.second);
}
std::cout << max << std::endl;
}
}
}
int main()
{
std::cout << "Input File Path: ";
std::string filepath;
while (std::cin >> filepath)
{
if (filepath == "q")
{
break;
}
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile(filepath, aiProcessPreset_TargetRealtime_Fast);
if (scene)
{
std::cout << "Number Of Meshes: " << scene->mNumMeshes << std::endl;
}
else
{
std::cout << "Failed To Read" << std::endl;
}
std::cout << "Input File Path: ";
}
return 0;
}
| [
"[email protected]"
] | |
3cc09499962ad2653f9a6883f589568270c3e842 | c51febc209233a9160f41913d895415704d2391f | /library/ATF/CParticle.hpp | c607c0b9f671196f08d6cb93bdd8ee54bbb6e6e3 | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 2,669 | hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <$3E60C3DACEF2E33FF1D1871D4F2565FA.hpp>
#include <CEntity.hpp>
#include <_PARTICLE_ELEMENT.hpp>
START_ATF_NAMESPACE
struct CParticle
{
char mEntityName[128];
int mNum;
_PARTICLE_ELEMENT *mElement;
CEntity *mEntity;
float mTotalTime;
float mLiveTime;
float mStartTimeRange;
float mTimeSpeed;
float mGravity[3];
float mStartPower[2][3];
float mStartScale[2];
float mStartZRot[2];
float mStartYRot[2];
char mFlickerAlpha;
float mFlickerTime;
float mStartARGB[4][2];
float mOnePerTimeEpsilon;
float mRotMat[4][4];
$3E60C3DACEF2E33FF1D1871D4F2565FA ___u18;
float mZFront;
float mEmitTime;
unsigned __int16 mSpecialID;
unsigned __int16 mTrackCnt;
float mTimeTrack[12];
char mTrackFlag[12];
char mATrack[12];
char mRTrack[12][2];
char mGTrack[12][2];
char mBTrack[12][2];
float mScaleTrack[12][2];
float mZRotTrack[12][2];
float mYRotTrack[12][2];
float mPowerTrack[12][2][3];
float mSpecialARGV[2][3];
void *mBsp;
unsigned int mFlag;
unsigned int mAlphaType;
float mStartPos[2][3];
float mCreatePos[3];
int mState;
float mOnePerTime;
float mOnePerTimeEpsilonTemp;
float mParticleTimer;
float mNextCreatorTime;
public:
void CheckCollision(int arg_0, float arg_1);
void CopyParticleToSaveParticle(struct _SAVE_PARTICLE* arg_0);
void CopySaveParticleToParticle(struct _SAVE_PARTICLE* arg_0);
void GetBBox(float* arg_0, float* arg_1);
void GetFlickerARGB(int arg_0, uint32_t* arg_1);
void GetPartcleStep(int arg_0, float arg_1);
uint32_t GetParticleState();
void InitElement(int arg_0, float arg_1);
void InitParticle();
int64_t LoadParticleSPT(char* arg_0, uint32_t arg_1);
int32_t Loop();
void ReInitParticle(int arg_0);
int32_t RealLoop();
void ReleaseEntity();
void ReleaseParticle();
void ResetOnePerTime();
void SetCreatePos(float* arg_0);
void SetParticleState(uint32_t arg_0);
void SetPreCalcParticle(uint32_t arg_0);
void SetStartBoxArea();
int32_t SpecialLoop();
int32_t SpecialLoop2();
~CParticle();
int64_t dtor_CParticle();
};
END_ATF_NAMESPACE
| [
"[email protected]"
] | |
01bbcf65cc6e259dbe884d2bc300c578f7da4183 | dbdb7a3e0726bd63dac553128a5ff046f76a7655 | /MFC/include/afxdlgs.inl | 327432fa7a76c350b65bb74497be863011a59bc1 | [] | no_license | 15831944/mfc-1 | f21c1aea2acfa489296ef33541792527c8778697 | 384c5b7199f8b20ef2f4f50c272c603a30426029 | refs/heads/master | 2022-02-21T19:29:35.812302 | 2019-10-18T14:40:11 | 2019-10-18T14:40:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,148 | inl | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
// Inlines for AFXDLGS.H
#pragma once
#ifdef _AFXDLGS_INLINE
// CCommonDialog
_AFXDLGS_INLINE CCommonDialog::CCommonDialog(CWnd* pParentWnd)
: CDialog((UINT)0, pParentWnd) { }
// CFileDialog
_AFXDLGS_INLINE BOOL CFileDialog::GetReadOnlyPref() const
{ return m_ofn.Flags & OFN_READONLY ? TRUE : FALSE; }
_AFXDLGS_INLINE void CFileDialog::SetTemplate(UINT nWin3ID, UINT nWin4ID)
{ SetTemplate(MAKEINTRESOURCE(nWin3ID), MAKEINTRESOURCE(nWin4ID)); }
_AFXDLGS_INLINE POSITION CFileDialog::GetStartPosition() const
{ return (POSITION)m_ofn.lpstrFile; }
// CFontDialog
_AFXDLGS_INLINE CString CFontDialog::GetFaceName() const
{ return (LPCTSTR)m_cf.lpLogFont->lfFaceName; }
_AFXDLGS_INLINE CString CFontDialog::GetStyleName() const
{ return m_cf.lpszStyle; }
_AFXDLGS_INLINE int CFontDialog::GetSize() const
{ return m_cf.iPointSize; }
_AFXDLGS_INLINE int CFontDialog::GetWeight() const
{ return (int)m_cf.lpLogFont->lfWeight; }
_AFXDLGS_INLINE BOOL CFontDialog::IsItalic() const
{ return m_cf.lpLogFont->lfItalic ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CFontDialog::IsStrikeOut() const
{ return m_cf.lpLogFont->lfStrikeOut ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CFontDialog::IsBold() const
{ return m_cf.lpLogFont->lfWeight == FW_BOLD ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CFontDialog::IsUnderline() const
{ return m_cf.lpLogFont->lfUnderline ? TRUE : FALSE; }
_AFXDLGS_INLINE COLORREF CFontDialog::GetColor() const
{ return m_cf.rgbColors; }
// CColorDialog
_AFXDLGS_INLINE COLORREF CColorDialog::GetColor() const
{ return m_cc.rgbResult; }
// CPrintDialog
_AFXDLGS_INLINE BOOL CPrintDialog::PrintSelection() const
{ return m_pd.Flags & PD_SELECTION ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CPrintDialog::PrintRange() const
{ return m_pd.Flags & PD_PAGENUMS ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CPrintDialog::PrintAll() const
{ return !PrintRange() && !PrintSelection() ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CPrintDialog::PrintCollate() const
{ return m_pd.Flags & PD_COLLATE ? TRUE : FALSE; }
_AFXDLGS_INLINE int CPrintDialog::GetFromPage() const
{ return (PrintRange() ? m_pd.nFromPage :-1); }
_AFXDLGS_INLINE int CPrintDialog::GetToPage() const
{ return (PrintRange() ? m_pd.nToPage :-1); }
_AFXDLGS_INLINE HDC CPrintDialog::GetPrinterDC() const
{ ASSERT_VALID(this);
ASSERT(m_pd.Flags & PD_RETURNDC);
return m_pd.hDC; }
// CPrintDialogEx
_AFXDLGS_INLINE BOOL CPrintDialogEx::PrintSelection() const
{ return m_pdex.Flags & PD_SELECTION ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CPrintDialogEx::PrintRange() const
{ return m_pdex.Flags & PD_PAGENUMS ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CPrintDialogEx::PrintCurrentPage() const
{ return m_pdex.Flags & PD_CURRENTPAGE ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CPrintDialogEx::PrintAll() const
{ return !PrintRange() && !PrintSelection() && !PrintCurrentPage() ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CPrintDialogEx::PrintCollate() const
{ return m_pdex.Flags & PD_COLLATE ? TRUE : FALSE; }
_AFXDLGS_INLINE HDC CPrintDialogEx::GetPrinterDC() const
{ ASSERT_VALID(this);
ASSERT(m_pdex.Flags & PD_RETURNDC);
return m_pdex.hDC; }
// CFindReplaceDialog
_AFXDLGS_INLINE BOOL CFindReplaceDialog::IsTerminating() const
{ return m_fr.Flags & FR_DIALOGTERM ? TRUE : FALSE ; }
_AFXDLGS_INLINE CString CFindReplaceDialog::GetReplaceString() const
{ return m_fr.lpstrReplaceWith; }
_AFXDLGS_INLINE CString CFindReplaceDialog::GetFindString() const
{ return m_fr.lpstrFindWhat; }
_AFXDLGS_INLINE BOOL CFindReplaceDialog::SearchDown() const
{ return m_fr.Flags & FR_DOWN ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CFindReplaceDialog::FindNext() const
{ return m_fr.Flags & FR_FINDNEXT ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CFindReplaceDialog::MatchCase() const
{ return m_fr.Flags & FR_MATCHCASE ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CFindReplaceDialog::MatchWholeWord() const
{ return m_fr.Flags & FR_WHOLEWORD ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CFindReplaceDialog::ReplaceCurrent() const
{ return m_fr. Flags & FR_REPLACE ? TRUE : FALSE; }
_AFXDLGS_INLINE BOOL CFindReplaceDialog::ReplaceAll() const
{ return m_fr.Flags & FR_REPLACEALL ? TRUE : FALSE; }
// CPropertySheet
_AFXDLGS_INLINE void CPropertySheet::MapDialogRect(LPRECT lpRect) const
{ ASSERT(::IsWindow(m_hWnd)); ::MapDialogRect(m_hWnd, lpRect); }
_AFXDLGS_INLINE CPropertyPage* CPropertySheet::GetPage(int nPage) const
{
CPropertyPage *pPage=STATIC_DOWNCAST(CPropertyPage, (CMyObject*)m_pages[nPage]);
ENSURE(pPage);
return pPage;
}
_AFXDLGS_INLINE void CPropertySheet::SetWizardMode()
{ m_psh.dwFlags |= PSH_WIZARD; }
_AFXDLGS_INLINE void CPropertySheet::SetFinishText(LPCTSTR lpszText)
{ ASSERT(::IsWindow(m_hWnd)); ::SendMessage(m_hWnd, PSM_SETFINISHTEXT, 0, (LPARAM)lpszText); }
_AFXDLGS_INLINE void CPropertySheet::SetWizardButtons(DWORD dwFlags)
{ ASSERT(::IsWindow(m_hWnd)); ::PostMessage(m_hWnd, PSM_SETWIZBUTTONS, 0, dwFlags); }
_AFXDLGS_INLINE CTabCtrl* CPropertySheet::GetTabControl() const
{ ASSERT(::IsWindow(m_hWnd)); return (CTabCtrl*)CWnd::FromHandle(
(HWND)::SendMessage(m_hWnd, PSM_GETTABCONTROL, 0, 0)); }
_AFXDLGS_INLINE void CPropertySheet::PressButton(int nButton)
{
ASSERT(::IsWindow(m_hWnd));
if (nButton == PSBTN_FINISH)
m_nModalResult = ID_WIZFINISH;
::SendMessage(m_hWnd, PSM_PRESSBUTTON, nButton, 0);
}
_AFXDLGS_INLINE BOOL CPropertySheet::IsWizard() const
{ return (m_psh.dwFlags & (PSH_WIZARD | PSH_WIZARD97)) != 0; }
_AFXDLGS_INLINE BOOL CPropertySheet::IsModeless() const
{ return m_bModeless; }
// CPageSetupDialog
_AFXDLGS_INLINE CSize CPageSetupDialog::GetPaperSize() const
{ return CSize(m_psd.ptPaperSize.x, m_psd.ptPaperSize.y); }
/////////////////////////////////////////////////////////////////////////////
#endif //_AFXDLGS_INLINE
| [
"[email protected]"
] | |
6323da1020a7ca9d197772b263ef365db5374c88 | 598275f974f5947c906773c0fd07bff798b09513 | /chap2_1/problem2_1.cpp | a90fd839a5c6db58e3433442be91474ae3b7a20a | [] | no_license | AkkyOrz/opengl_practice | a6c2f2c67b059a784d7f026631fb33aca8f88d6d | 4e410171a83b8ff718ce45cf1f9191c723f4294c | refs/heads/master | 2020-04-04T00:43:31.920225 | 2018-11-28T18:22:18 | 2018-11-28T18:22:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,056 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#define WINDOW_X (500)
#define WINDOW_Y (500)
#define WINDOW_NAME "test1"
void init_GL(int argc, char *argv[]);
void init();
void set_callback_functions();
void glut_display();
void glut_keyboard(unsigned char key, int x, int y);
void draw_square1();
void draw_square2();
void draw_square3();
void draw_hexagon();
void draw_polygon();
// グローバル変数
int g_display_mode = 1;
int g_num = 6;
int main(int argc, char *argv[]){
/* OpenGLの初期化 */
init_GL(argc, argv);
/* このプログラム特有の初期化 */
init();
/* コールバック関数の登録 */
set_callback_functions();
/* メインループ */
glutMainLoop(); // 無限ループ。コールバック関数が呼ばれるまでずっと実行される。
return 0;
}
void init_GL(int argc, char *argv[]){
glutInit(&argc, argv); // OpenGLの初期化
glutInitDisplayMode(GLUT_RGBA); // ディスプレイモードをRGBAモードに設定
glutInitWindowSize(WINDOW_X, WINDOW_Y); // ウィンドウサイズを指定
glutCreateWindow(WINDOW_NAME); // ウィンドウを「生成」。まだ「表示」はされない。
}
void init(){
glClearColor(0.0, 0.0, 0.0, 0.0); // 背景の塗りつぶし色を指定
}
void set_callback_functions(){
glutDisplayFunc(glut_display); // ディスプレイに変化があった時に呼ばれるコールバック関数を登録
glutKeyboardFunc(glut_keyboard); // キーボードに変化があった時に呼び出されるコールバック関数を登録
}
// キーボードに変化があった時に呼び出されるコールバック関数。
void glut_keyboard(unsigned char key, int x, int y){
switch(key){
case 'q':
case 'Q':
case '\033': // Escキーのこと
exit(0);
case '1':
g_display_mode = 1;
break;
case '2':
g_display_mode = 2;
break;
case '3':
g_display_mode = 3;
break;
case '4':
g_display_mode = 4;
break;
case '5':
g_display_mode = 5;
break;
case 'n':
g_num++;
g_display_mode = 5;
break;
case 'b':
if (g_num <= 3) {
g_display_mode = 5;
break;
}
g_num--;
g_display_mode = 5;
break;
}
glutPostRedisplay(); // 「ディスプレイのコールバック関数を呼んで」と指示する。
}
// ディスプレイに変化があった時に呼び出されるコールバック関数。
// 「ディスプレイに変化があった時」は、glutPostRedisplay() で指示する。
void glut_display(){
glClear(GL_COLOR_BUFFER_BIT); // 今まで画面に描かれていたものを消す
switch(g_display_mode){
case 1:
draw_square1();
break;
case 2:
draw_square2();
break;
case 3:
draw_square3();
break;
case 4:
draw_hexagon();
break;
case 5:
draw_polygon();
break;
}
glFlush(); // ここで画面に描画をする
}
void draw_square1(){
glBegin(GL_LINE_LOOP);
glColor3d(1.0, 0.0, 0.0);
glVertex2d(-0.9, -0.9);
glVertex2d(0.9, -0.9);
glVertex2d(0.9, 0.9);
glVertex2d(-0.9, 0.9);
glEnd();
}
void draw_square2(){
glBegin(GL_POLYGON);
glColor3d(1.0, 0.0, 0.0);
glVertex2d(-0.9, -0.9);
glVertex2d(0.9, -0.9);
glVertex2d(0.9, 0.9);
glVertex2d(-0.9, 0.9);
glEnd();
}
void draw_square3(){
glBegin(GL_POLYGON);
glColor3d(1.0, 0.0, 0.0);
glVertex2d(-0.9, -0.9);
glColor3d(1.0, 1.0, 0.0);
glVertex2d(0.9, -0.9);
glColor3d(0.0, 1.0, 1.0);
glVertex2d(0.9, 0.9);
glColor3d(0.0, 0.0, 0.0);
glVertex2d(-0.9, 0.9);
glEnd();
}
void draw_hexagon(){
glBegin(GL_LINE_LOOP);
glColor3d(1.0, 0.0, 0.0);
for (int i = 0; i < 6; i++){
glVertex2d(cos(2*M_PI*i/6.0), sin(2*M_PI*i/6.0));
}
glEnd();
}
void draw_polygon(){
glBegin(GL_LINE_LOOP);
glColor3d(1.0, 0.0, 0.0);
for (int i = 0; i < g_num; i++){
glVertex2d(cos(2*M_PI*i/(double)(g_num)), sin(2*M_PI*i/(double)(g_num)));
}
glEnd();
}
| [
"[email protected]"
] | |
40ee8ca3f59fe5d89c3f9e32f0e32766257d8aaa | 4d9cee8c67af579fa10bf132a9e79bcbaf094bee | /jisuanke/焦作网络赛2018 G.Give Candies | 大数.cpp | a112f4892ea0cf91f6b349d673c0d83170dc1356 | [] | no_license | FeiiYin/acm | 3e886bba5aa40471d869c4f3d69e3afcb9fce944 | 29ac440ca6456e134b75c3fae90608676f162680 | refs/heads/master | 2022-11-08T04:11:38.614436 | 2020-06-16T09:12:33 | 2020-06-16T09:12:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,659 | cpp | #include<iostream>
#include<string>
#include<iomanip>
#include<cstring>
#include<algorithm>
using namespace std;
#define MAXN 9999
#define MAXSIZE 10
#define DLEN 4
class BigNum
{
private:
int a[100005]; //可以控制大数的位数
int len; //大数长度
public:
BigNum(){ len = 1;memset(a,0,sizeof(a)); } //构造函数
BigNum(const int); //将一个int类型的变量转化为大数
BigNum(const char*); //将一个字符串类型的变量转化为大数
BigNum(const BigNum &); //拷贝构造函数
BigNum &operator=(const BigNum &); //重载赋值运算符,大数之间进行赋值运算
friend istream& operator>>(istream&, BigNum&); //重载输入运算符
friend ostream& operator<<(ostream&, BigNum&); //重载输出运算符
BigNum operator+(const BigNum &) const; //重载加法运算符,两个大数之间的相加运算
BigNum operator-(const BigNum &) const; //重载减法运算符,两个大数之间的相减运算
BigNum operator*(const BigNum &) const; //重载乘法运算符,两个大数之间的相乘运算
BigNum operator/(const int &) const; //重载除法运算符,大数对一个整数进行相除运算
BigNum operator^(const int &) const; //大数的n次方运算
long long operator%(const long long &) const; //大数对一个int类型的变量进行取模运算
bool operator>(const BigNum & T)const; //大数和另一个大数的大小比较
bool operator>(const int & t)const; //大数和一个int类型的变量的大小比较
void print(); //输出大数
};
BigNum::BigNum(const int b) //将一个int类型的变量转化为大数
{
int c,d = b;
len = 0;
memset(a,0,sizeof(a));
while(d > MAXN)
{
c = d - (d / (MAXN + 1)) * (MAXN + 1);
d = d / (MAXN + 1);
a[len++] = c;
}
a[len++] = d;
}
BigNum::BigNum(const char*s) //将一个字符串类型的变量转化为大数
{
int t,k,index,l,i;
memset(a,0,sizeof(a));
l=strlen(s);
len=l/DLEN;
if(l%DLEN)
len++;
index=0;
for(i=l-1;i>=0;i-=DLEN)
{
t=0;
k=i-DLEN+1;
if(k<0)
k=0;
for(int j=k;j<=i;j++)
t=t*10+s[j]-'0';
a[index++]=t;
}
}
BigNum::BigNum(const BigNum & T) : len(T.len) //拷贝构造函数
{
int i;
memset(a,0,sizeof(a));
for(i = 0 ; i < len ; i++)
a[i] = T.a[i];
}
BigNum & BigNum::operator=(const BigNum & n) //重载赋值运算符,大数之间进行赋值运算
{
int i;
len = n.len;
memset(a,0,sizeof(a));
for(i = 0 ; i < len ; i++)
a[i] = n.a[i];
return *this;
}
istream& operator>>(istream & in, BigNum & b) //重载输入运算符
{
char ch[MAXSIZE*4];
int i = -1;
in>>ch;
int l=strlen(ch);
int count=0,sum=0;
for(i=l-1;i>=0;)
{
sum = 0;
int t=1;
for(int j=0;j<4&&i>=0;j++,i--,t*=10)
{
sum+=(ch[i]-'0')*t;
}
b.a[count]=sum;
count++;
}
b.len =count++;
return in;
}
ostream& operator<<(ostream& out, BigNum& b) //重载输出运算符
{
int i;
cout << b.a[b.len - 1];
for(i = b.len - 2 ; i >= 0 ; i--)
{
cout.width(DLEN);
cout.fill('0');
cout << b.a[i];
}
return out;
}
BigNum BigNum::operator+(const BigNum & T) const //两个大数之间的相加运算
{
BigNum t(*this);
int i,big; //位数
big = T.len > len ? T.len : len;
for(i = 0 ; i < big ; i++)
{
t.a[i] +=T.a[i];
if(t.a[i] > MAXN)
{
t.a[i + 1]++;
t.a[i] -=MAXN+1;
}
}
if(t.a[big] != 0)
t.len = big + 1;
else
t.len = big;
return t;
}
BigNum BigNum::operator-(const BigNum & T) const //两个大数之间的相减运算
{
int i,j,big;
bool flag;
BigNum t1,t2;
if(*this>T)
{
t1=*this;
t2=T;
flag=0;
}
else
{
t1=T;
t2=*this;
flag=1;
}
big=t1.len;
for(i = 0 ; i < big ; i++)
{
if(t1.a[i] < t2.a[i])
{
j = i + 1;
while(t1.a[j] == 0)
j++;
t1.a[j--]--;
while(j > i)
t1.a[j--] += MAXN;
t1.a[i] += MAXN + 1 - t2.a[i];
}
else
t1.a[i] -= t2.a[i];
}
t1.len = big;
while(t1.a[len - 1] == 0 && t1.len > 1)
{
t1.len--;
big--;
}
if(flag)
t1.a[big-1]=0-t1.a[big-1];
return t1;
}
BigNum BigNum::operator*(const BigNum & T) const //两个大数之间的相乘运算
{
BigNum ret;
int i,j,up;
int temp,temp1;
for(i = 0 ; i < len ; i++)
{
up = 0;
for(j = 0 ; j < T.len ; j++)
{
temp = a[i] * T.a[j] + ret.a[i + j] + up;
if(temp > MAXN)
{
temp1 = temp - temp / (MAXN + 1) * (MAXN + 1);
up = temp / (MAXN + 1);
ret.a[i + j] = temp1;
}
else
{
up = 0;
ret.a[i + j] = temp;
}
}
if(up != 0)
ret.a[i + j] = up;
}
ret.len = i + j;
while(ret.a[ret.len - 1] == 0 && ret.len > 1)
ret.len--;
return ret;
}
BigNum BigNum::operator/(const int & b) const //大数对一个整数进行相除运算
{
BigNum ret;
int i,down = 0;
for(i = len - 1 ; i >= 0 ; i--)
{
ret.a[i] = (a[i] + down * (MAXN + 1)) / b;
down = a[i] + down * (MAXN + 1) - ret.a[i] * b;
}
ret.len = len;
while(ret.a[ret.len - 1] == 0 && ret.len > 1)
ret.len--;
return ret;
}
long long BigNum::operator %(const long long & b) const //大数对一个int类型的变量进行取模运算
{
long long i,d=0;
for (i = len-1; i>=0; i--)
{
d = ((d * (MAXN+1))% b + a[i])% b;
}
return d;
}
BigNum BigNum::operator^(const int & n) const //大数的n次方运算
{
BigNum t,ret(1);
int i;
if(n<0)
exit(-1);
if(n==0)
return 1;
if(n==1)
return *this;
int m=n;
while(m>1)
{
t=*this;
for( i=1;i<<1<=m;i<<=1)
{
t=t*t;
}
m-=i;
ret=ret*t;
if(m==1)
ret=ret*(*this);
}
return ret;
}
bool BigNum::operator>(const BigNum & T) const //大数和另一个大数的大小比较
{
int ln;
if(len > T.len)
return true;
else if(len == T.len)
{
ln = len - 1;
while(a[ln] == T.a[ln] && ln >= 0)
ln--;
if(ln >= 0 && a[ln] > T.a[ln])
return true;
else
return false;
}
else
return false;
}
bool BigNum::operator >(const int & t) const //大数和一个int类型的变量的大小比较
{
BigNum b(t);
return *this>b;
}
void BigNum::print() //输出大数
{
int i;
cout << a[len - 1];
for(i = len - 2 ; i >= 0 ; i--)
{
cout.width(DLEN);
cout.fill('0');
cout << a[i];
}
cout << endl;
}
long long powmod(long long a, long long n, long long mod) {
long long ans = 1;
while(n) {
if(n&1) ans=ans*a%mod;
n/=2;
a=a*a%mod;
}
return ans%mod;
}
char s[100005];
int main(void)
{
int T; scanf("%d",&T);
while(T--) {
scanf("%s",s);
BigNum a(s);
a = a-1;
long long n = a % (1000000006);
long long ans = powmod(2ll,n,1000000007);
cout<<ans<<endl;
}
}
| [
"[email protected]"
] | |
329c24d73b74c4d245d0cebe3faafd4e24528070 | 0749035f5d77a182155efca5aff2f1cfe1da8cc6 | /HACKER/implementation/dyn_programming/fibonacci/point.cpp | 9cf1da6147e3b7d010deaebdbcc3b7406f26e262 | [] | no_license | anandkodnani/C- | a291025604a8d37e50bd3e9bdd99d2a95eedcd79 | 635e517a7ae31d70b531f611867f40fa34a4f575 | refs/heads/master | 2021-01-10T13:48:56.042453 | 2016-01-29T20:11:38 | 2016-01-29T20:11:38 | 50,384,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | cpp | #include <iostream>
using namespace std;
class Point {
public:
Point() {
x = 0;
y = 0;
}
Point(int a, int b) {
x = a;
y = b;
}
Point operator++ () {
this->x += 2;
this->y += 2;
return *this;
}
void print() {
cout << x << "\n";
cout << y << "\n";
}
Point(const Point &other) {
x = other.x;
y = other.y;
}
private:
int x, y;
};
int main() {
Point a(1, 2);
++a;
Point b(a);
a.print();
b.print();
// cout << a;
return 0;
}
return sqrt(a*a + b*b);
| [
"[email protected]"
] | |
803181e892b899739cb5585571c378d874a71e7f | 370055a10fe4061c0dfd35869adec252d1465b8d | /src/util/tsv.hpp | 3ba37048755876a9e7dde23be1a8712be9c68b54 | [
"MIT"
] | permissive | ssameerr/pytubes | badeeab7394493e66bf9f2ed01e3094b4acd4a14 | 6b4a839b7503780930b667cf12053089bc66c027 | refs/heads/master | 2022-12-24T05:01:57.195522 | 2018-04-03T11:50:01 | 2018-04-03T11:50:01 | 128,112,099 | 0 | 0 | MIT | 2021-09-06T18:41:35 | 2018-04-04T19:36:47 | C++ | UTF-8 | C++ | false | false | 3,325 | hpp | #pragma once
#include <cstdio>
#include <vector>
#include "error.hpp"
#include "slice.hpp"
#include "array.hpp"
#include "../bytes.hpp"
#include "skiplist.hpp"
namespace ss {
struct TsvHeader;
struct TsvRow;
struct TsvValueIter {
ByteSlice row;
ByteSlice cur;
TsvValueIter(ByteSlice row) : row(row) {
cur = row.slice_to_ptr(row.find_first('\t'));
}
inline void operator++() {
if (cur.end() == row.end()) {
row = ByteSlice::Null();
cur = ByteSlice::Null();
} else {
row = row.slice_from(cur.len+1);
cur = row.slice_to_ptr(row.find_first('\t'));
}
}
inline ByteSlice operator*() const {
return cur;
}
inline bool operator==(const TsvValueIter &other) const {
return row.is(other.row);
}
inline bool operator!=(const TsvValueIter &other) const {
return !row.is(other.row);
}
};
struct TsvRow{
using iterator = TsvValueIter;
using const_iterator = const TsvValueIter;
ByteSlice row;
TsvHeader *header;
TsvRow() {}
TsvRow(ByteSlice row, TsvHeader *header) : row(row), header(header) {}
inline iterator begin() const { return iterator(row); }
inline iterator end() const { return iterator(ByteSlice::Null()); }
inline void populate_slots(SkipList<ByteSlice> &skips) const {
auto value = begin();
for (auto &skip : skips) {
size_t to_skip = skip.skip;
while(to_skip--){
++value;
if (value == end()) { return; }
}
*(skip.destination) = *value;
}
}
};
struct TsvHeader {
Array<ByteSlice> fields;
Array<ByteString> stored_fields;
bool have_headers = false;
void read(TsvRow &row) {
std::vector<ByteString> field_vec;
throw_if(ValueError, have_headers, "Trying to read header row, but already have headers");
for (auto val : row) {
field_vec.emplace_back(val);
}
stored_fields = field_vec;
fields = Array<ByteSlice>(stored_fields.size);
std::transform(stored_fields.begin(), stored_fields.end(), fields.begin(), [](ByteString &x){ return ByteSlice(x); });
have_headers = true;
}
SkipList<ByteSlice> make_skip_list(const Array<ByteSlice> &out_fields, const Array<ByteSlice> &slots) {
SkipList<ByteSlice> skips;
throw_if(ValueError, out_fields.size != slots.size, "Tried to apply TSV header with incorrect values");
throw_if(ValueError, !have_headers, "Tried to apply uninitialized TSV header");
// This is N*M, but /probably/ doesn't matter, I'm happy to be wrong about this
size_t last_header_index = 0;
for (size_t header_index = 0; header_index < stored_fields.size; ++header_index){
for (size_t slot_index = 0; slot_index < slots.size; ++slot_index){
auto &out_field = out_fields[slot_index];
if (out_field == fields[header_index]) {
size_t skip = header_index - last_header_index;
skips.emplace_back(skip, &slots[slot_index]);
last_header_index = header_index;
break;
}
}
}
return skips;
}
};
} | [
"[email protected]"
] | |
473fece814385a61af1a4af2080df68dec9b253b | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/make/hunk_429.cpp | 71712558b7e2ca4938ebcdff5e821ab927040082 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 878 | cpp | return 1;
}
- open ("SAVEDOS" . $default_output_stack_level . "out", ">&STDOUT")
- || &error ("ado: $! duping STDOUT\n", 1);
- open ("SAVEDOS" . $default_output_stack_level . "err", ">&STDERR")
- || &error ("ado: $! duping STDERR\n", 1);
+ my $dup = undef;
+ open($dup, '>&', STDOUT) or error("ado: $! duping STDOUT\n", 1);
+ push @OUTSTACK, $dup;
- open (STDOUT, "> " . $filename)
- || &error ("ado: $filename: $!\n", 1);
- open (STDERR, ">&STDOUT")
- || &error ("ado: $filename: $!\n", 1);
+ open($dup, '>&', STDERR) or error("ado: $! duping STDERR\n", 1);
+ push @ERRSTACK, $dup;
- $default_output_stack_level++;
+ open(STDOUT, '>', $filename) or error("ado: $filename: $!\n", 1);
+ open(STDERR, ">&STDOUT") or error("ado: $filename: $!\n", 1);
}
# close the current stdout/stderr, and restore the previous ones from
| [
"[email protected]"
] | |
944291ef5a86d52d5046eb8698db75d1e097aa3d | c9abbbfd1ccdbdf75c5b35b28c841b6fc8165ee6 | /AtCoder/Contestant/Exca/test.cpp | 949e40a4ad0507954bf6f59293f98d24341b1a54 | [] | no_license | kanade9/kyopro | 8d9b12a4da2353595836cf68066e2b425379990b | 3b5d998b99603c4473dc22e62252a2dd5ba143c2 | refs/heads/master | 2023-04-20T15:18:37.199790 | 2021-05-19T17:49:16 | 2021-05-19T17:49:16 | 175,988,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | #include <iostream>
using namespace std;
int main(){
int n, sum=0;
cin >> n;
for (int i=0 ; i<n ; i++){
int a;
cin >> a;
sum += a;
}
cout << sum << endl;
return 0;
} | [
"[email protected]"
] | |
2154786977cf2dbc77c851f6f38ccd65aa2f06f6 | 2cb88f7a2499a718c6cc31bb93a143ba4c1bbc91 | /LinkedList.cpp | efa6c27118e4ec731fdd08b1972400457d13aee1 | [] | no_license | famu/LinkedList_CPP | f4ed2e8bfe171621ef255d09cb0bc87d0ce7e438 | 9426f7ad94b43eb112f6fdaddb51f21a349bd430 | refs/heads/master | 2016-08-04T10:36:25.273971 | 2015-03-23T02:56:30 | 2015-03-23T02:56:30 | 32,705,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,610 | cpp | /*
* LinkedList.cpp
*
* Created on: oct 14, 2013
* Author: Faisal
*/
#include <iostream>
using namespace std;
struct Node { int data; Node* next; };
/*To add a node at the end of existing list.*/
void append(struct Node *head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;
Node *cur = head;
while(cur)
{
if(cur->next == NULL)
{
cur->next = newNode;
return;
}
cur = cur->next;
}
}
/*creating a linked list with one node.*/
void initialize(struct Node *head,int n){
head->data = n;
head->next =NULL;
}
/**/
void addTail(struct Node **head, int n)
{
Node *newNode = new Node;
newNode->data = n;
newNode->next = *head;
*head = newNode;
}
struct Node *search(struct Node *head, int n) {
Node *cur = head;
while(cur)
{
if(cur->data == n)
return cur;
cur = cur->next;
}
cout << "No Node " << n << " in list.\n";
}
bool delete(struct Node **head, Node *ptrDel)
{
Node *cur = *head; if(ptrDel == *head)
{
*head = cur->next;
delete ptrDel;
return true;
}
while(cur) {
if(cur->next == ptrDel)
{
cur->next = ptrDel->next;
delete ptrDel; return true;
}
cur = cur->next;
}
return false;
}
/* reverse the list */
struct Node* reverse(struct Node** head) {
Node *parent = *head;
Node *me = parent->next;
Node *child = me->next;
/* make parent as tail */
parent->next = NULL;
while(child) { me->next = parent; parent = me;
me = child; child = child->next;
} me->next = parent;
*head = me;
return *head;
}
/* Creating a copy of a linked list */
void cloneList(struct Node *node, struct Node **pNew) {
if(node != NULL)
{ *pNew = new Node;
(*pNew)->data = node->data;
(*pNew)->next = NULL;
cloneList(node->next, &((*pNew)->next));
}
}
/* Compare two linked list */
/* return value: same(1), different(0) */
int compareList(struct Node *node1, struct Node *node2)
{
static int flag;
/* both lists are NULL */
if(node1 == NULL && node2 == NULL)
{
flag = 1;
}
else {
if(node1 == NULL || node2 == NULL)
flag = 0;
else if(node1->data != node2->data)
flag = 0;
else compareList(node1->next, node2->next);
}
return flag;
}
void deleteList(struct Node **node)
{
struct Node *tmpNode;
while(*node) { tmpNode = *node;
*node = tmpNode->next;
delete tmpNode;
}
}
void display(struct Node *head) {
Node *list = head;
while(list) {
cout << list->data << " ";
list = list->next;
}
cout << endl; cout << endl;
}
int main() { struct Node *newHead;
struct Node *head = new Node;
initialize(head,45); display(head);
append(head,18); display(head);
append(head,91); display(head);
append(head,73); display(head);
append(head,4); display(head);
addTail(&head,1); display(head);
int delNum = 5;
Node *ptrDelete = search(head,delNum);
if(delete(&head,ptrDelete))
cout << "Comparing lists\n";
cout << "Are the two lists same?\n";
if(compareList(head,newHead))
cout << "Yes, they are same!\n";
else cout << "No, they are different!\n";
cout << endl;
cout << "Node "<< delNum << " deleted!\n";
display(head);
cout << "Copying List\n";
cloneList(head,&newHead);
display(newHead);
cout << "reversed List\n";
reverse(&head);
display(head);
delNum = 73;
ptrDelete = search(newHead,delNum);
if(delete(&newHead,ptrDelete)) {
cout << "Node "<< delNum << " deleted!\n";
cout << "New list after deletion\n";
display(newHead);
}
cout << "Comparing the two lists again...\n";
cout << "Are the two lists same?\n";
if(compareList(head,newHead))
cout << "Yes, they are same!\n";
else cout << "No, they are different!\n";
cout << endl;
cout << "Deleting the copied list\n";
deleteList(&newHead);
display(newHead);
return 0;
}
#endif /* LINKEDLIST_H_ */
| [
"[email protected]"
] | |
b3dca6bf5e2d54295830d166b9d10857466bf5ca | 41eff316a4c252dbb71441477a7354c9b192ba41 | /src/PhysX/physx/source/foundation/include/PsHashInternals.h | 8ff9d67073c2d689afecb773a82e76bc6248d3c9 | [] | no_license | erwincoumans/pybullet_physx | 40615fe8502cf7d7a5e297032fc4af62dbdd0821 | 70f3e11ad7a1e854d4f51992edd1650bbe4ac06a | refs/heads/master | 2021-07-01T08:02:54.367317 | 2020-10-22T21:43:34 | 2020-10-22T21:43:34 | 183,939,616 | 21 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 18,323 | h | //
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PSFOUNDATION_PSHASHINTERNALS_H
#define PSFOUNDATION_PSHASHINTERNALS_H
#include "PsBasicTemplates.h"
#include "PsArray.h"
#include "PsBitUtils.h"
#include "PsHash.h"
#include "foundation/PxIntrinsics.h"
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4127) // conditional expression is constant
#endif
namespace physx
{
namespace shdfnd
{
namespace internal
{
template <class Entry, class Key, class HashFn, class GetKey, class Allocator, bool compacting>
class HashBase : private Allocator
{
void init(uint32_t initialTableSize, float loadFactor)
{
mBuffer = NULL;
mEntries = NULL;
mEntriesNext = NULL;
mHash = NULL;
mEntriesCapacity = 0;
mHashSize = 0;
mLoadFactor = loadFactor;
mFreeList = uint32_t(EOL);
mTimestamp = 0;
mEntriesCount = 0;
if(initialTableSize)
reserveInternal(initialTableSize);
}
public:
typedef Entry EntryType;
HashBase(uint32_t initialTableSize = 64, float loadFactor = 0.75f) : Allocator(PX_DEBUG_EXP("hashBase"))
{
init(initialTableSize, loadFactor);
}
HashBase(uint32_t initialTableSize, float loadFactor, const Allocator& alloc) : Allocator(alloc)
{
init(initialTableSize, loadFactor);
}
HashBase(const Allocator& alloc) : Allocator(alloc)
{
init(64, 0.75f);
}
~HashBase()
{
destroy(); // No need to clear()
if(mBuffer)
Allocator::deallocate(mBuffer);
}
static const uint32_t EOL = 0xffffffff;
PX_INLINE Entry* create(const Key& k, bool& exists)
{
uint32_t h = 0;
if(mHashSize)
{
h = hash(k);
uint32_t index = mHash[h];
while(index != EOL && !HashFn().equal(GetKey()(mEntries[index]), k))
index = mEntriesNext[index];
exists = index != EOL;
if(exists)
return mEntries + index;
}
else
exists = false;
if(freeListEmpty())
{
grow();
h = hash(k);
}
uint32_t entryIndex = freeListGetNext();
mEntriesNext[entryIndex] = mHash[h];
mHash[h] = entryIndex;
mEntriesCount++;
mTimestamp++;
return mEntries + entryIndex;
}
PX_INLINE const Entry* find(const Key& k) const
{
if(!mEntriesCount)
return NULL;
const uint32_t h = hash(k);
uint32_t index = mHash[h];
while(index != EOL && !HashFn().equal(GetKey()(mEntries[index]), k))
index = mEntriesNext[index];
return index != EOL ? mEntries + index : NULL;
}
PX_INLINE bool erase(const Key& k, Entry& e)
{
if(!mEntriesCount)
return false;
const uint32_t h = hash(k);
uint32_t* ptr = mHash + h;
while(*ptr != EOL && !HashFn().equal(GetKey()(mEntries[*ptr]), k))
ptr = mEntriesNext + *ptr;
if(*ptr == EOL)
return false;
PX_PLACEMENT_NEW(&e, Entry)(mEntries[*ptr]);
return eraseInternal(ptr);
}
PX_INLINE bool erase(const Key& k)
{
if(!mEntriesCount)
return false;
const uint32_t h = hash(k);
uint32_t* ptr = mHash + h;
while(*ptr != EOL && !HashFn().equal(GetKey()(mEntries[*ptr]), k))
ptr = mEntriesNext + *ptr;
if(*ptr == EOL)
return false;
return eraseInternal(ptr);
}
PX_INLINE uint32_t size() const
{
return mEntriesCount;
}
PX_INLINE uint32_t capacity() const
{
return mHashSize;
}
void clear()
{
if(!mHashSize || mEntriesCount == 0)
return;
destroy();
intrinsics::memSet(mHash, EOL, mHashSize * sizeof(uint32_t));
const uint32_t sizeMinus1 = mEntriesCapacity - 1;
for(uint32_t i = 0; i < sizeMinus1; i++)
{
prefetchLine(mEntriesNext + i, 128);
mEntriesNext[i] = i + 1;
}
mEntriesNext[mEntriesCapacity - 1] = uint32_t(EOL);
mFreeList = 0;
mEntriesCount = 0;
}
void reserve(uint32_t size)
{
if(size > mHashSize)
reserveInternal(size);
}
PX_INLINE const Entry* getEntries() const
{
return mEntries;
}
PX_INLINE Entry* insertUnique(const Key& k)
{
PX_ASSERT(find(k) == NULL);
uint32_t h = hash(k);
uint32_t entryIndex = freeListGetNext();
mEntriesNext[entryIndex] = mHash[h];
mHash[h] = entryIndex;
mEntriesCount++;
mTimestamp++;
return mEntries + entryIndex;
}
private:
void destroy()
{
for(uint32_t i = 0; i < mHashSize; i++)
{
for(uint32_t j = mHash[i]; j != EOL; j = mEntriesNext[j])
mEntries[j].~Entry();
}
}
template <typename HK, typename GK, class A, bool comp>
PX_NOINLINE void copy(const HashBase<Entry, Key, HK, GK, A, comp>& other);
// free list management - if we're coalescing, then we use mFreeList to hold
// the top of the free list and it should always be equal to size(). Otherwise,
// we build a free list in the next() pointers.
PX_INLINE void freeListAdd(uint32_t index)
{
if(compacting)
{
mFreeList--;
PX_ASSERT(mFreeList == mEntriesCount);
}
else
{
mEntriesNext[index] = mFreeList;
mFreeList = index;
}
}
PX_INLINE void freeListAdd(uint32_t start, uint32_t end)
{
if(!compacting)
{
for(uint32_t i = start; i < end - 1; i++) // add the new entries to the free list
mEntriesNext[i] = i + 1;
// link in old free list
mEntriesNext[end - 1] = mFreeList;
PX_ASSERT(mFreeList != end - 1);
mFreeList = start;
}
else if(mFreeList == EOL) // don't reset the free ptr for the compacting hash unless it's empty
mFreeList = start;
}
PX_INLINE uint32_t freeListGetNext()
{
PX_ASSERT(!freeListEmpty());
if(compacting)
{
PX_ASSERT(mFreeList == mEntriesCount);
return mFreeList++;
}
else
{
uint32_t entryIndex = mFreeList;
mFreeList = mEntriesNext[mFreeList];
return entryIndex;
}
}
PX_INLINE bool freeListEmpty() const
{
if(compacting)
return mEntriesCount == mEntriesCapacity;
else
return mFreeList == EOL;
}
PX_INLINE void replaceWithLast(uint32_t index)
{
PX_PLACEMENT_NEW(mEntries + index, Entry)(mEntries[mEntriesCount]);
mEntries[mEntriesCount].~Entry();
mEntriesNext[index] = mEntriesNext[mEntriesCount];
uint32_t h = hash(GetKey()(mEntries[index]));
uint32_t* ptr;
for(ptr = mHash + h; *ptr != mEntriesCount; ptr = mEntriesNext + *ptr)
PX_ASSERT(*ptr != EOL);
*ptr = index;
}
PX_INLINE uint32_t hash(const Key& k, uint32_t hashSize) const
{
return HashFn()(k) & (hashSize - 1);
}
PX_INLINE uint32_t hash(const Key& k) const
{
return hash(k, mHashSize);
}
PX_INLINE bool eraseInternal(uint32_t* ptr)
{
const uint32_t index = *ptr;
*ptr = mEntriesNext[index];
mEntries[index].~Entry();
mEntriesCount--;
mTimestamp++;
if (compacting && index != mEntriesCount)
replaceWithLast(index);
freeListAdd(index);
return true;
}
void reserveInternal(uint32_t size)
{
if(!isPowerOfTwo(size))
size = nextPowerOfTwo(size);
PX_ASSERT(!(size & (size - 1)));
// decide whether iteration can be done on the entries directly
bool resizeCompact = compacting || freeListEmpty();
// define new table sizes
uint32_t oldEntriesCapacity = mEntriesCapacity;
uint32_t newEntriesCapacity = uint32_t(float(size) * mLoadFactor);
uint32_t newHashSize = size;
// allocate new common buffer and setup pointers to new tables
uint8_t* newBuffer;
uint32_t* newHash;
uint32_t* newEntriesNext;
Entry* newEntries;
{
uint32_t newHashByteOffset = 0;
uint32_t newEntriesNextBytesOffset = newHashByteOffset + newHashSize * sizeof(uint32_t);
uint32_t newEntriesByteOffset = newEntriesNextBytesOffset + newEntriesCapacity * sizeof(uint32_t);
newEntriesByteOffset += (16 - (newEntriesByteOffset & 15)) & 15;
uint32_t newBufferByteSize = newEntriesByteOffset + newEntriesCapacity * sizeof(Entry);
newBuffer = reinterpret_cast<uint8_t*>(Allocator::allocate(newBufferByteSize, __FILE__, __LINE__));
PX_ASSERT(newBuffer);
newHash = reinterpret_cast<uint32_t*>(newBuffer + newHashByteOffset);
newEntriesNext = reinterpret_cast<uint32_t*>(newBuffer + newEntriesNextBytesOffset);
newEntries = reinterpret_cast<Entry*>(newBuffer + newEntriesByteOffset);
}
// initialize new hash table
intrinsics::memSet(newHash, uint32_t(EOL), newHashSize * sizeof(uint32_t));
// iterate over old entries, re-hash and create new entries
if(resizeCompact)
{
// check that old free list is empty - we don't need to copy the next entries
PX_ASSERT(compacting || mFreeList == EOL);
for(uint32_t index = 0; index < mEntriesCount; ++index)
{
uint32_t h = hash(GetKey()(mEntries[index]), newHashSize);
newEntriesNext[index] = newHash[h];
newHash[h] = index;
PX_PLACEMENT_NEW(newEntries + index, Entry)(mEntries[index]);
mEntries[index].~Entry();
}
}
else
{
// copy old free list, only required for non compact resizing
intrinsics::memCopy(newEntriesNext, mEntriesNext, mEntriesCapacity * sizeof(uint32_t));
for(uint32_t bucket = 0; bucket < mHashSize; bucket++)
{
uint32_t index = mHash[bucket];
while(index != EOL)
{
uint32_t h = hash(GetKey()(mEntries[index]), newHashSize);
newEntriesNext[index] = newHash[h];
PX_ASSERT(index != newHash[h]);
newHash[h] = index;
PX_PLACEMENT_NEW(newEntries + index, Entry)(mEntries[index]);
mEntries[index].~Entry();
index = mEntriesNext[index];
}
}
}
// swap buffer and pointers
Allocator::deallocate(mBuffer);
mBuffer = newBuffer;
mHash = newHash;
mHashSize = newHashSize;
mEntriesNext = newEntriesNext;
mEntries = newEntries;
mEntriesCapacity = newEntriesCapacity;
freeListAdd(oldEntriesCapacity, newEntriesCapacity);
}
void grow()
{
PX_ASSERT((mFreeList == EOL) || (compacting && (mEntriesCount == mEntriesCapacity)));
uint32_t size = mHashSize == 0 ? 16 : mHashSize * 2;
reserve(size);
}
uint8_t* mBuffer;
Entry* mEntries;
uint32_t* mEntriesNext; // same size as mEntries
uint32_t* mHash;
uint32_t mEntriesCapacity;
uint32_t mHashSize;
float mLoadFactor;
uint32_t mFreeList;
uint32_t mTimestamp;
uint32_t mEntriesCount; // number of entries
public:
class Iter
{
public:
PX_INLINE Iter(HashBase& b) : mBucket(0), mEntry(uint32_t(b.EOL)), mTimestamp(b.mTimestamp), mBase(b)
{
if(mBase.mEntriesCapacity > 0)
{
mEntry = mBase.mHash[0];
skip();
}
}
PX_INLINE void check() const
{
PX_ASSERT(mTimestamp == mBase.mTimestamp);
}
PX_INLINE const Entry& operator*() const
{
check();
return mBase.mEntries[mEntry];
}
PX_INLINE Entry& operator*()
{
check();
return mBase.mEntries[mEntry];
}
PX_INLINE const Entry* operator->() const
{
check();
return mBase.mEntries + mEntry;
}
PX_INLINE Entry* operator->()
{
check();
return mBase.mEntries + mEntry;
}
PX_INLINE Iter operator++()
{
check();
advance();
return *this;
}
PX_INLINE Iter operator++(int)
{
check();
Iter i = *this;
advance();
return i;
}
PX_INLINE bool done() const
{
check();
return mEntry == mBase.EOL;
}
private:
PX_INLINE void advance()
{
mEntry = mBase.mEntriesNext[mEntry];
skip();
}
PX_INLINE void skip()
{
while(mEntry == mBase.EOL)
{
if(++mBucket == mBase.mHashSize)
break;
mEntry = mBase.mHash[mBucket];
}
}
Iter& operator=(const Iter&);
uint32_t mBucket;
uint32_t mEntry;
uint32_t mTimestamp;
HashBase& mBase;
};
/*!
Iterate over entries in a hash base and allow entry erase while iterating
*/
class EraseIterator
{
public:
PX_INLINE EraseIterator(HashBase& b): mBase(b)
{
reset();
}
PX_INLINE Entry* eraseCurrentGetNext(bool eraseCurrent)
{
if(eraseCurrent && mCurrentEntryIndexPtr)
{
mBase.eraseInternal(mCurrentEntryIndexPtr);
// if next was valid return the same ptr, if next was EOL search new hash entry
if(*mCurrentEntryIndexPtr != mBase.EOL)
return mBase.mEntries + *mCurrentEntryIndexPtr;
else
return traverseHashEntries();
}
// traverse mHash to find next entry
if(mCurrentEntryIndexPtr == NULL)
return traverseHashEntries();
const uint32_t index = *mCurrentEntryIndexPtr;
if(mBase.mEntriesNext[index] == mBase.EOL)
{
return traverseHashEntries();
}
else
{
mCurrentEntryIndexPtr = mBase.mEntriesNext + index;
return mBase.mEntries + *mCurrentEntryIndexPtr;
}
}
PX_INLINE void reset()
{
mCurrentHashIndex = 0;
mCurrentEntryIndexPtr = NULL;
}
private:
PX_INLINE Entry* traverseHashEntries()
{
mCurrentEntryIndexPtr = NULL;
while (mCurrentEntryIndexPtr == NULL && mCurrentHashIndex < mBase.mHashSize)
{
if (mBase.mHash[mCurrentHashIndex] != mBase.EOL)
{
mCurrentEntryIndexPtr = mBase.mHash + mCurrentHashIndex;
mCurrentHashIndex++;
return mBase.mEntries + *mCurrentEntryIndexPtr;
}
else
{
mCurrentHashIndex++;
}
}
return NULL;
}
EraseIterator& operator=(const EraseIterator&);
private:
uint32_t* mCurrentEntryIndexPtr;
uint32_t mCurrentHashIndex;
HashBase& mBase;
};
};
template <class Entry, class Key, class HashFn, class GetKey, class Allocator, bool compacting>
template <typename HK, typename GK, class A, bool comp>
PX_NOINLINE void
HashBase<Entry, Key, HashFn, GetKey, Allocator, compacting>::copy(const HashBase<Entry, Key, HK, GK, A, comp>& other)
{
reserve(other.mEntriesCount);
for(uint32_t i = 0; i < other.mEntriesCount; i++)
{
for(uint32_t j = other.mHash[i]; j != EOL; j = other.mEntriesNext[j])
{
const Entry& otherEntry = other.mEntries[j];
bool exists;
Entry* newEntry = create(GK()(otherEntry), exists);
PX_ASSERT(!exists);
PX_PLACEMENT_NEW(newEntry, Entry)(otherEntry);
}
}
}
template <class Key, class HashFn, class Allocator = typename AllocatorTraits<Key>::Type, bool Coalesced = false>
class HashSetBase
{
PX_NOCOPY(HashSetBase)
public:
struct GetKey
{
PX_INLINE const Key& operator()(const Key& e)
{
return e;
}
};
typedef HashBase<Key, Key, HashFn, GetKey, Allocator, Coalesced> BaseMap;
typedef typename BaseMap::Iter Iterator;
HashSetBase(uint32_t initialTableSize, float loadFactor, const Allocator& alloc)
: mBase(initialTableSize, loadFactor, alloc)
{
}
HashSetBase(const Allocator& alloc) : mBase(64, 0.75f, alloc)
{
}
HashSetBase(uint32_t initialTableSize = 64, float loadFactor = 0.75f) : mBase(initialTableSize, loadFactor)
{
}
bool insert(const Key& k)
{
bool exists;
Key* e = mBase.create(k, exists);
if(!exists)
PX_PLACEMENT_NEW(e, Key)(k);
return !exists;
}
PX_INLINE bool contains(const Key& k) const
{
return mBase.find(k) != 0;
}
PX_INLINE bool erase(const Key& k)
{
return mBase.erase(k);
}
PX_INLINE uint32_t size() const
{
return mBase.size();
}
PX_INLINE uint32_t capacity() const
{
return mBase.capacity();
}
PX_INLINE void reserve(uint32_t size)
{
mBase.reserve(size);
}
PX_INLINE void clear()
{
mBase.clear();
}
protected:
BaseMap mBase;
};
template <class Key, class Value, class HashFn, class Allocator = typename AllocatorTraits<Pair<const Key, Value> >::Type>
class HashMapBase
{
PX_NOCOPY(HashMapBase)
public:
typedef Pair<const Key, Value> Entry;
struct GetKey
{
PX_INLINE const Key& operator()(const Entry& e)
{
return e.first;
}
};
typedef HashBase<Entry, Key, HashFn, GetKey, Allocator, true> BaseMap;
typedef typename BaseMap::Iter Iterator;
typedef typename BaseMap::EraseIterator EraseIterator;
HashMapBase(uint32_t initialTableSize, float loadFactor, const Allocator& alloc)
: mBase(initialTableSize, loadFactor, alloc)
{
}
HashMapBase(const Allocator& alloc) : mBase(64, 0.75f, alloc)
{
}
HashMapBase(uint32_t initialTableSize = 64, float loadFactor = 0.75f) : mBase(initialTableSize, loadFactor)
{
}
bool insert(const Key /*&*/ k, const Value /*&*/ v)
{
bool exists;
Entry* e = mBase.create(k, exists);
if(!exists)
PX_PLACEMENT_NEW(e, Entry)(k, v);
return !exists;
}
Value& operator[](const Key& k)
{
bool exists;
Entry* e = mBase.create(k, exists);
if(!exists)
PX_PLACEMENT_NEW(e, Entry)(k, Value());
return e->second;
}
PX_INLINE const Entry* find(const Key& k) const
{
return mBase.find(k);
}
PX_INLINE bool erase(const Key& k)
{
return mBase.erase(k);
}
PX_INLINE bool erase(const Key& k, Entry& e)
{
return mBase.erase(k, e);
}
PX_INLINE uint32_t size() const
{
return mBase.size();
}
PX_INLINE uint32_t capacity() const
{
return mBase.capacity();
}
PX_INLINE Iterator getIterator()
{
return Iterator(mBase);
}
PX_INLINE EraseIterator getEraseIterator()
{
return EraseIterator(mBase);
}
PX_INLINE void reserve(uint32_t size)
{
mBase.reserve(size);
}
PX_INLINE void clear()
{
mBase.clear();
}
protected:
BaseMap mBase;
};
}
} // namespace shdfnd
} // namespace physx
#if PX_VC
#pragma warning(pop)
#endif
#endif // #ifndef PSFOUNDATION_PSHASHINTERNALS_H
| [
"[email protected]"
] | |
42003c8535fd445dab347d25b7878bff53ae1e58 | 6dae6b4944430a97aeac743723ce98a325648b13 | /chap16/Exer16_48.cpp | 0f964cf8bc5c4a052cdac0e167c8bc58e2533963 | [] | no_license | donjohnnie/CPP_Primer | 139749158d67fa32d0179eef70551cd9ff2107c5 | 97cdd7b222cbbac3a050b66c7f077cb56f9163d9 | refs/heads/master | 2021-01-21T02:55:50.114408 | 2016-07-23T15:19:41 | 2016-07-23T15:19:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | cpp | #include <iostream>
#include <string>
#include "Exer16_48_debug_rep.h"
using std::cout;
using std::endl;
using std::string;
int main()
{
string s("hi");
const string *sp = &s;
char a[] = "How are you?";
char *p = a;
cout << debug_rep(s) << "\n" << endl; // call debug_rep(const string&)
cout << debug_rep(sp) << "\n" << endl; // call debug_rep(T*), instantiated to debug_rep(const string*)
cout << debug_rep("hi world!") << "\n" << endl; // call debug_rep(const char*)
cout << debug_rep(p) << endl; // call debug_rep(char*)
return 0;
} | [
"[email protected]"
] | |
bd3eddc461ecf313c3e198263bb0b59ffbb0c298 | 4c8b65c9372da593b8966578781cffd225e78d23 | /src/targets/gpu/device/asinh.cpp | 0ddb9446f1e61dd0df91a63188fe6d887e0851ca | [
"MIT"
] | permissive | pfultz2/AMDMIGraphX | 1969702ae845cc16c4a64fd82457799885836fcc | 1dd4e4d9d871222eb957cfb1505cc4ddfed89aa9 | refs/heads/develop | 2023-02-05T22:45:50.332911 | 2020-12-19T21:45:52 | 2020-12-19T21:45:52 | 325,127,362 | 0 | 0 | NOASSERTION | 2020-12-28T22:11:43 | 2020-12-28T22:10:32 | null | UTF-8 | C++ | false | false | 477 | cpp | #include <migraphx/gpu/device/asinh.hpp>
#include <migraphx/gpu/device/nary.hpp>
#include <migraphx/gpu/device/types.hpp>
namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace gpu {
namespace device {
void asinh(hipStream_t stream, const argument& result, const argument& arg)
{
nary(stream, result, arg)([](auto x) { return ::asinh(to_hip_type(x)); });
}
} // namespace device
} // namespace gpu
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx
| [
"[email protected]"
] | |
346a13bc0d77659d5b580c88f4227a114ddfc1d0 | 93f547a11085f5e2fa4f756257c7a1148fd5cbd2 | /Geo4Engine/ExturbatorRequests.cpp | 84ded079563bedbeea5dd742ea57732b3ca7ec55 | [] | no_license | houseofbits/Geo4.2_Exturbator | f61dfb96856c9a60a4fa48fba352ca69ce3c25be | 30da27618b8342f0398895b2a8e9c04ef1037ac0 | refs/heads/master | 2020-04-29T07:13:53.313231 | 2019-05-10T11:54:05 | 2019-05-10T11:54:05 | 175,944,635 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,776 | cpp | #include "Geo4.h"
CLASS_DECLARATION(ExturbatorRequests);
ExturbatorRequests::ExturbatorRequests() : winderState(), statusResponseEXT()
{
}
ExturbatorRequests::~ExturbatorRequests()
{
}
void ExturbatorRequests::Initialise(EventManager*const event_manager, ResourceManager*const resourceManager)
{
Hardware* hw = getParent<Hardware>();
event_manager->RegisterEventHandler(this);
event_manager->RegisterEventReceiver(this, &ExturbatorRequests::OnWindowEvent);
statusResponseEXT.transmitPacket = new CommandDataPacket("EXTRBEXT", PacketClassEnumerator::COMMAND);
statusResponseEXT.transmitPacket->setPayload(CommandOutStructure{ GET_STATUS });
statusResponseEXT.responsePacket = new StatusDataPacket(PacketClassEnumerator::STATUS);
if(hw)hw->RegisterRequest(&statusResponseEXT);
statusResponseEXT.commit();
/*
statusResponseWND.transmitPacket = new CommandDataPacket("EXTRBWND", PacketClassEnumerator::COMMAND);
statusResponseWND.transmitPacket->setPayload(CommandOutStructure{ GET_STATUS });
statusResponseWND.responsePacket = new StatusDataPacket(PacketClassEnumerator::STATUS);
if(hw)hw->RegisterRequest(&statusResponseWND);
statusResponsePUL.transmitPacket = new CommandDataPacket("EXTRBPUL", PacketClassEnumerator::COMMAND);
statusResponsePUL.transmitPacket->setPayload(CommandOutStructure{ GET_STATUS });
statusResponsePUL.responsePacket = new StatusDataPacket(PacketClassEnumerator::STATUS);
if(hw)hw->RegisterRequest(&statusResponsePUL);
statusResponseWND.commit();
statusResponsePUL.commit();
*/
}
void ExturbatorRequests::Deserialize(CFONode* node)
{
Entity::Deserialize(node);
}
bool ExturbatorRequests::OnWindowEvent(WindowEvent*const event) {
Hardware* hw = getParent<Hardware>();
if (!hw)return 1;
if (statusResponseEXT.isFinished()
&& statusResponseEXT.isError()
&& statusResponseEXT.error == BasePacketRequest::RESPONSE_TIMEOUT) {
hw->DetectPorts();
if (hw->IsOpen()) {
statusResponseEXT.commit();
}
}
//Request status packet again
if (statusResponseEXT.isCompleted()) {
hw->setPortValid(true);
statusResponseEXT.commit();
}
/*
if (processResponseEXT.isCompleted()){
extruderSpeed = processResponseEXT.receivePacket->speed;
processResponseEXT.commit();
}
if (processResponsePUL.isCompleted()){
diameter.x = processResponseEXT.receivePacket->diameter1;
diameter.y = processResponseEXT.receivePacket->diameter2;
processResponsePUL.commit();
}
pullerSpeed = calculatePullerSpeedFromExtruder();
winderSpeed = calculateWinderSpeedFromExtruder();
setPullerState(pullerState, pullerSpeed);
setWinderState(winderState, winderSpeed);
*/
return 1;
}
void ExturbatorRequests::setExtruderState(bool state, float speed) {
//if(stateCommandEXT.isCompleted()){
//stateCommandEXT.transmitPacket->setPayload(StateOutStructure{state, speed});
//stateCommandEXT.commit();
//}
}
void ExturbatorRequests::setPullerState(bool state, float speed) {
//if(stateCommandPUL.isCompleted()){
//stateCommandPUL.transmitPacket->setPayload(StateOutStructure{state, speed});
//stateCommandPUL.commit();
//}
}
void ExturbatorRequests::setWinderState(bool state, float speed) {
//if(stateCommandWND.isCompleted()){
//stateCommandWND.transmitPacket->setPayload(StateOutStructure{state, speed});
//stateCommandWND.commit();
//}
}
void ExturbatorRequests::setExtruderConfiguration() {
//if(configCommandEXT.isCompleted()){
//configCommandEXT.transmitPacket->setPayload(ConfigurationOutStructure{});
//configCommandEXT.commit();
//}
}
void ExturbatorRequests::setPullerConfiguration() {
}
void ExturbatorRequests::setWinderConfiguration() {
}
float ExturbatorRequests::calculatePullerSpeedFromExtruder() {
return 0;
}
float ExturbatorRequests::calculateWinderSpeedFromExtruder() {
return 0;
} | [
"[email protected]"
] | |
efb3c0f594113aa081fdd36e28203b1fc9e86040 | a7091ff071e9ff7e8cf1569d1a45a03bbc0e6e7a | /B_Easter_Eggs.cpp | 10a6c75b18abdc291fca9088849bf979aae89521 | [] | no_license | bhavanisilasagaram/B_CodeForcesSolutions | 753593e28c259e1f082ca6a3010cb0a468a1a6ec | ae34cfd1f25aa395f91a31f831ddcdd386b25b17 | refs/heads/main | 2023-01-24T17:16:27.966974 | 2020-12-04T14:58:14 | 2020-12-04T14:58:14 | 304,842,302 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp | #include <iostream>
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ll long long
using namespace std;
int main() {
fastio;
int num;
cin >>num;
string s="VIBGYOR";
string g="GYOR";
if(num<7){
for(int i=0;i<(num%7);i++){
cout<<s[i];
}
}
else{
cout<<s;
for(int i=0;i<(num-7)/4;i++){
cout<<"GYOR";
}
for(int j=0;j<(num-7)%4;j++){
cout<<g[j];
}
}
return 0;
} | [
"[email protected]"
] | |
f0b541afe4e6fe1c9d55e64d0bddf0dc7e0c19f1 | 33cdd09e352529963fe8b28b04e0d2e33483777b | /trunk/LMPlugin/TKLQuantifier_Recordset.cpp | edde7bd8691a37340f95779ac7ba0e1581215464 | [] | no_license | BackupTheBerlios/reportasistent-svn | 20e386c86b6990abafb679eeb9205f2aef1af1ac | 209650c8cbb0c72a6e8489b0346327374356b57c | refs/heads/master | 2020-06-04T16:28:21.972009 | 2010-05-18T12:06:48 | 2010-05-18T12:06:48 | 40,804,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,752 | cpp | // TKLQuantifier_Recordset.cpp : implementation file
//
/*
This file is part of LM Report Asistent.
Authors: Jan Dedek, Jan Kodym, Martin Chrz, Iva Bartunkova
LM Report Asistent is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
LM Report Asistent is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with LM Report Asistent; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "TKLQuantifier_Recordset.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// TKLQuantifier_Recordset
IMPLEMENT_DYNAMIC(TKLQuantifier_Recordset, CRecordset)
TKLQuantifier_Recordset::TKLQuantifier_Recordset(CDatabase* pdb)
: CRecordset(pdb)
{
//{{AFX_FIELD_INIT(TKLQuantifier_Recordset)
m_TaskID = 0;
m_Name = _T("");
m_TaskSubTypeID = 0;
m_TaskGroupID = 0;
m_UserID = 0;
m_MatrixID = 0;
m_ParamBASE = 0;
m_ParamBASERelativ = FALSE;
m_ReadOnly = FALSE;
m_HypothesisGenerated = FALSE;
m_GenerationInterrupted = FALSE;
m_GenerationNrOfTests = 0;
m_GenerationTotalTime = 0;
m_Notice = _T("");
m_KLQuantifierID = 0;
m_TaskID2 = 0;
m_KLQuantifierTypeID = 0;
m_FromRow = 0;
m_FromCol = 0;
m_ToRow = 0;
m_ToCol = 0;
m_CompareTypeID = 0;
m_ValuePar = 0.0;
m_KLQuantifierValueTypeID = 0;
m_Threshold = 0.0;
m_Formula = _T("");
m_Ord = 0;
m_KendalAbsValueTauB = FALSE;
m_Notice2 = _T("");
m_MatrixID2 = 0;
m_Name2 = _T("");
m_Initialised = FALSE;
m_RecordCount = 0;
m_Notice3 = _T("");
m_wSavedCountUsed = 0;
m_CompareTypeID2 = 0;
m_Name3 = _T("");
m_ShortName = _T("");
m_Ord2 = 0;
m_Notice4 = _T("");
m_KLQuantifierTypeID2 = 0;
m_Name4 = _T("");
m_ShortName2 = _T("");
m_Ord3 = 0;
m_Notice5 = _T("");
m_KLQuantifierValueTypeID2 = 0;
m_Name5 = _T("");
m_ShortName3 = _T("");
m_Ord4 = 0;
m_Notice6 = _T("");
m_TaskSubTypeID2 = 0;
m_Name6 = _T("");
m_ShortName4 = _T("");
m_Ord5 = 0;
m_Notice7 = _T("");
m_nFields = 56;
//}}AFX_FIELD_INIT
m_nDefaultType = snapshot;
}
CString TKLQuantifier_Recordset::GetDefaultSQL()
{
return _T("[taTask],[tdKLQuantifier],[tmMatrix],[tsCompareType],[tsKLQuantifierType],[tsKLQuantifierValueType],[tsTaskSubType]");
}
void TKLQuantifier_Recordset::DoFieldExchange(CFieldExchange* pFX)
{
//{{AFX_FIELD_MAP(TKLQuantifier_Recordset)
pFX->SetFieldType(CFieldExchange::outputColumn);
RFX_Long(pFX, _T("[taTask].[TaskID]"), m_TaskID);
RFX_Text(pFX, _T("[taTask].[Name]"), m_Name);
RFX_Long(pFX, _T("[taTask].[TaskSubTypeID]"), m_TaskSubTypeID);
RFX_Long(pFX, _T("[TaskGroupID]"), m_TaskGroupID);
RFX_Long(pFX, _T("[UserID]"), m_UserID);
RFX_Long(pFX, _T("[taTask].[MatrixID]"), m_MatrixID);
RFX_Long(pFX, _T("[ParamBASE]"), m_ParamBASE);
RFX_Bool(pFX, _T("[ParamBASERelativ]"), m_ParamBASERelativ);
RFX_Bool(pFX, _T("[ReadOnly]"), m_ReadOnly);
RFX_Bool(pFX, _T("[HypothesisGenerated]"), m_HypothesisGenerated);
RFX_Bool(pFX, _T("[GenerationInterrupted]"), m_GenerationInterrupted);
RFX_Long(pFX, _T("[GenerationNrOfTests]"), m_GenerationNrOfTests);
RFX_Date(pFX, _T("[GenerationStartTime]"), m_GenerationStartTime);
RFX_Long(pFX, _T("[GenerationTotalTime]"), m_GenerationTotalTime);
RFX_Text(pFX, _T("[taTask].[Notice]"), m_Notice);
RFX_Long(pFX, _T("[KLQuantifierID]"), m_KLQuantifierID);
RFX_Long(pFX, _T("[tdKLQuantifier].[TaskID]"), m_TaskID2);
RFX_Long(pFX, _T("[tdKLQuantifier].[KLQuantifierTypeID]"), m_KLQuantifierTypeID);
RFX_Long(pFX, _T("[FromRow]"), m_FromRow);
RFX_Long(pFX, _T("[FromCol]"), m_FromCol);
RFX_Long(pFX, _T("[ToRow]"), m_ToRow);
RFX_Long(pFX, _T("[ToCol]"), m_ToCol);
RFX_Long(pFX, _T("[tdKLQuantifier].[CompareTypeID]"), m_CompareTypeID);
RFX_Double(pFX, _T("[ValuePar]"), m_ValuePar);
RFX_Long(pFX, _T("[tdKLQuantifier].[KLQuantifierValueTypeID]"), m_KLQuantifierValueTypeID);
RFX_Double(pFX, _T("[Threshold]"), m_Threshold);
RFX_Text(pFX, _T("[Formula]"), m_Formula);
RFX_Long(pFX, _T("[tdKLQuantifier].[Ord]"), m_Ord);
RFX_Bool(pFX, _T("[KendalAbsValueTauB]"), m_KendalAbsValueTauB);
RFX_Text(pFX, _T("[tdKLQuantifier].[Notice]"), m_Notice2);
RFX_Long(pFX, _T("[tmMatrix].[MatrixID]"), m_MatrixID2);
RFX_Text(pFX, _T("[tmMatrix].[Name]"), m_Name2);
RFX_Bool(pFX, _T("[Initialised]"), m_Initialised);
RFX_Long(pFX, _T("[RecordCount]"), m_RecordCount);
RFX_Text(pFX, _T("[tmMatrix].[Notice]"), m_Notice3);
RFX_Long(pFX, _T("[wSavedCountUsed]"), m_wSavedCountUsed);
RFX_Long(pFX, _T("[tsCompareType].[CompareTypeID]"), m_CompareTypeID2);
RFX_Text(pFX, _T("[tsCompareType].[Name]"), m_Name3);
RFX_Text(pFX, _T("[tsCompareType].[ShortName]"), m_ShortName);
RFX_Long(pFX, _T("[tsCompareType].[Ord]"), m_Ord2);
RFX_Text(pFX, _T("[tsCompareType].[Notice]"), m_Notice4);
RFX_Long(pFX, _T("[tsKLQuantifierType].[KLQuantifierTypeID]"), m_KLQuantifierTypeID2);
RFX_Text(pFX, _T("[tsKLQuantifierType].[Name]"), m_Name4);
RFX_Text(pFX, _T("[tsKLQuantifierType].[ShortName]"), m_ShortName2);
RFX_Long(pFX, _T("[tsKLQuantifierType].[Ord]"), m_Ord3);
RFX_Text(pFX, _T("[tsKLQuantifierType].[Notice]"), m_Notice5);
RFX_Long(pFX, _T("[tsKLQuantifierValueType].[KLQuantifierValueTypeID]"), m_KLQuantifierValueTypeID2);
RFX_Text(pFX, _T("[tsKLQuantifierValueType].[Name]"), m_Name5);
RFX_Text(pFX, _T("[tsKLQuantifierValueType].[ShortName]"), m_ShortName3);
RFX_Long(pFX, _T("[tsKLQuantifierValueType].[Ord]"), m_Ord4);
RFX_Text(pFX, _T("[tsKLQuantifierValueType].[Notice]"), m_Notice6);
RFX_Long(pFX, _T("[tsTaskSubType].[TaskSubTypeID]"), m_TaskSubTypeID2);
RFX_Text(pFX, _T("[tsTaskSubType].[Name]"), m_Name6);
RFX_Text(pFX, _T("[tsTaskSubType].[ShortName]"), m_ShortName4);
RFX_Long(pFX, _T("[tsTaskSubType].[Ord]"), m_Ord5);
RFX_Text(pFX, _T("[tsTaskSubType].[Notice]"), m_Notice7);
//}}AFX_FIELD_MAP
}
/////////////////////////////////////////////////////////////////////////////
// TKLQuantifier_Recordset diagnostics
#ifdef _DEBUG
void TKLQuantifier_Recordset::AssertValid() const
{
CRecordset::AssertValid();
}
void TKLQuantifier_Recordset::Dump(CDumpContext& dc) const
{
CRecordset::Dump(dc);
}
#endif //_DEBUG
| [
"chrzm@fded5620-0c03-0410-a24c-85322fa64ba0"
] | chrzm@fded5620-0c03-0410-a24c-85322fa64ba0 |
34a6d20b028cdeea92527da8e5a3225179fea31b | 101960fc6b1977dc848c5902d12f919dd22ab5c0 | /第18章/TGAFile/Font.h | 0b53e9b5d065fa792656a6f6a3df2fc69fd926d2 | [] | no_license | jackros1022/OpenGL-Classic-Example-Programming | cf3dbdfc024243f4ebd54d49b22ebe92bd7d52e0 | 508e43e3439d4659e7fe451f3c3f2f7b357dcbdd | refs/heads/master | 2020-03-12T08:27:05.197916 | 2018-04-22T02:15:19 | 2018-04-22T02:15:19 | 130,527,811 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 806 | h | //========================================================
/**
* @file Font.h
*
* 项目描述: TGA文件载入
* 文件描述: 字体类
* 适用平台: Windows98/2000/NT/XP
*
* 作者: BrightXu
* 电子邮件: [email protected]
* 创建日期: 2006-09-13
* 修改日期: 2006-12-02
*
*/
//========================================================
#ifndef __GLFONT_H__
#define __GLFONT_H__
#include "stdafx.h"
/** 定义字体类 */
class GLFont
{
public:
/** 构造函数和析构函数 */
GLFont();
~GLFont();
///成员方法
bool InitFont(); /**< 初始化字体 */
void PrintText(char *string, float x, float y); /**< 在(x,y)处输出string内容 */
protected:
HFONT m_hFont; /**< 字体句柄 */
};
#endif // __GLFONT_H__ | [
"[email protected]"
] | |
89b317120a0ae581a3f3ddf67137b8eef967174a | a6d15c19698025ee007ed6b7b258a4de9eca40d2 | /softwarecontest/src/GameHost.h | 78a7622006c328327ae8f21ef29e18daf459a829 | [] | no_license | dougreichard/software-contest-2013 | 109910cf837cc9ee46e1f3d8569b2086df49e62a | ec4c3ebae22f9530da8ebc4de280d8d3fd5da338 | refs/heads/master | 2021-01-13T02:10:37.063244 | 2013-02-28T17:10:37 | 2013-02-28T17:10:37 | 8,271,942 | 0 | 0 | null | 2023-08-29T18:19:55 | 2013-02-18T16:12:57 | C | UTF-8 | C++ | false | false | 335 | h | #pragma once
#include <string>
#include "CastleGameBoard.h"
#include "Card.h"
using namespace std;
class GameClient;
class GameHost{
public:
GameHost(GameClient* host);
virtual ~GameHost();
virtual void Start();
virtual void End();
virtual void Command(string s);
void Broadcast(string s);
private:
GameClient* _host;
};
| [
"[email protected]"
] | |
10b3e38af3112fdbff54e3f974d4695f8985edf7 | 8b2f9b6633c64743957c32042c3b2166792711c3 | /source/game/backend/basicClasses/CProjectile.cpp | cca367c58b0904fde8e8d9b3e20345dbd2d34a2e | [] | no_license | DavidAStoll/FighterPilotGameCode | bbb54c85a09d8442f94d681f910bc467139bc9a2 | 9042977373d9e405e38bd3a8f703ab68f53e8f75 | refs/heads/master | 2016-08-13T01:11:24.821458 | 2016-03-16T00:07:26 | 2016-03-16T00:07:26 | 53,984,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,072 | cpp | /*
============================================================================
Name : Projectile.cpp
Author : David Stoll
Version : 1.0
Copyright : Your copyright notice
Description : CProjectile implementation
============================================================================
*/
#include "includes/game/backend/basicClasses/CProjectile.h"
#include "includes/game/backend/gameObjects/CGameObjectDefaultValues.h"
CProjectile::CProjectile(CTextureObject* aTextureObject, CAnimationPlayer* aAnimationPlayer, TPoint aLocation, SGameObjectAttributes& aAttributes, TIntFloat aSpeed, TInt aRange, TInt aAngel) :
CMoveableGameObject(BASIC_PROJECTILE_DEFAULT_Z_COORDINATE, aTextureObject, aAnimationPlayer, aLocation, aAttributes, BASIC_PROJECTILE_DEFAULT_FRAMES_PER_MOVE)
{
iSpeed = aSpeed;
iRange = aRange;
iAngle = aAngel;
//calculate how fast the object will move via X and Y axis
//adjust X axis speed
iPixelsPerMoveX = iSpeed * CMath::GraphicsCosTable(aAngel);
//adjust Y axis speed
iPixelsPerMoveY = iSpeed * CMath::GraphicsSinTable(aAngel);
}
CProjectile::CProjectile(CTextureObject* aTextureObject, CAnimationPlayer* aAnimationPlayer, TPointIntFloat aLocation, SGameObjectAttributes& aAttributes, TIntFloat aSpeed, TInt aRange, TInt aAngel) :
CMoveableGameObject(BASIC_PROJECTILE_DEFAULT_Z_COORDINATE, aTextureObject, aAnimationPlayer, aLocation, aAttributes, BASIC_PROJECTILE_DEFAULT_FRAMES_PER_MOVE)
{
iSpeed = aSpeed;
iRange = aRange;
iAngle = aAngel;
//calculate how fast the object will move via X and Y axis
//adjust X axis speed
iPixelsPerMoveX = iSpeed * CMath::GraphicsCosTable(aAngel);
//adjust Y axis speed
iPixelsPerMoveY = iSpeed * CMath::GraphicsSinTable(aAngel);
}
CProjectile::~CProjectile()
{
}
void CProjectile::ConstructL()
{
}
//this method just aligns the texture probably with the current rotation
void CProjectile::AdjustCoordinatesAndTexture()
{
if(iObjectReflected)
{
iTextureObject->ReflectOverYAxis();
TInt lRotateAngel = iAngle;
iTextureObject->RotateVertexes(lRotateAngel);
}else
{
TInt lRotateAngel = -180 + iAngle;
iTextureObject->RotateVertexes(lRotateAngel);
}
TPointIntFloat lTextureLowerCorner = iTextureObject->ReturnCurrentFixPoint();
TPointIntFloat lTextureAdjustmentDueToRotation;
lTextureAdjustmentDueToRotation.iX = -lTextureLowerCorner.iX + iCoordinates.iX;
lTextureAdjustmentDueToRotation.iY = -lTextureLowerCorner.iY + iCoordinates.iY;
iTextureObject->ChangeXCoordinate(lTextureAdjustmentDueToRotation.iX);
iTextureObject->ChangeYCoordinate(lTextureAdjustmentDueToRotation.iY);
}
//-------------- functions ---------------------
void CProjectile::CProjectile::Move()
{
//do nothing
}
void CProjectile::Update()
{
iRange -= iSpeed.GetIntInBaseInt();
if(iRange < 0)
{
Destruct();
}else
{
iCoordinates.iX += iPixelsPerMoveX;
iCoordinates.iY += iPixelsPerMoveY;
iTextureObject->ChangeXCoordinate(iPixelsPerMoveX);
iTextureObject->ChangeYCoordinate(iPixelsPerMoveY);
}
}
void CProjectile::Destruct()//default behaviour, just set it to dead to remove it
{
MoveableObjectBasicDieRoutine();
iDoNotDraw = true;
iRecycleObject = true;//remove from game
if(iSoundObject)
{
iSoundObject->StopSoundChannel();
}
}
void CProjectile::SetPixelsPerMoveX(TIntFloat aValue)
{
iPixelsPerMoveX = aValue;
}
void CProjectile::SetPixelsPerMoveY(TIntFloat aValue)
{
iPixelsPerMoveY = aValue;
}
void CProjectile::Die(TDamageType aDamageType)
{
Destruct();
}
void CProjectile::ProjectileObjectSaveContentToDisk(CFileWriteStream &aOutputStream)
{
MoveableGameObjectSaveContentToDisk(aOutputStream);
aOutputStream.WriteInt32(iRange);
}
void CProjectile::ProjectileObjectLoadContentFromDisk(CFileReadStream &aReadStream)
{
MoveableGameObjectLoadContentFromDisk(aReadStream);
iRange = aReadStream.ReadInt32();
}
void CProjectile::SaveOnDisk(CFileWriteStream &aOutputStream)
{
ProjectileObjectSaveContentToDisk(aOutputStream);
}
void CProjectile::LoadFromDisk(CFileReadStream &aReadStream)
{
ProjectileObjectLoadContentFromDisk(aReadStream);
}
| [
"[email protected]"
] | |
a60a893b927d7ce5b5907aa852f404d24f62ac71 | 2ebcdbd956e051ba11547423839e71323abae6e4 | /Marker/App.h | 7104bc5edcaf626c07201045fc29d0ed820737eb | [] | no_license | WangYiTao0/Marker | 271e3ea8dd60cafefeebc4ebfcb9950adcabf0d8 | f90554916f89919788f050aac38f53da0a8a7132 | refs/heads/master | 2020-10-01T08:21:34.941266 | 2019-12-11T11:13:10 | 2019-12-11T11:13:10 | 227,499,018 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 797 | h | #pragma once
#include <Siv3D.hpp> // OpenSiv3D v0.4.2
#include <memory>
#include "Marker.h"
#include "MarkerManager.h"
class App
{
public:
App();
void Update();
void Draw();
private:
void AssetRegiseter();
private:
struct RingEffect : IEffect
{
Vec2 m_pos;
ColorF m_color;
RingEffect(const Vec2& pos)
: m_pos(pos)
, m_color(RandomColor())
{}
bool update(double t) override
{
// イージング
const double e = EaseOutExpo(t);
Circle(m_pos, e * 100).drawFrame(20.0 * (1.0 - e), m_color);
return t < 1.0;
}
};
Effect effect;
MarkerManager m_Manager;
Vec2 mouseStartPos = { 100,100 };
Vec2 mouseDelta = { 200,200 };
}; | [
"[email protected]"
] | |
27bdf115e6e0c850605fde76e2a3cce6e6e726c1 | 263a50fb4ca9be07a5b229ac80047f068721f459 | /ppapi/proxy/ppb_flash_menu_proxy.cc | d2ef2a3d77789d1ea212205609d8c063c1336dc2 | [
"BSD-3-Clause"
] | permissive | talalbutt/clank | 8150b328294d0ac7406fa86e2d7f0b960098dc91 | d060a5fcce180009d2eb9257a809cfcb3515f997 | refs/heads/master | 2021-01-18T01:54:24.585184 | 2012-10-17T15:00:42 | 2012-10-17T15:00:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,257 | cc | // Copyright (c) 2011 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 "ppapi/proxy/ppb_flash_menu_proxy.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/private/ppb_flash_menu.h"
#include "ppapi/proxy/enter_proxy.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/tracked_callback.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_flash_menu_api.h"
#include "ppapi/thunk/resource_creation_api.h"
using ppapi::thunk::EnterFunctionNoLock;
using ppapi::thunk::PPB_Flash_Menu_API;
using ppapi::thunk::ResourceCreationAPI;
namespace ppapi {
namespace proxy {
class FlashMenu : public PPB_Flash_Menu_API, public Resource {
public:
explicit FlashMenu(const HostResource& resource);
virtual ~FlashMenu();
// Resource overrides.
virtual PPB_Flash_Menu_API* AsPPB_Flash_Menu_API() OVERRIDE;
// PPB_Flash_Menu_API implementation.
virtual int32_t Show(const PP_Point* location,
int32_t* selected_id,
PP_CompletionCallback callback) OVERRIDE;
void ShowACK(int32_t selected_id, int32_t result);
private:
scoped_refptr<TrackedCallback> callback_;
int32_t* selected_id_ptr_;
DISALLOW_COPY_AND_ASSIGN(FlashMenu);
};
FlashMenu::FlashMenu(const HostResource& resource)
: Resource(resource),
selected_id_ptr_(NULL) {
}
FlashMenu::~FlashMenu() {
}
PPB_Flash_Menu_API* FlashMenu::AsPPB_Flash_Menu_API() {
return this;
}
int32_t FlashMenu::Show(const struct PP_Point* location,
int32_t* selected_id,
struct PP_CompletionCallback callback) {
if (TrackedCallback::IsPending(callback_))
return PP_ERROR_INPROGRESS;
selected_id_ptr_ = selected_id;
callback_ = new TrackedCallback(this, callback);
PluginDispatcher::GetForResource(this)->Send(
new PpapiHostMsg_PPBFlashMenu_Show(
API_ID_PPB_FLASH_MENU, host_resource(), *location));
return PP_OK_COMPLETIONPENDING;
}
void FlashMenu::ShowACK(int32_t selected_id, int32_t result) {
*selected_id_ptr_ = selected_id;
TrackedCallback::ClearAndRun(&callback_, result);
}
PPB_Flash_Menu_Proxy::PPB_Flash_Menu_Proxy(Dispatcher* dispatcher)
: InterfaceProxy(dispatcher),
callback_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}
PPB_Flash_Menu_Proxy::~PPB_Flash_Menu_Proxy() {
}
// static
PP_Resource PPB_Flash_Menu_Proxy::CreateProxyResource(
PP_Instance instance_id,
const PP_Flash_Menu* menu_data) {
PluginDispatcher* dispatcher = PluginDispatcher::GetForInstance(instance_id);
if (!dispatcher)
return 0;
HostResource result;
SerializedFlashMenu serialized_menu;
if (!serialized_menu.SetPPMenu(menu_data))
return 0;
dispatcher->Send(new PpapiHostMsg_PPBFlashMenu_Create(
API_ID_PPB_FLASH_MENU, instance_id, serialized_menu, &result));
if (result.is_null())
return 0;
return (new FlashMenu(result))->GetReference();
}
bool PPB_Flash_Menu_Proxy::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PPB_Flash_Menu_Proxy, msg)
IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFlashMenu_Create,
OnMsgCreate)
IPC_MESSAGE_HANDLER(PpapiHostMsg_PPBFlashMenu_Show,
OnMsgShow)
IPC_MESSAGE_HANDLER(PpapiMsg_PPBFlashMenu_ShowACK,
OnMsgShowACK)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
// FIXME(brettw) handle bad messages!
return handled;
}
void PPB_Flash_Menu_Proxy::OnMsgCreate(PP_Instance instance,
const SerializedFlashMenu& menu_data,
HostResource* result) {
thunk::EnterResourceCreation enter(instance);
if (enter.succeeded()) {
result->SetHostResource(
instance,
enter.functions()->CreateFlashMenu(instance, menu_data.pp_menu()));
}
}
struct PPB_Flash_Menu_Proxy::ShowRequest {
HostResource menu;
int32_t selected_id;
};
void PPB_Flash_Menu_Proxy::OnMsgShow(const HostResource& menu,
const PP_Point& location) {
ShowRequest* request = new ShowRequest;
request->menu = menu;
EnterHostFromHostResourceForceCallback<PPB_Flash_Menu_API> enter(
menu, callback_factory_, &PPB_Flash_Menu_Proxy::SendShowACKToPlugin,
request);
if (enter.succeeded()) {
enter.SetResult(enter.object()->Show(&location, &request->selected_id,
enter.callback()));
}
}
void PPB_Flash_Menu_Proxy::OnMsgShowACK(const HostResource& menu,
int32_t selected_id,
int32_t result) {
EnterPluginFromHostResource<PPB_Flash_Menu_API> enter(menu);
if (enter.failed())
return;
static_cast<FlashMenu*>(enter.object())->ShowACK(selected_id, result);
}
void PPB_Flash_Menu_Proxy::SendShowACKToPlugin(
int32_t result,
ShowRequest* request) {
dispatcher()->Send(new PpapiMsg_PPBFlashMenu_ShowACK(
API_ID_PPB_FLASH_MENU,
request->menu,
request->selected_id,
result));
delete request;
}
} // namespace proxy
} // namespace ppapi
| [
"[email protected]"
] | |
a5e5fbbf7b0c932a10deae083eaa57fb3e71b9d7 | e30874b3aa20804833dd11788176f839fcd08690 | /java/src/main/native/src/emptyfile.cpp | 67fa3acd73932756556e1c1c7fa19adb8e6d8ab7 | [
"Apache-2.0"
] | permissive | rapidsai/cudf | eaba8948cddde8161c3b02b1b972dab3df8d95b3 | c51633627ee7087542ad4c315c0e139dea58e408 | refs/heads/branch-23.10 | 2023-09-04T07:18:27.194295 | 2023-09-03T06:20:33 | 2023-09-03T06:20:33 | 90,506,918 | 5,386 | 751 | Apache-2.0 | 2023-09-14T00:27:03 | 2017-05-07T03:43:37 | C++ | UTF-8 | C++ | false | false | 632 | cpp | /*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Intentionally empty
| [
"[email protected]"
] |
Subsets and Splits