blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 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 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 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 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0926be3c2d29a23c40f2149860a378d68d5d76a2 | 5fc03cffb8e7c0d83ec0feab7be675dc530b3396 | /src/engine/physics/particle_generator.h | 546b11322d9f21a97edab3ec1fd267f4fdf808f6 | [] | no_license | simplejeff/liquidSim | 205f6fdce4db280dbe7dd0bbb7673efca7690828 | c0468d54374667b3b8e0733693d86e4246a28db6 | refs/heads/master | 2020-03-10T03:24:25.757580 | 2018-04-27T13:31:07 | 2018-04-27T13:31:07 | 129,163,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 257 | h | #ifndef PARTICLE_GENERATOR_H
#define PARTICLE_GENERATOR_H
#include <Eigen/Dense>
using namespace Eigen;
void InitRandom();
float Random();
VectorXf GenParticleInCube(size_t,float);
VectorXf GenRandomVelocities(size_t);
#endif // PARTICLE_GENERATOR_H
| [
"jeffrey_hao@brown.edu"
] | jeffrey_hao@brown.edu |
f8626aa4ca99069d35abb224ea6c70549d4c9004 | 551bf7d1180a6d54449eb7f60c5120d7bd8a953d | /include/rpoly/rpoly_ak1.hpp | 3e218b1f1f90789773153cf744eb160b6ed4a1e9 | [] | no_license | swgmone/trajectory_server | 76d40212c8f70ab6141e918888f7e770f44ffc09 | e2dea16266cea8b7b7f4b35af5dccb14f80129aa | refs/heads/main | 2023-09-01T10:24:17.174801 | 2021-10-12T08:58:20 | 2021-10-12T08:58:20 | 406,545,939 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 587 | hpp | /* Polynomial Handler */
/* Author: Lorenzo Gentilini */
/* E-Mail: lorenzo.gentilini6@unibo.it */
/* Date: August 2020 */
/* File: rpoly_ak1.hpp */
#ifndef _RPOLY_H
#define _RPOLY_H
#include <Eigen/Eigen>
#include <iostream>
#include <fstream>
#include <cctype>
#include <cmath>
#include <cfloat>
int findLastNonZeroCoeff(Eigen::VectorXd coefficients);
bool findRootsJenkinsTraub(Eigen::VectorXd coefficients_increasing,
Eigen::VectorXcd& roots);
#endif | [
"lorenzo.gentilini6@unibo.it"
] | lorenzo.gentilini6@unibo.it |
e1a4b0203c949dcfe478c1b29e0c3ae4779792f3 | cfdab33825bb160dea64f0aab79b7206bf82e6d7 | /10828/10828.cc | 0955cac890a3052709ddc19e1858b118c29f557a | [] | no_license | wjdwithyou/BOJ | 299e0efaf3e5173addc55709fed5c19a458a0900 | a8ab50a14f2059905be4093b1f889c02f568126c | refs/heads/master | 2021-01-11T20:18:13.462615 | 2018-01-24T14:28:25 | 2018-01-24T14:28:25 | 81,535,224 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 734 | cc | #include <iostream>
int stack[10000];
int main() {
char buf[16];
int n, num;
int stack_idx = 0;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%s", buf);
switch (buf[0]) {
case 'p':
if (buf[1] == 'u') {
scanf("%d", &num);
stack[stack_idx++] = num;
}
else {
if (stack_idx == 0) {
puts("-1");
}
else {
printf("%d\n", stack[--stack_idx]);
}
}
break;
case 's':
printf("%d\n", stack_idx);
break;
case 'e':
if (stack_idx == 0) {
puts("1");
}
else {
puts("0");
}
break;
case 't':
if (stack_idx == 0) {
puts("-1");
}
else {
printf("%d\n", stack[stack_idx - 1]);
}
break;
default:
break;
}
}
return 0;
} | [
"administrator@mail.tastewiki.xyz"
] | administrator@mail.tastewiki.xyz |
a5bc5ae5202a6e8f63dd3cef85326031d7752a5c | f163486ed0a7e38c15c51e5d55dbf1443a7e637c | /HomeAlertTest/HomeAlertTest.ino | cae0fdf6b3748b4ec5b4465d05b456b20d2a2fc5 | [] | no_license | khawajamechatronics/Arduino | 31c58145cd0632664026030160a45d6f64c34dad | 721855f0d1f965399a6200e7018d195ae7902c58 | refs/heads/master | 2020-03-18T18:35:42.125924 | 2017-02-08T14:40:59 | 2017-02-08T14:40:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,710 | ino | #include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <TimeLib.h>
#include <Timezone.h>
#include "ModuleSettings.h"
#include "ESP8266WebServerEx.h"
#include "SendEmailSms.h"
#include "NTPClient.h"
#include "TimeSettings.h"
#include "SerialDebug.h"
#include "General.h"
#include "EmailSms.h"
#include "InputPinMgmt.h"
#include "HttpSession.h"
#include "InfoExchg.h"
#include "MyWiFi.h"
#include "ArmLogic.h"
//#include <ESP8266mDNS.h>
#include "admin.html.h"
#ifndef PHASE2_CODE
#include "email.html.h"
#else
#include "email.html.h"
//#include "email_p2.html.h"
#endif
#include "favicon.png.h"
#include "general.html.h"
#include "gpio.html.h"
#include "login.html.h"
#include "time.html.h"
#include "device.html.h"
#include "network.html.h"
#include "skeleton.css.h"
#include "normalize.css.h"
#include "main.css.h"
#include "main.js.h"
#include "jquery-3.1.0.min.js.gz.h"
#include "md5.min.js.gz.h"
///////////////////////////////////////////////////////////////////////// 12 13
int g_inputPins[INPUT_PIN_COUNT]={5};
int g_outputPins[OUTPUT_PIN_COUNT]={ 15, 2, 0, 4, 16, 14, 12, 13};
int g_buttonPins[BUTTON_PIN_COUNT]={};
int g_ARM_INPUT_PIN = 5;
int g_ARM_OFF_PIN = 99; // virtual pin for toggle off ARM
int g_BELL_PIN = 16;
char* g_WifiApPassword = NULL;
IPAddress g_ApIp(192,168,3,1);
/////////////////////////////////////////////////////////////////////////
const int ANALOG_PIN = A0; // Analog input. Need to seed the random generator
#define BROWSER_CACHE_DAYS 864000 // cache for 10 days
static const char MimeTypeJS[] = "application/javascript";
static const char MimeCss[] = "text/css";
static const char MimeHtml[] = "text/html";
static const char MimeJson[] = "application/json";
static const char MimePNG[] = "image/png";
static const char StatusJsonTrue[] = "{\"status\":true}";
static const char StatusJsonFalse[] = "{\"status\":false}";
InfoExchg udpServer;
CNTPClient NTP;
ModuleSettings g_ModuleSettings;
General g_General;
InputPinMagement g_InputPinMgmt;
ArmLogic g_ArmLogic(g_ARM_INPUT_PIN, g_BELL_PIN);
MyWiFi g_WifiList;
ESP8266WebServerEx *g_pServer = NULL;
DNSServer *g_pDnsServer = NULL;
void SetupGPIO();
void handleRoot();
void handleIoPinMaps();
void handleNotFound();
void handleGetTimeSettings();
void handleSetTimeSettings();
void handleGetGeneral();
void handleSetGeneral();
void handleGetEmailSms();
void handleSetEmailSms();
void handleGetDeviceInfo();
void handleGetGpio();
void handleGetDeviceList();
void handleScanWiFi();
void handleGetNetworkSettings(bool bHead=true);
void handleSetNetworkSettings();
void handleRebootEsp();
bool StartAsWifiSTA();
bool StartAsWifiAP();
bool g_IsAPMode = false;
bool g_FirstAPMode = false;
unsigned long g_lastSave = 0;
unsigned long g_lastimeCheckConn;
String inputString;
bool stringComplete=false;
//////////////////////////////////////////////////////////////////////////////////////////////////
// global setup
void setup ( void ) {
delay(1000);
INIT_SERIAL_DEBUG();
g_IsAPMode = false;
g_ModuleSettings.LoadSettings();
g_ModuleSettings.data.ending=9;
g_ModuleSettings.SaveSettings();
// seed the random generator sources
randomSeed(analogRead(ANALOG_PIN) ^ millis());
SetupGPIO();
g_WifiList.Scan();
if ( StartAsWifiSTA() ) {
g_pServer = new ESP8266WebServerEx(g_ModuleSettings.data.port);
TRACE2("HTTP server port: ",g_ModuleSettings.data.port);
TRACE2("IP address: ",WiFi.localIP());
}
else {
if ( StartAsWifiAP() ) {
g_FirstAPMode = true;
g_IsAPMode = true;
g_pServer = new ESP8266WebServerEx(80);
TRACE2("IP address: ",WiFi.softAPIP());
g_pServer->ForceLogin(false);
} else {
TRACE("Starting as WIFI AP failed.\nRebooting...");
delay(2000);
ESP.restart();
return;
}
}
//here the list of headers to be recorded
const char * headerkeys[] = {"Cookie","Host"};
size_t headerkeyssize = sizeof(headerkeys)/sizeof(char*);
//ask server to track these headers
g_pServer->collectHeaders(headerkeys, headerkeyssize );
// send jquery and related CSS files
g_pServer->on ( "/js/jquery-3.1.0.min.js.gz", []() { g_pServer->sendEx(200, MimeTypeJS, jquery_3_1_0_min_js_gz, sizeof(jquery_3_1_0_min_js_gz),true,BROWSER_CACHE_DAYS); });
g_pServer->on ( "/js/md5.min.js.gz", []() { g_pServer->sendEx(200, MimeTypeJS, md5_min_js_gz, sizeof(md5_min_js_gz),true,BROWSER_CACHE_DAYS); });
g_pServer->on("/js/main.js", []() { g_pServer->sendEx(200, MimeTypeJS, main_js, sizeof(main_js),false,BROWSER_CACHE_DAYS); });
g_pServer->on("/css/skeleton.css", []() { g_pServer->sendEx(200, MimeCss, skeleton_css, sizeof(skeleton_css),false,BROWSER_CACHE_DAYS); });
g_pServer->on("/css/normalize.css", []() { g_pServer->sendEx(200, MimeCss, normalize_css, sizeof(normalize_css),false,BROWSER_CACHE_DAYS); });
g_pServer->on("/css/main.css", []() { g_pServer->sendEx(200, MimeCss, main_css, sizeof(main_css),false,BROWSER_CACHE_DAYS); });
g_pServer->onNotFound ( handleNotFound );
g_pServer->on("/favicon.png", []() { g_pServer->sendEx(200, MimePNG, favicon_png, sizeof(favicon_png),false,BROWSER_CACHE_DAYS); });
g_pServer->on("/js/ioPinMaps.js", handleIoPinMaps);
g_pServer->on("/getdeviceinfo", handleGetDeviceInfo);
g_pServer->on("/getgpio", handleGetGpio);
g_pServer->on("/setgpio", []() { g_pServer->handleSetGpio(); });
g_pServer->on("/gettimesettings", handleGetTimeSettings);
g_pServer->on("/settimesettings", handleSetTimeSettings);
g_pServer->on("/getgeneral", handleGetGeneral);
g_pServer->on("/setgeneral", handleSetGeneral);
g_pServer->on("/getemailsms", handleGetEmailSms);
g_pServer->on("/setemailsms", handleSetEmailSms);
g_pServer->on("/getdevicelist", handleGetDeviceList);
g_pServer->on("/scanwifi", handleScanWiFi);
g_pServer->on("/setnetworksettings", handleSetNetworkSettings);
g_pServer->on("/reboot", handleRebootEsp);
if ( g_IsAPMode ) {
g_pServer->on("/getnetworksettings", []() { handleGetNetworkSettings(false); });
g_pServer->on("/network.html", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); });
g_pServer->on("/", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); });
g_pServer->on("/hotspot-detect.html", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); });
g_pServer->on("/ search", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); });
g_pServer->on("/search", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); });
g_pServer->begin();
return;
}
g_pServer->on("/getnetworksettings", []() { handleGetNetworkSettings(); });
g_pServer->on("/", handleRoot);
g_pServer->on("/admin.html", []() { g_pServer->sendEx(200, MimeHtml, admin_html, sizeof(admin_html)); });
g_pServer->on("/gpio.html", []() { g_pServer->sendEx(200, MimeHtml, gpio_html, sizeof(gpio_html)); });
g_pServer->on("/general.html", []() { g_pServer->sendEx(200, MimeHtml, general_html, sizeof(general_html)); });
g_pServer->on("/network.html", []() { g_pServer->sendEx(200, MimeHtml, network_html, sizeof(network_html)); });
g_pServer->on("/time.html", []() { g_pServer->sendEx(200, MimeHtml, time_html, sizeof(time_html)); });
#ifndef PHASE2_CODE
g_pServer->on("/email.html", []() { g_pServer->sendEx(200, MimeHtml, email_html, sizeof(email_html)); });
#else
g_pServer->on("/email.html", []() { g_pServer->sendEx(200, MimeHtml, email_p2_html, sizeof(email_p2_html)); });
#endif
g_pServer->on("/device.html", []() { g_pServer->sendEx(200, MimeHtml, device_html, sizeof(device_html)); });
g_pServer->on("/logout.html", []() { g_pServer->handleLogout(); });
g_pServer->on("/login.html", handleRoot);
g_pServer->begin();
udpServer.begin();
}
#ifdef _DEBUG_
unsigned long heapChk = 0;
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////
// main loop
//////////////////////////////////////////////////////////////////////////////////////////////////
void loop ( void ) {
while(!g_FirstAPMode&&(WiFi.status()==WL_CONNECTION_LOST||WiFi.status()==WL_DISCONNECTED)){
g_WifiList.Scan();
delay(1000);
StartAsWifiSTA();
}
if(g_FirstAPMode&&g_ModuleSettings.data.ssid[0]){
if((millis()-g_lastimeCheckConn)>5000){
g_lastimeCheckConn = millis();
int numSsid = WiFi.scanNetworks();
if (numSsid == -1) {
TRACE("Couldn't get a wifi connection");
}
for (int thisNet = 0; thisNet < numSsid; thisNet++) {
if(String(WiFi.SSID(thisNet))==String(g_ModuleSettings.data.ssid)){
TRACE2("ssid :", WiFi.SSID(thisNet));
g_FirstAPMode = false;
if(StartAsWifiSTA()){
ESP.restart();
}
}
}
}
}
if (g_pServer) g_pServer->handleClient();
if ( g_IsAPMode ) {
if ( g_pDnsServer ) g_pDnsServer->processNextRequest();
return;
}
g_InputPinMgmt.checkInputPinStatus();
g_ArmLogic.runLogic();
NTP.AutoSync();
g_General.CheckPinSetOnOff();
udpServer.Update();
unsigned long curMillis = millis();
if ( curMillis>g_lastSave ) {
if ( curMillis-g_lastSave>3600000 ) {
g_ModuleSettings.SaveSettings();
g_lastSave = curMillis;
}
}
else g_lastSave = curMillis;
serialEvent();
if (stringComplete) {
Serial.println(inputString);
if(inputString.indexOf("restore")>=0){
g_ModuleSettings.CleanSettings();
ESP.restart();
}else if(inputString.indexOf("restart")>=0){
ESP.restart();
}
// clear the string:
inputString = "";
stringComplete = false;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
void handleRoot() {
g_pServer->handleLogin(login_html,sizeof(login_html),"/gpio.html");
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// return a JavaScript mapping of inputs and output pins
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleIoPinMaps() {
int i;
char buf[16];
String data = "var outputPins = {";
for (i=0; i<OUTPUT_PIN_COUNT; i++) {
delay(0);
if ( i ) data += ",";
sprintf(buf,"\"GPIO-%d\":%d",g_outputPins[i],g_outputPins[i]);
data += buf;
}
data += "};\nvar inputPins = {";
for (i=0; i<INPUT_PIN_COUNT; i++) {
delay(0);
if ( i ) data += ",";
sprintf(buf,"\"GPIO-%d\":%d",g_inputPins[i],g_inputPins[i]);
data += buf;
}
data += "};\nvar buttonPins = {";
for (i=0; i<BUTTON_PIN_COUNT; i++) {
delay(0);
if ( i ) data += ",";
sprintf(buf,"\"GPIO-%d\":%d",g_buttonPins[i],g_buttonPins[i]);
data += buf;
}
data += "};";
g_pServer->send(200,MimeTypeJS,data);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// process not found case
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += g_pServer->uri();
message += "\nMethod: ";
message += ( g_pServer->method() == HTTP_GET ) ? "GET" : "POST";
message += "\nArguments: ";
message += g_pServer->args();
message += "\n";
for ( uint8_t i = 0; i < g_pServer->args(); i++ ) {
delay(0);
message += " " + g_pServer->argName ( i ) + ": " + g_pServer->arg ( i ) + "\n";
}
g_pServer->send ( 404, "text/plain", message );
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
void SetupGPIO() {
int i;
for (i=0; i<INPUT_PIN_COUNT; i++) {
delay(0);
pinMode(g_inputPins[i], INPUT_PULLUP);
}
for (i=0; i<OUTPUT_PIN_COUNT; i++) {
delay(0);
pinMode(g_outputPins[i], OUTPUT);
}
for (i=0; i<BUTTON_PIN_COUNT; i++) {
delay(0);
pinMode(g_buttonPins[i], OUTPUT);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// return JSON {server: "timeg_pServer->com",time:12345648,zone:4}
// time is UNIX epoch and zone is the zone index
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleGetTimeSettings() {
String result;
TimeSettings::GetTimeSettingsData(result);
g_pServer->send(200, MimeJson, result);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// client call this to set the time zone index {zone: 4, server: "pool.ntp.org"}
// return status OK if success or failed
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleSetTimeSettings() {
if ( TimeSettings::ParseData(g_pServer) ) {
NTP.SetNTPServer(g_ModuleSettings.data.TimeServer);
g_pServer->send(200, MimeJson, StatusJsonTrue);
g_ModuleSettings.SaveSettings();
} else {
g_pServer->send(200, MimeJson, StatusJsonFalse);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// return settings to client
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleGetGeneral() {
String result;
General::GetGeneralData(g_pServer,result);
g_pServer->send(200, MimeJson, result);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Parse client data and save to the settings
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleSetGeneral() {
if ( General::ParseData(g_pServer) ) {
g_pServer->send(200, MimeJson, StatusJsonTrue);
g_ModuleSettings.SaveSettings();
} else {
g_pServer->send(200, MimeJson, StatusJsonFalse);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// return email and sms settings to client
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleGetEmailSms() {
String result;
EmailSmsSettings::GetEmailSmsSettings(g_pServer,result);
g_pServer->send(200, MimeJson, result);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Parse client data and save to the settings for email and sms
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleSetEmailSms() {
if ( EmailSmsSettings::ParseData(g_pServer) ) {
g_pServer->send(200, MimeJson, StatusJsonTrue);
g_ModuleSettings.SaveSettings();
} else {
g_pServer->send(200, MimeJson, StatusJsonFalse);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// return device information: {"name":"My Bedroom","cat:":"0","ip":"192.168.1.100","port":8080}
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleGetDeviceInfo() {
String buffer;
buffer.reserve(80);
buffer = "{\"name\":\"";
buffer += g_ModuleSettings.data.ModuleName;
buffer += "\",\"cat\":\"";
buffer += g_ModuleSettings.data.Category;
buffer += "\",\"ip\":\"";
buffer += WiFi.localIP().toString();
buffer += "\",\"port\":";
buffer += (int)g_ModuleSettings.data.port;
buffer +="}";
g_pServer->send(200, MimeJson, buffer);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// return a json of all inputs and output pin status
// {"gpi12":1,"gpo13":0}
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleGetGpio() {
String buffer;
int i;
buffer.reserve(64);
buffer = "{";
for (i=0; i<INPUT_PIN_COUNT; i++) {
delay(0);
if ( i>0 ) buffer += ",";
buffer += "\"gpi";
buffer += g_inputPins[i];
buffer += "\":";
buffer += g_InputPinMgmt.GetInputPinStatus(i);
}
for (i=0; i<OUTPUT_PIN_COUNT; i++) {
delay(0);
buffer += ",\"gpo";
buffer += g_outputPins[i];
buffer += "\":";
buffer += (int)(digitalRead(g_outputPins[i])==HIGH);
}
// for virtual pin arm/disarm
buffer += ",\"gpo";
buffer += g_ARM_OFF_PIN;
buffer += "\":";
buffer += (int)g_ArmLogic.getOutputActive();
for (i=0; i<BUTTON_PIN_COUNT; i++) {
delay(0);
buffer += ",\"gpo";
buffer += g_buttonPins[i];
buffer += "\":";
buffer += (int)(digitalRead(g_buttonPins[i])==HIGH);
}
buffer += "}";
g_pServer->send(200, MimeJson, buffer);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// receive: {cat: 1}
// return: [{"name":"Living Room","ip":"192.168.1.1","port":8080},{name:"Bed Room",ip:"192.168.1.2",port:8080}]
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleGetDeviceList() {
String buffer;
buffer.reserve(256);
udpServer.ParseData(g_pServer,buffer);
g_pServer->send(200, MimeJson, buffer);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleScanWiFi() {
String buffer;
buffer.reserve(256);
g_WifiList.GetWifiList(buffer);
g_pServer->send(200, MimeJson, buffer);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleGetNetworkSettings(bool bHead) {
String buffer;
buffer.reserve(256);
MyWiFi::GetWifiData(buffer,bHead);
g_pServer->send(200, MimeJson, buffer);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleSetNetworkSettings() {
if ( MyWiFi::ParseData(g_pServer) ) {
g_pServer->send(200, MimeJson, StatusJsonTrue);
g_ModuleSettings.SaveSettings();
} else {
g_pServer->send(200, MimeJson, StatusJsonFalse);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool StartAsWifiSTA() {
WiFi.softAPdisconnect();
WiFi.disconnect();
WiFi.mode(WIFI_STA);
TRACE("Trying to connect to WIFI");
// ip, gw, subnet, dns1, dns2
if ( !g_ModuleSettings.data.dhcp ) {
IPAddress ip;
IPAddress gw;
IPAddress mask;
TRACE("Using static IP");
if ( ip.fromString(g_ModuleSettings.data.ip)
&& gw.fromString(g_ModuleSettings.data.gw)
&& mask.fromString(g_ModuleSettings.data.mask) ) {
WiFi.config(ip, gw, mask, IPAddress(8,8,8,8), IPAddress(208,67,222,222));
}
else {
TRACE("Error: Invalid IP format");
}
}
else {
TRACE("Using DHCP");
}
WiFi.setAutoConnect(true);
WiFi.setAutoReconnect(true);
TRACE("Connecting to WIFI.");
TRACE2("SSID:",g_ModuleSettings.data.ssid);
TRACE2("PW:",g_ModuleSettings.data.pw);
if ( g_ModuleSettings.data.pw[0] ) WiFi.begin(g_ModuleSettings.data.ssid, g_ModuleSettings.data.pw);
else WiFi.begin(g_ModuleSettings.data.ssid);
for (int i=0; i<20; i++) {
if ( WiFi.isConnected() ) {
TRACE("CONNECTED!");
return true;
}
delay(500);
}
TRACE("Failed to connect to WIFI.\nStarting in AP Mode");
return false;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool StartAsWifiAP() {
WiFi.disconnect();
WiFi.mode(WIFI_AP_STA);
WiFi.softAPConfig(g_ApIp,g_ApIp,IPAddress(255,255,255,0));
g_pDnsServer = new DNSServer();
String ssid = "ESP" + String(ESP.getChipId());
bool bRvl = WiFi.softAP(ssid.c_str(),g_WifiApPassword);
if ( bRvl && g_pDnsServer ) {
// Setup the DNS server redirecting all the domains to the apIP
g_pDnsServer->setErrorReplyCode(DNSReplyCode::NoError);
g_pDnsServer->start(53, "*", g_ApIp);
}
return bRvl;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
void handleRebootEsp() {
g_pServer->send(200, MimeJson, StatusJsonTrue);
delay(100);
g_pServer->close();
ESP.restart();
}
///////////////////////////////
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
| [
"binhpham1909@gmail.com"
] | binhpham1909@gmail.com |
098607574dba40af93cac4f5e38cffd90c00d1f7 | d8f854a479641a793b775fa6b573543e32694a37 | /src/sender.hpp | 79b57cc6ab393e9946d493063362e6cc7dd27b63 | [] | no_license | dudelka/file_streamer | e8d3def168160d2ca05e863cff449a39f767bde5 | f2813fd960b700036208504ca209b71cc4f6aa0a | refs/heads/main | 2023-08-01T00:34:49.133633 | 2021-09-12T18:19:17 | 2021-09-12T18:19:17 | 395,458,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,022 | hpp | #pragma once
#include "socket.hpp"
#include "packet.hpp"
#include <string>
#ifdef CLIENT_MODE
#include "utils.hpp"
#include <cstdint>
#include <atomic>
#include <queue>
#include <list>
class Sender : public Multithreaded {
public:
Sender(const std::string& send_address, uint32_t resend_timeout);
void Connect();
void Shutdown();
void PushPacket(Packet packet);
virtual void Run() override;
void AckPacket(uint32_t id, uint32_t packet_num);
private:
Socket sock_;
uint32_t resend_timeout_;
std::queue<Packet> fifo_;
std::list<Packet> not_ack_packets_;
std::atomic<bool> has_packets_ {false};
std::atomic<bool> has_not_ack_packets_ {false};
LockPrimitives fifo_lock_;
LockPrimitives ack_lock_;
void SendControlPacket(const PacketType packet_type);
void ResendPackets();
};
#elif SERVER_MODE
class Sender {
public:
explicit Sender(const std::string& send_address);
void ProcessPacket(Packet packet);
private:
Socket sock_;
};
#endif
| [
"nbazargarmaev@gmail.com"
] | nbazargarmaev@gmail.com |
690384a8dc25e76b0c4115a91527ec013668a1c0 | 69bdd4914ac1a014a089325d468bf0c0ab2fd458 | /PHONELST.cpp | f5e5c9974f00eff2c3d939cd2754b4999814b14c | [] | no_license | ab1hi2shek/SPOJ-Solutions | f0185f8758fca2e4daa633e66739a17fc68d8f9d | d80da26241f19bf75f77c369d520b19e2520cd91 | refs/heads/master | 2021-07-04T01:37:56.219641 | 2017-09-26T17:23:50 | 2017-09-26T17:23:50 | 103,300,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | cpp | #include <bits/stdc++.h>
using namespace std;
//data types
#define ll long long int
//stl
typedef vector<ll> vi;
typedef vector<vi> vvi;
typedef pair<ll,ll> pii;
typedef map<ll,ll> mpll;
//loops
#define loop(i,a,b) for(ll i=a;i<=b;i++)
#define loopr(i,a,b) for(ll i=a;i>=b;i--)
#define SIZE 10
struct trie{
trie *child[SIZE];
bool isLeaf;
};
trie* getNode()
{
trie* root = new trie;
root->isLeaf = false;
for(int i=0;i<SIZE;i++)
root->child[i] = NULL;
return root;
}
int insert(trie *root, string s)
{
trie *temp = root;
ll flag = 0;
for(ll i=0;i<s.size();i++)
{
ll index = s[i]-'0';
//cout<<" index = "<<index<<endl;
if(!temp->child[index])
{
temp->child[index] = getNode();
flag = 1;
}
else
{
if(temp->child[index]->isLeaf)
return 0;
}
temp = temp->child[index];
}
temp->isLeaf = true;
return flag;
}
int main()
{
std::ios::sync_with_stdio(false);
ll t;
cin>>t;
while(t--)
{
trie *root = getNode();
ll n;
cin>>n;
bool ans = true;
for(ll i=0;i<n;i++)
{
string s;
cin>>s;
//cout<<s<<endl;
if(ans && !insert(root,s))
ans = false;
// cout<<insert(root,s)<<endl;
// if(insert(root,s) == false)
// break;
}
if(!ans)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
} | [
"ab1hi2shek@DESKTOP-FC3M4GT.localdomain"
] | ab1hi2shek@DESKTOP-FC3M4GT.localdomain |
2456f9c26d8c92f9cbdb4fc19f2abbdfdec5250d | 5470644b5f0834b9646649da365c96101a2f9b2a | /Sources/Elastos/Frameworks/Droid/Base/Core/inc/text/method/DigitsKeyListener.h | 792dd387ebee09cbe44de8e8a1cc67d50537801e | [] | no_license | dothithuy/ElastosRDK5_0 | 42372da3c749170581b5ee9b3884f4a27ae81608 | 2cf231e9f09f8b3b8bcacb11080b4a87d047833f | refs/heads/master | 2021-05-13T15:02:22.363934 | 2015-05-25T01:54:38 | 2015-05-25T01:54:38 | 116,755,452 | 1 | 0 | null | 2018-01-09T02:33:06 | 2018-01-09T02:33:06 | null | UTF-8 | C++ | false | false | 2,485 | h | #ifndef __DigitsKeyListener_H__
#define __DigitsKeyListener_H__
#include "text/method/NumberKeyListener.h"
namespace Elastos {
namespace Droid {
namespace Text {
namespace Method {
extern "C" const InterfaceID EIID_DigitsKeyListener;
/**
* For digits-only text entry
* <p></p>
* As for all implementations of {@link KeyListener}, this class is only concerned
* with hardware keyboards. Software input methods have no obligation to trigger
* the methods in this class.
*/
class DigitsKeyListener : public NumberKeyListener
{
public:
/**
* Allocates a DigitsKeyListener that accepts the digits 0 through 9.
*/
DigitsKeyListener();
/**
* Allocates a DigitsKeyListener that accepts the digits 0 through 9,
* plus the minus sign (only at the beginning) and/or decimal point
* (only one per field) if specified.
*/
DigitsKeyListener(
/* [in] */ Boolean sign,
/* [in] */ Boolean decimal);
static CARAPI_(AutoPtr<IDigitsKeyListener>) GetInstance();
static CARAPI_(AutoPtr<IDigitsKeyListener>) GetInstance(
/* [in] */ Boolean sign,
/* [in] */ Boolean decimal);
static CARAPI_(AutoPtr<IDigitsKeyListener>) GetInstance(
/* [in] */ const String& accepted);
CARAPI_(void) Init();
CARAPI_(void) Init(
/* [in] */ Boolean sign,
/* [in] */ Boolean decimal);
CARAPI_(Int32) GetInputType();
//@Override
CARAPI_(AutoPtr<ICharSequence>) Filter(
/* [in] */ ICharSequence* source,
/* [in] */ Int32 start,
/* [in] */ Int32 end,
/* [in] */ ISpanned* dest,
/* [in] */ Int32 dstart,
/* [in] */ Int32 dend);
protected:
//@Override
CARAPI_(AutoPtr< ArrayOf<Char32> >) GetAcceptedChars();
protected:
static const Int32 SIGN;// = 1;
static const Int32 DECIMAL;// = 2;
/**
* The characters that are used.
*
* @see KeyEvent#getMatch
* @see #getAcceptedChars
*/
AutoPtr< ArrayOf<Char32> > mAccepted;
private:
Boolean mSign;
Boolean mDecimal;
static const Char32* CHARACTERS[];
static const Char32 CHARACTERS0[];
static const Char32 CHARACTERS1[];
static const Char32 CHARACTERS2[];
static const Char32 CHARACTERS3[];
static AutoPtr< ArrayOf< IDigitsKeyListener* > > sInstance;// = new DigitsKeyListener[4];
};
} // namespace Method
} // namespace Text
} // namepsace Droid
} // namespace Elastos
#endif // __DigitsKeyListener_H__
| [
"chen.yunzhi@kortide.com"
] | chen.yunzhi@kortide.com |
236741d68b3ba05de79b872aaecda117efa339cb | 37cca16f12e7b1d4d01d6f234da6d568c318abee | /src/rice/pastry/socket/nat/connectivityverifiier/ConnectivityVerifierImpl_findExternalNodesHelper_3_receiveResult_3_1.hpp | c54da7f810897c6ed9fbe0155645beec41c6778f | [] | no_license | subhash1-0/thirstyCrow | e48155ce68fc886f2ee8e7802567c1149bc54206 | 78b7e4e3d2b9a9530ad7d66b44eacfe73ceea582 | refs/heads/master | 2016-09-06T21:25:54.075724 | 2015-09-21T17:21:15 | 2015-09-21T17:21:15 | 42,881,521 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,412 | hpp | // Generated from /pastry-2.1/src/rice/pastry/socket/nat/connectivityverifiier/ConnectivityVerifierImpl.java
#pragma once
#include <java/util/fwd-pastry-2.1.hpp>
#include <rice/fwd-pastry-2.1.hpp>
#include <rice/pastry/socket/nat/connectivityverifiier/fwd-pastry-2.1.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/Runnable.hpp>
struct default_init_tag;
class rice::pastry::socket::nat::connectivityverifiier::ConnectivityVerifierImpl_findExternalNodesHelper_3_receiveResult_3_1
: public virtual ::java::lang::Object
, public virtual ::java::lang::Runnable
{
public:
typedef ::java::lang::Object super;
void run() override;
// Generated
ConnectivityVerifierImpl_findExternalNodesHelper_3_receiveResult_3_1(ConnectivityVerifierImpl_findExternalNodesHelper_3 *ConnectivityVerifierImpl_findExternalNodesHelper_3_this, ::rice::Continuation* deliverResultToMe, ::java::util::Collection* result);
static ::java::lang::Class *class_();
ConnectivityVerifierImpl_findExternalNodesHelper_3 *ConnectivityVerifierImpl_findExternalNodesHelper_3_this;
::rice::Continuation* deliverResultToMe;
::java::util::Collection* result;
private:
virtual ::java::lang::Class* getClass0();
friend class ConnectivityVerifierImpl;
friend class ConnectivityVerifierImpl_getInetSocketAddressLookup_1;
friend class ConnectivityVerifierImpl_findExternalNodes_2;
friend class ConnectivityVerifierImpl_findExternalNodesHelper_3;
friend class ConnectivityVerifierImpl_findExternalNodesHelper_3_receiveException_3_2;
friend class ConnectivityVerifierImpl_findExternalAddress_4;
friend class ConnectivityVerifierImpl_findExternalAddressHelper_5;
friend class ConnectivityVerifierImpl_findExternalAddressHelper_5_receiveResult_5_1;
friend class ConnectivityVerifierImpl_findExternalAddressHelper_5_receiveException_5_2;
friend class ConnectivityVerifierImpl_verifyConnectivity_6;
friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_1;
friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_2;
friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_2_udpSuccess_6_2_1;
friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_2_tcpSuccess_6_2_2;
friend class ConnectivityVerifierImpl_verifyConnectivity_6_receiveResult_6_2_receiveException_6_2_3;
};
| [
"sgurjar@adobe.com"
] | sgurjar@adobe.com |
0553178a51410ac56d2588fecaaabe1cbb1817d8 | c76796ac315152b9c701c120be2562bded1ac584 | /ObjectInserter.h | 35ed93878a5d44ea61575a6e60c59bd9cb5fff93 | [] | no_license | shocklateboy92/conemaker2 | 6983ea8f5410ffb791422eaf6e177c0615e139cc | 0e5ddda7d8b154bae8313f6f4898e3fed7ea2400 | refs/heads/master | 2016-09-15T22:24:49.176141 | 2014-05-13T23:41:49 | 2014-05-13T23:41:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 513 | h | #ifndef CONEMAKER_OBJECTINSERTER_H
#define CONEMAKER_OBJECTINSERTER_H
#include "Tool.h"
#include <Ogre.h>
namespace ConeMaker {
class ObjectInserter : public Tool
{
public:
ObjectInserter(Ogre::SceneNode *cursor);
// MouseListener interface
public:
virtual bool mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id);
// Tool interface
public:
virtual void setup();
private:
Ogre::SceneNode *m_cursorNode;
};
} // namespace ConeMaker
#endif // CONEMAKER_OBJECTINSERTER_H
| [
"kde@lasath.org"
] | kde@lasath.org |
03fc0ef2fa87babe7dd145f194bf2877f802bb23 | f426375bc339ae8f5c6244dc47bd453c6dce1371 | /Classes/HelloWorldScene.h | 77807375ec36b3988f3f8fb1ddc9445432c54c2c | [] | no_license | TunerRed/HeroRun | dc21caea374d1acff6131095ccdd4766806962a2 | c3a3ac3b8fe7b98c596a9a040887403323767dbe | refs/heads/master | 2020-03-25T13:51:22.138757 | 2018-09-17T04:08:06 | 2018-09-17T04:08:06 | 143,846,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 310 | h | #ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
USING_NS_CC;
class HelloWorld : public cocos2d::Layer
{
public:
ActionInterval *action[5];
static cocos2d::Scene* createScene();
virtual bool init();
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
| [
"12877111966@qq.com"
] | 12877111966@qq.com |
a74605e6cb5132d3d5a09516616aafbc45402db4 | dfe1f796a54143e5eb8661f3328ad29dbfa072d6 | /psx/_dump_/23/_dump_c_src_/diabpsx/source/lighting.cpp | 394f829720bb799182612df5d02a2e3cc7728022 | [
"Unlicense"
] | permissive | diasurgical/scalpel | 0f73ad9be0750ce08eb747edc27aeff7931800cd | 8c631dff3236a70e6952b1f564d0dca8d2f4730f | refs/heads/master | 2021-06-10T18:07:03.533074 | 2020-04-16T04:08:35 | 2020-04-16T04:08:35 | 138,939,330 | 15 | 7 | Unlicense | 2019-08-27T08:45:36 | 2018-06-27T22:30:04 | C | UTF-8 | C++ | false | false | 5,311 | cpp | // C:\diabpsx\SOURCE\LIGHTING.CPP
#include "types.h"
// address: 0x800453FC
// line start: 319
// line end: 334
int veclen2__Fii(int ix, int iy) {
// register: 4
register int t;
}
// address: 0x80045464
// line start: 380
// line end: 399
void set_light_bands__Fv() {
// register: 2
register int v;
// register: 5
register int y;
// register: 4
register int c;
}
// address: 0x800454D8
// line start: 404
// line end: 411
void SetLightFX__FiisssUcUcUc(int x, int y, short s_r, short s_g, int s_b, int d_r, int d_g, int d_b) {
}
// address: 0x80045544
// line start: 415
// line end: 765
void DoLighting__Fiiii(int nXPos, int nYPos, int nRadius, int Lnum) {
// register: 9
register int xoff;
// register: 10
register int yoff;
// register: 20
register int x;
// register: 30
register int y;
// register: 4
register int v;
// register: 22
register int colour_mask;
// register: 17
register int shift_mask;
// register: 12
register int shake;
// address: 0xFFFFFFA8
auto int light_x;
// address: 0xFFFFFFB0
auto int light_y;
// address: 0xFFFFFFB8
auto int block_x;
// register: 9
register int block_y;
// register: 23
register int dist_y;
// register: 11
register int max_x;
// register: 6
register int mult;
// register: 7
register int mult_st;
// register: 21
register int radius_block;
// register: 7
register int scr_x;
// register: 8
register int scr_y;
// register: 6
register int temp_x;
// register: 5
register int temp_y;
// register: 19
register int weirdy;
// register: 11
register int cont;
}
// address: 0x800461F4
// line start: 771
// line end: 819
void DoUnLight__Fv() {
// register: 6
register int x;
// register: 7
register int y;
// register: 11
register int max_x;
// register: 16
register int max_y;
// register: 14
register int radius_block;
// register: 13
register int nXPos;
// register: 12
register int nYPos;
}
// address: 0x80046438
// line start: 826
// line end: 841
void DoUnVision__Fiii(int nXPos, int nYPos, int nRadius) {
// register: 4
register int i;
// register: 6
register int j;
// register: 3
register int x1;
// register: 9
register int y1;
// register: 8
register int x2;
// register: 5
register int y2;
}
// address: 0x800464FC
// line start: 848
// line end: 952
void DoVision__FiiiUcUc(int nXPos, int nYPos, int nRadius, unsigned char doautomap, int visible) {
// register: 16
register int nCrawlX;
// register: 19
register int nCrawlY;
// register: 9
register int nLineLen;
// register: 21
register int nBlockerFlag;
// register: 8
register int j;
// register: 20
register int k;
// register: 2
register int v;
// register: 5
register int x1adj;
// register: 7
register int x2adj;
// register: 4
register int y1adj;
// register: 6
register int y2adj;
}
// address: 0x80046A0C
// line start: 957
// line end: 958
void FreeLightTable__Fv() {
}
// address: 0x80046A14
// line start: 964
// line end: 965
void InitLightTable__Fv() {
}
// address: 0x80046A1C
// line start: 970
// line end: 971
void MakeLightTable__Fv() {
}
// address: 0x80046A24
// line start: 1062
// line end: 1065
void InitLightMax__Fv() {
}
// address: 0x80046A48
// line start: 1072
// line end: 1083
void InitLighting__Fv() {
// register: 2
register int i;
}
// address: 0x80046A8C
// line start: 1089
// line end: 1105
int AddLight__Fiii(int x, int y, int r) {
// register: 7
register int lid;
}
// address: 0x80046B20
// line start: 1110
// line end: 1116
void AddUnLight__Fi(int i) {
}
// address: 0x80046B50
// line start: 1121
// line end: 1131
void ChangeLightRadius__Fii(int i, int r) {
}
// address: 0x80046B7C
// line start: 1136
// line end: 1147
void ChangeLightXY__Fiii(int i, int x, int y) {
}
// address: 0x80046BB4
// line start: 1150
// line end: 1156
void light_fix__Fi(int i) {
}
// address: 0x80046BBC
// line start: 1166
// line end: 1178
void ChangeLightOff__Fiii(int i, int x, int y) {
}
// address: 0x80046BF4
// line start: 1183
// line end: 1195
void ChangeLight__Fiiii(int i, int x, int y, int r) {
}
// address: 0x80046C38
// line start: 1198
// line end: 1199
void ChangeLightColour__Fii(int i, int c) {
}
// address: 0x80046C68
// line start: 1205
// line end: 1266
void ProcessLightList__Fv() {
// register: 7
register int i;
// register: 16
register int j;
// register: 4
register unsigned char temp;
}
// address: 0x80046D94
// line start: 1271
// line end: 1298
void SavePreLighting__Fv() {
}
// address: 0x80046D9C
// line start: 1303
// line end: 1310
void InitVision__Fv() {
// register: 4
register int i;
}
// address: 0x80046DEC
// line start: 1317
// line end: 1333
int AddVision__FiiiUc(int x, int y, int r, unsigned char mine) {
// register: 8
register int vid;
}
// address: 0x80046EF0
// line start: 1356
// line end: 1369
void ChangeVisionRadius__Fii(int id, int r) {
// register: 8
register int i;
}
// address: 0x80046FA4
// line start: 1374
// line end: 1388
void ChangeVisionXY__Fiii(int id, int x, int y) {
// register: 10
register int i;
}
// address: 0x8004705C
// line start: 1417
// line end: 1446
void ProcessVisionList__Fv() {
// register: 17
register int i;
// register: 4
register unsigned char delflag;
}
| [
"rnd0x00@gmail.com"
] | rnd0x00@gmail.com |
07d6728a9182ed1a39c77d9ce33b8be446490452 | 0e6c9a7187fd0d3ff3e6419c3041fa04e50e192e | /deimos/llvm/c/bitwriter.d | 727e33e80e07db370d2dc0339f2d260b48cfccd6 | [] | no_license | jkm/deimos-llvm | 45511e009a6982493bda7d2f8567d545a3299a0b | 25b58cec1c5a053e44a7ad8e1167d1515032ae2f | refs/heads/master | 2020-06-08T14:17:30.833067 | 2014-02-15T21:33:48 | 2014-02-15T21:33:48 | 5,119,416 | 1 | 1 | null | 2017-02-18T19:40:25 | 2012-07-20T05:16:18 | D | UTF-8 | C++ | false | false | 2,145 | d | /*===-- llvm-c/BitWriter.h - BitWriter Library C Interface ------*- C++ -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This header declares the C interface to libLLVMBitWriter.a, which *|
|* implements output of the LLVM bitcode format. *|
|* *|
|* Many exotic languages can interoperate with C code but have a harder time *|
|* with C++ due to name mangling. So in addition to C, this interface enables *|
|* tools written in such languages. *|
|* *|
\*===----------------------------------------------------------------------===*/
module deimos.llvm.c.bitwriter;
import deimos.llvm.c.core;
extern(C) nothrow:
/**
* @defgroup LLVMCBitWriter Bit Writer
* @ingroup LLVMC
*
* @{
*/
/*===-- Operations on modules ---------------------------------------------===*/
/** Writes a module to the specified path. Returns 0 on success. */
int LLVMWriteBitcodeToFile(LLVMModuleRef M, const(char) *Path);
/** Writes a module to an open file descriptor. Returns 0 on success. */
int LLVMWriteBitcodeToFD(LLVMModuleRef M, int FD, int ShouldClose,
int Unbuffered);
/** Deprecated for LLVMWriteBitcodeToFD. Writes a module to an open file
descriptor. Returns 0 on success. Closes the Handle. */
int LLVMWriteBitcodeToFileHandle(LLVMModuleRef M, int Handle);
/**
* @}
*/
| [
"jkm@gluey.org"
] | jkm@gluey.org |
f90a5fb6203ff252c3aa3371018b448b9b15fedf | be0204c1b95839adee1ad204be022be38e32e2d6 | /BOJ/1003.cpp | 5d7c948297e279a1d5391ac594f7a700c9942836 | [] | no_license | tlsdorye/Problem-Solving | 507bc8d3cf1865c10067ef2e8eb7cb2ee42e16dd | 5c112d2238bfb1fc092612a76f10c7785ba86c78 | refs/heads/master | 2021-06-12T19:19:19.337092 | 2021-04-23T06:39:43 | 2021-04-23T06:39:43 | 179,432,390 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 409 | cpp | #include <iostream>
using namespace std;
int fibo[41][2];
void makeFibo() {
fibo[0][0] = 1;
fibo[0][1] = 0;
fibo[1][0] = 0;
fibo[1][1] = 1;
for (int i = 2; i <= 40; i++) {
fibo[i][0] = fibo[i - 1][1];
fibo[i][1] = fibo[i - 1][0] + fibo[i - 1][1];
}
}
int main() {
makeFibo();
int n;
cin >> n;
while (n--) {
int tmp;
cin >> tmp;
cout << fibo[tmp][0] << " " << fibo[tmp][1] << endl;
}
} | [
"tlsdorye@gmail.com"
] | tlsdorye@gmail.com |
0e67e467f3c4fb6aabeeb1789b6b3fe9d0bc726e | e09a7d5e9c8a2a2a2dc7b6d972d6d62e7db284e3 | /Dynamic Programming/number_of_balanced_binary_tree.cpp | b7f833d551e5b917984a45db2b527bc35feef425 | [] | no_license | yuktajuneja/Data-Structure-Coding-ninjas | 5254ef0e2d4d1bc02c22c1aebe746bcbe6eba2e6 | 200891531364aca9b4baa650a035d4db7a415600 | refs/heads/main | 2023-08-16T10:39:47.996011 | 2021-09-28T08:22:14 | 2021-09-28T08:22:14 | 405,596,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,199 | cpp | /*
Given an integer h, find the possible number of balanced binary trees of height h. You just need to return the count of possible binary trees which are balanced.
This number can be huge, so return output modulus 10^9 + 7.
*/
#include<iostream>
using namespace std;
#include<cmath>
int count_of_bt1(int n){
if(n<=1){
return 1;
}
int mod=(int) (pow(10,9)) +7;
int x=count_of_bt1(n-1);
int y=count_of_bt1(n-2);
int x1=(int) ( ( (long)(x) *x) % mod);
int y1=(int) ( (2* (long)(x) *y) % mod);
int ans= ((x1+y1)%mod);
return ans;
}
int helper(int n,int* ans){
if(n<=1){
return 1;
}
if(ans[n]!=-1){
return ans[n];
}
int x=helper(n-1,ans);
int y=helper(n-2,ans);
ans[n]=(x*x)+(2*(x*y));
return ans[n];
}
int count_of_bt2(int n){
int*ans=new int[n+1];
for(int i=0;i<n+1;i++){
ans[i]=-1;
}
return helper(n,ans);
}
int count_of_bt3(int n){
int ans[n+1];
ans[0]=ans[1]=1;
for(int i=2;i<=n;i++){
int x=ans[i-1];
int y=ans[i-2];
ans[i]= (x*x)+(2*(x*y));
}
return ans[n];
}
int main(int argc, char const *argv[]) {
int n;
cin>>n;
cout<<count_of_bt1(n)<<" "<<count_of_bt2(n)<<" "<<count_of_bt3(n)<<endl;
return 0;
}
| [
"yukta.juneja1582@gmail.com"
] | yukta.juneja1582@gmail.com |
599c82acea40477281e2a0e2e79cb2e2e65d1c9e | eead3440d191939b0288b33599a1a9bdb72e4280 | /Arrays & Strings/spiral_anti.cpp | 161b419e1046022a912f7b20c79ed48bcf2f66a5 | [] | no_license | Akp6528/DS-Algo | f1cd1d2624be6747e237055e8c1bced7ca499e00 | 63e38c9263e46332f62011ce053555fc9cdf7021 | refs/heads/main | 2023-04-18T12:08:09.078473 | 2021-05-04T08:28:04 | 2021-05-04T08:28:04 | 300,832,214 | 1 | 1 | null | 2020-10-14T13:24:57 | 2020-10-03T08:23:58 | C++ | UTF-8 | C++ | false | false | 939 | cpp | #include<iostream>
using namespace std;
void spiral(int a[][100], int m, int n) {
int startRow = 0;
int startCol = 0;
int endRow = m-1;
int endCol = n-1;
while(startRow <= endRow and startCol <= endCol){
// 1
for(int i=startRow; i<=endRow; i++)
cout<<a[i][startCol]<<", ";
startCol++;
//2
for(int i=startCol; i<=endCol; i++)
cout<<a[endRow][i] <<", ";
endRow--;
//3
if(endRow > startRow){
for(int i=endRow; i>=startRow; i--)
cout<<a[i][endCol]<<", ";
endCol--;
}
//4
if(endCol > startCol) {
for(int i=endCol; i>=startCol; i--)
cout<<a[startRow][i]<<", ";
startRow++;
}
}
}
int main(){
int a[100][100] ;
int m,n;
cin>>m>>n;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
cin>>a[i][j];
}
}
spiral(a,m,n);
cout<<"END";
return 0;
}
| [
"pandeyashwani999@gmail.com"
] | pandeyashwani999@gmail.com |
c583c58cd155c70d0f13223d477c5ad24f44e2ae | 47de9c88b957dc66c46769f40103d5147b00b7c9 | /codeforces/609/C.cpp | 835488ef50d68d9863bd9709a67dfb32c6b45bd7 | [] | no_license | autul2017831021/Codeforces_Atcoder_Solved_Problems | 1027a606b3cb5be80e57fcfbcfa0327ebd47bd95 | b95e432718c9393f8a781fa56c2ed65f082274f5 | refs/heads/master | 2023-07-02T02:23:58.307782 | 2021-03-01T13:00:00 | 2021-07-31T15:40:28 | 329,067,317 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 827 | cpp | using namespace std;
#include<bits/stdc++.h>
typedef long long int ll;
typedef double dl;
#define pb push_back
#define bg begin()
#define en end()
#define rbg rbegin()
#define ren rend()
#define sz size()
#define r0 return 0
#define F first
#define S second
#define inf 9999999999
#define its (*it).S
#define itf (*it).F
#define nl cout<<endl;
main()
{
ll n,c=0,s=0;
cin>>n;
vector<ll>v,w;
for(int i=0;i<n;i++)
{
ll x;
cin>>x;
v.pb(x);
s+=x;
}
sort(v.rbg,v.ren);
if(v[0]-v[n-1]==1 || n==1)
{
cout<<c;nl
r0;
}
ll av,m;
av=s/n;
m=s%n;
for(int i=0;i<n;i++)
w.pb(av);
for(int i=0;i<m;i++)
w[i]+=1;
for(int i=0;i<n;i++)
{
if(w[i]<v[i])
c=c+(v[i]-w[i]);
}
cout<<c<<endl;
}
| [
"alexiautul@gmail.com"
] | alexiautul@gmail.com |
c080bfc93864a58c321390627a1c6a9ef9b94a6f | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qttools/src/designer/src/components/formeditor/formwindow.h | 802b27f707a671c8a0c75e20556ed2ba641ed215 | [
"Qt-LGPL-exception-1.1",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"LGPL-3.0-only",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"GFDL-1.3-only",
"LicenseRef-scancode-digia-qt-preview",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-generic-exception"
] | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 12,172 | h | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef FORMWINDOW_H
#define FORMWINDOW_H
#include "formeditor_global.h"
#include "qdesignerundostack.h"
#include <formwindowbase_p.h>
// Qt
#include <QtCore/QHash>
#include <QtCore/QList>
#include <QtCore/QMap>
#include <QtCore/QSet>
#include <QtCore/QPointer>
QT_BEGIN_NAMESPACE
class QDesignerDnDItemInterface;
class QDesignerTaskMenuExtension;
class DomConnections;
class DomUI;
class QWidget;
class QAction;
class QLabel;
class QTimer;
class QAction;
class QMenu;
class QRubberBand;
namespace qdesigner_internal {
class FormEditor;
class FormWindowCursor;
class WidgetEditorTool;
class FormWindowWidgetStack;
class FormWindowManager;
class FormWindowDnDItem;
class SetPropertyCommand;
class QT_FORMEDITOR_EXPORT FormWindow: public FormWindowBase
{
Q_OBJECT
public:
explicit FormWindow(FormEditor *core, QWidget *parent = 0, Qt::WindowFlags flags = 0);
virtual ~FormWindow();
QDesignerFormEditorInterface *core() const Q_DECL_OVERRIDE;
QDesignerFormWindowCursorInterface *cursor() const Q_DECL_OVERRIDE;
// Overwritten: FormWindowBase
QWidget *formContainer() const Q_DECL_OVERRIDE;
int toolCount() const Q_DECL_OVERRIDE;
int currentTool() const Q_DECL_OVERRIDE;
void setCurrentTool(int index) Q_DECL_OVERRIDE;
QDesignerFormWindowToolInterface *tool(int index) const Q_DECL_OVERRIDE;
void registerTool(QDesignerFormWindowToolInterface *tool) Q_DECL_OVERRIDE;
QString author() const Q_DECL_OVERRIDE;
void setAuthor(const QString &author) Q_DECL_OVERRIDE;
QString comment() const Q_DECL_OVERRIDE;
void setComment(const QString &comment) Q_DECL_OVERRIDE;
void layoutDefault(int *margin, int *spacing) Q_DECL_OVERRIDE;
void setLayoutDefault(int margin, int spacing) Q_DECL_OVERRIDE;
void layoutFunction(QString *margin, QString *spacing) Q_DECL_OVERRIDE;
void setLayoutFunction(const QString &margin, const QString &spacing) Q_DECL_OVERRIDE;
QString pixmapFunction() const Q_DECL_OVERRIDE;
void setPixmapFunction(const QString &pixmapFunction) Q_DECL_OVERRIDE;
QString exportMacro() const Q_DECL_OVERRIDE;
void setExportMacro(const QString &exportMacro) Q_DECL_OVERRIDE;
QStringList includeHints() const Q_DECL_OVERRIDE;
void setIncludeHints(const QStringList &includeHints) Q_DECL_OVERRIDE;
QString fileName() const Q_DECL_OVERRIDE;
void setFileName(const QString &fileName) Q_DECL_OVERRIDE;
QString contents() const Q_DECL_OVERRIDE;
bool setContents(QIODevice *dev, QString *errorMessage = 0) Q_DECL_OVERRIDE;
bool setContents(const QString &) Q_DECL_OVERRIDE;
QDir absoluteDir() const Q_DECL_OVERRIDE;
void simplifySelection(QWidgetList *sel) const Q_DECL_OVERRIDE;
void ensureUniqueObjectName(QObject *object) Q_DECL_OVERRIDE;
QWidget *mainContainer() const Q_DECL_OVERRIDE;
void setMainContainer(QWidget *mainContainer) Q_DECL_OVERRIDE;
bool isMainContainer(const QWidget *w) const;
QWidget *currentWidget() const;
bool hasInsertedChildren(QWidget *w) const;
QList<QWidget *> selectedWidgets() const;
void clearSelection(bool changePropertyDisplay = true) Q_DECL_OVERRIDE;
bool isWidgetSelected(QWidget *w) const;
void selectWidget(QWidget *w, bool select = true) Q_DECL_OVERRIDE;
void selectWidgets();
void repaintSelection();
void updateSelection(QWidget *w);
void updateChildSelections(QWidget *w);
void raiseChildSelections(QWidget *w);
void raiseSelection(QWidget *w);
inline const QList<QWidget *>& widgets() const { return m_widgets; }
inline int widgetCount() const { return m_widgets.count(); }
inline QWidget *widgetAt(int index) const { return m_widgets.at(index); }
QList<QWidget *> widgets(QWidget *widget) const;
QWidget *createWidget(DomUI *ui, const QRect &rect, QWidget *target);
bool isManaged(QWidget *w) const Q_DECL_OVERRIDE;
void manageWidget(QWidget *w) Q_DECL_OVERRIDE;
void unmanageWidget(QWidget *w) Q_DECL_OVERRIDE;
QUndoStack *commandHistory() const Q_DECL_OVERRIDE;
void beginCommand(const QString &description) Q_DECL_OVERRIDE;
void endCommand() Q_DECL_OVERRIDE;
bool blockSelectionChanged(bool blocked) Q_DECL_OVERRIDE;
void emitSelectionChanged() Q_DECL_OVERRIDE;
bool unify(QObject *w, QString &s, bool changeIt);
bool isDirty() const Q_DECL_OVERRIDE;
void setDirty(bool dirty) Q_DECL_OVERRIDE;
static FormWindow *findFormWindow(QWidget *w);
virtual QWidget *containerAt(const QPoint &pos);
QWidget *widgetAt(const QPoint &pos) Q_DECL_OVERRIDE;
void highlightWidget(QWidget *w, const QPoint &pos, HighlightMode mode = Highlight) Q_DECL_OVERRIDE;
void updateOrderIndicators();
bool handleEvent(QWidget *widget, QWidget *managedWidget, QEvent *event);
QStringList resourceFiles() const Q_DECL_OVERRIDE;
void addResourceFile(const QString &path) Q_DECL_OVERRIDE;
void removeResourceFile(const QString &path) Q_DECL_OVERRIDE;
void resizeWidget(QWidget *widget, const QRect &geometry);
bool dropDockWidget(QDesignerDnDItemInterface *item, const QPoint &global_mouse_pos);
bool dropWidgets(const QList<QDesignerDnDItemInterface*> &item_list, QWidget *target,
const QPoint &global_mouse_pos) Q_DECL_OVERRIDE;
QWidget *findContainer(QWidget *w, bool excludeLayout) const Q_DECL_OVERRIDE;
// for WidgetSelection only.
QWidget *designerWidget(QWidget *w) const;
// Initialize and return a popup menu for a managed widget
QMenu *initializePopupMenu(QWidget *managedWidget) Q_DECL_OVERRIDE;
#ifndef QT_NO_CLIPBOARD
void paste(PasteMode pasteMode) Q_DECL_OVERRIDE;
#endif
virtual QEditorFormBuilder *createFormBuilder() Q_DECL_OVERRIDE;
bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE;
signals:
void contextMenuRequested(QMenu *menu, QWidget *widget);
public slots:
void deleteWidgets();
void raiseWidgets();
void lowerWidgets();
#ifndef QT_NO_CLIPBOARD
void copy();
void cut();
void paste();
#endif
void selectAll();
void createLayout(int type, QWidget *container = 0);
void morphLayout(QWidget *container, int newType);
void breakLayout(QWidget *w);
void editContents();
protected:
virtual QMenu *createPopupMenu(QWidget *w);
void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE;
void insertWidget(QWidget *w, const QRect &rect, QWidget *target, bool already_in_form = false);
private slots:
void selectionChangedTimerDone();
void checkSelection();
void checkSelectionNow();
void slotSelectWidget(QAction *);
private:
enum MouseState {
NoMouseState,
// Double click received
MouseDoubleClicked,
// Drawing selection rubber band rectangle
MouseDrawRubber,
// Started a move operation
MouseMoveDrag,
// Click on a widget whose parent is selected. Defer selection to release
MouseDeferredSelection
};
MouseState m_mouseState;
QPointer<QWidget> m_lastClickedWidget;
void init();
void initializeCoreTools();
int getValue(const QRect &rect, int key, bool size) const;
int calcValue(int val, bool forward, bool snap, int snapOffset) const;
void handleClickSelection(QWidget *managedWidget, unsigned mouseFlags);
bool frameNeeded(QWidget *w) const;
enum RectType { Insert, Rubber };
void startRectDraw(const QPoint &global, QWidget *, RectType t);
void continueRectDraw(const QPoint &global, QWidget *, RectType t);
void endRectDraw();
QWidget *containerAt(const QPoint &pos, QWidget *notParentOf);
void checkPreviewGeometry(QRect &r);
bool handleContextMenu(QWidget *widget, QWidget *managedWidget, QContextMenuEvent *e);
bool handleMouseButtonDblClickEvent(QWidget *widget, QWidget *managedWidget, QMouseEvent *e);
bool handleMousePressEvent(QWidget *widget, QWidget *managedWidget, QMouseEvent *e);
bool handleMouseMoveEvent(QWidget *widget, QWidget *managedWidget, QMouseEvent *e);
bool handleMouseReleaseEvent(QWidget *widget, QWidget *managedWidget, QMouseEvent *e);
bool handleKeyPressEvent(QWidget *widget, QWidget *managedWidget, QKeyEvent *e);
bool handleKeyReleaseEvent(QWidget *widget, QWidget *managedWidget, QKeyEvent *e);
bool isCentralWidget(QWidget *w) const;
bool setCurrentWidget(QWidget *currentWidget);
bool trySelectWidget(QWidget *w, bool select);
void dragWidgetWithinForm(QWidget *widget, const QRect &targetGeometry, QWidget *targetContainer);
void setCursorToAll(const QCursor &c, QWidget *start);
QPoint mapToForm(const QWidget *w, const QPoint &pos) const;
bool canBeBuddy(QWidget *w) const;
QWidget *findTargetContainer(QWidget *widget) const;
void clearMainContainer();
static int widgetDepth(const QWidget *w);
static bool isChildOf(const QWidget *c, const QWidget *p);
void editWidgets() Q_DECL_OVERRIDE;
void updateWidgets();
void handleArrowKeyEvent(int key, Qt::KeyboardModifiers modifiers);
void layoutSelection(int type);
void layoutContainer(QWidget *w, int type);
private:
QWidget *innerContainer(QWidget *outerContainer) const;
QWidget *containerForPaste() const;
QAction *createSelectAncestorSubMenu(QWidget *w);
void selectSingleWidget(QWidget *w);
FormEditor *m_core;
FormWindowCursor *m_cursor;
QWidget *m_mainContainer;
QWidget *m_currentWidget;
bool m_blockSelectionChanged;
QPoint m_rectAnchor;
QRect m_currRect;
QWidgetList m_widgets;
QSet<QWidget*> m_insertedWidgets;
class Selection;
Selection *m_selection;
QPoint m_startPos;
QDesignerUndoStack m_undoStack;
QString m_fileName;
typedef QPair<QPalette ,bool> PaletteAndFill;
typedef QMap<QWidget*, PaletteAndFill> WidgetPaletteMap;
WidgetPaletteMap m_palettesBeforeHighlight;
QRubberBand *m_rubberBand;
QTimer *m_selectionChangedTimer;
QTimer *m_checkSelectionTimer;
QTimer *m_geometryChangedTimer;
FormWindowWidgetStack *m_widgetStack;
WidgetEditorTool *m_widgetEditor;
QStringList m_resourceFiles;
QString m_comment;
QString m_author;
QString m_pixmapFunction;
int m_defaultMargin, m_defaultSpacing;
QString m_marginFunction, m_spacingFunction;
QString m_exportMacro;
QStringList m_includeHints;
QPoint m_contextMenuPosition;
private:
friend class WidgetEditorTool;
};
} // namespace qdesigner_internal
QT_END_NAMESPACE
#endif // FORMWINDOW_H
| [
"p_pavlov@wargaming.net"
] | p_pavlov@wargaming.net |
d9c68afd6c6836c865f5b05206068ee5daf0bd89 | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/libstdc++-v3/testsuite/experimental/filesystem/path/compare/strings.cc | 19d22664226152615e03b366d224653b4c18c68c | [
"Zlib",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 1,414 | cc | // { dg-options "-DUSE_FILESYSTEM_TS -lstdc++fs" }
// { dg-do run { target c++11 } }
// { dg-require-filesystem-ts "" }
// Copyright (C) 2014-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 8.4.8 path compare [path.compare]
#include <experimental/filesystem>
#include <testsuite_hooks.h>
#include <testsuite_fs.h>
using std::experimental::filesystem::path;
void
test01()
{
const std::string s0 = "/a/a/b/b";
const path p0 = s0;
for (const std::string& s : __gnu_test::test_paths)
{
path p(s);
VERIFY( p.compare(s) == 0 );
VERIFY( p.compare(s.c_str()) == 0 );
VERIFY( p.compare(p0) == p.compare(s0) );
VERIFY( p.compare(p0) == p.compare(s0.c_str()) );
}
}
int
main()
{
test01();
}
| [
"rink@rink.nu"
] | rink@rink.nu |
1d1ebd38358b891198e20b3e68f562603c5c7539 | 0466f22155da48d446f27a7de2c3023c85284f14 | /src/hdchain.h | fc72c5e98531703bca139f99b365d57cfa447760 | [
"MIT"
] | permissive | jesusleon1995/dashdiff | fe660564ccf31a32cfd2851abb527a1fb7eb314f | 83347b555ab7f6212bc40bb47f9afee7823be090 | refs/heads/master | 2020-03-21T16:58:34.574472 | 2018-06-27T00:45:18 | 2018-06-27T00:45:18 | 138,805,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,467 | h | // Copyright (c) 2014-2017 The Dashdiff Core developers
// Distributed under the MIT software license, see the accompanying
#ifndef DASH_HDCHAIN_H
#define DASH_HDCHAIN_H
#include "key.h"
#include "sync.h"
/* hd account data model */
class CHDAccount
{
public:
uint32_t nExternalChainCounter;
uint32_t nInternalChainCounter;
CHDAccount() : nExternalChainCounter(0), nInternalChainCounter(0) {}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(nExternalChainCounter);
READWRITE(nInternalChainCounter);
}
};
/* simple HD chain data model */
class CHDChain
{
private:
static const int CURRENT_VERSION = 1;
int nVersion;
uint256 id;
bool fCrypted;
SecureVector vchSeed;
SecureVector vchMnemonic;
SecureVector vchMnemonicPassphrase;
std::map<uint32_t, CHDAccount> mapAccounts;
// critical section to protect mapAccounts
mutable CCriticalSection cs_accounts;
public:
CHDChain() : nVersion(CHDChain::CURRENT_VERSION) { SetNull(); }
CHDChain(const CHDChain& other) :
nVersion(other.nVersion),
id(other.id),
fCrypted(other.fCrypted),
vchSeed(other.vchSeed),
vchMnemonic(other.vchMnemonic),
vchMnemonicPassphrase(other.vchMnemonicPassphrase),
mapAccounts(other.mapAccounts)
{}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
LOCK(cs_accounts);
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(id);
READWRITE(fCrypted);
READWRITE(vchSeed);
READWRITE(vchMnemonic);
READWRITE(vchMnemonicPassphrase);
READWRITE(mapAccounts);
}
void swap(CHDChain& first, CHDChain& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.nVersion, second.nVersion);
swap(first.id, second.id);
swap(first.fCrypted, second.fCrypted);
swap(first.vchSeed, second.vchSeed);
swap(first.vchMnemonic, second.vchMnemonic);
swap(first.vchMnemonicPassphrase, second.vchMnemonicPassphrase);
swap(first.mapAccounts, second.mapAccounts);
}
CHDChain& operator=(CHDChain from)
{
swap(*this, from);
return *this;
}
bool SetNull();
bool IsNull() const;
void SetCrypted(bool fCryptedIn);
bool IsCrypted() const;
void Debug(std::string strName) const;
bool SetMnemonic(const SecureVector& vchMnemonic, const SecureVector& vchMnemonicPassphrase, bool fUpdateID);
bool SetMnemonic(const SecureString& ssMnemonic, const SecureString& ssMnemonicPassphrase, bool fUpdateID);
bool GetMnemonic(SecureVector& vchMnemonicRet, SecureVector& vchMnemonicPassphraseRet) const;
bool GetMnemonic(SecureString& ssMnemonicRet, SecureString& ssMnemonicPassphraseRet) const;
bool SetSeed(const SecureVector& vchSeedIn, bool fUpdateID);
SecureVector GetSeed() const;
uint256 GetID() const { return id; }
uint256 GetSeedHash();
void DeriveChildExtKey(uint32_t nAccountIndex, bool fInternal, uint32_t nChildIndex, CExtKey& extKeyRet);
void AddAccount();
bool GetAccount(uint32_t nAccountIndex, CHDAccount& hdAccountRet);
bool SetAccount(uint32_t nAccountIndex, const CHDAccount& hdAccount);
size_t CountAccounts();
};
/* hd pubkey data model */
class CHDPubKey
{
private:
static const int CURRENT_VERSION = 1;
int nVersion;
public:
CExtPubKey extPubKey;
uint256 hdchainID;
uint32_t nAccountIndex;
uint32_t nChangeIndex;
CHDPubKey() : nVersion(CHDPubKey::CURRENT_VERSION), nAccountIndex(0), nChangeIndex(0) {}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(extPubKey);
READWRITE(hdchainID);
READWRITE(nAccountIndex);
READWRITE(nChangeIndex);
}
std::string GetKeyPath() const;
};
#endif // DASH_HDCHAIN_H
| [
"jjuansan9@alumnes.ub.edu"
] | jjuansan9@alumnes.ub.edu |
288901475252d80a65f8fab91d3a2961ca72d925 | a1b93fd969fa04db05f01a3783f7e9ff77c0c9df | /Random/random.hh | 5755cd869ae5d6d4304bf84a5296cf791555e7e1 | [] | no_license | mvdsanden/mvds | a31176d423203abf4e5b16a5effdebd7e2c054d8 | c95c1b4706dc718cb7dcee6dee01c922691d7968 | refs/heads/master | 2021-01-19T14:04:54.389200 | 2009-10-27T20:14:14 | 2009-10-27T20:14:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,796 | hh | #ifndef __INC_MVDS_RANDOM_HH__
#define __INC_MVDS_RANDOM_HH__
#include <algorithm>
#include <gsl/gsl_rng.h>
#include <cmath>
namespace mvds {
class Random {
static Random *s_instance;
Random();
public:
~Random();
static void initialize();
static void finish();
static Random &instance();
/**
* Seed the random number generator.
*/
void seed(unsigned seed);
/**
* @returns a uniform distributed random value in the range [0,1).
*/
double uniform();
/**
* @returns a uniform distributed random value in the range [r0,r1).
*/
double uniform(double r0, double r1);
/**
* @param sigma the standard deviation.
* @param mu the means.
*
* @returns a normal (gaussian) distributed random value (N(mu,sigma)).
*/
double normal(double sigma);
double normal(double mu, double sigma);
/**
* @returns a uniform distributed random value in the range [r0,r1).
*/
size_t inRange(size_t r0, size_t r1);
/**
* @returns true with a probability of pHeads.
*/
bool coinToss(double pHeads = 0.5);
/**
* This operator can be used with random_shuffle.
*/
ptrdiff_t operator()(ptrdiff_t scale);
private:
gsl_rng *d_random;
};
inline double Random::uniform(double r0, double r1)
{
return r0 + uniform() / (r1 - r0);
}
inline double Random::normal(double mu, double sigma)
{
return mu + normal(sigma);
}
inline size_t Random::inRange(size_t r0, size_t r1)
{
return std::min(r0,r1) + (1.0/labs(r0 - r1)) * uniform();
}
inline bool Random::coinToss(double pHeads)
{
return uniform() < pHeads;
}
inline ptrdiff_t Random::operator()(ptrdiff_t scale)
{
return std::floor(inRange(0,scale));
}
};
#endif // __INC_MVDS_RANDOM_HH__
| [
"mart.vd.sanden@gmail.com"
] | mart.vd.sanden@gmail.com |
4cf65fe9b3e6a052d442b84a81f8d9247b52083c | db2b7b36ae7eced337d50d31d3917900c4578e59 | /ProjectBarnabus/src/GameEngine/Transform.cpp | 28781b3717a77e0532cf93069e76a2fc8ca05dae | [] | no_license | conzo096/ProjectBarnabus | 6b355efbef61d10599947fc10ff3649513cb6a78 | 3cf276fd667cba4b429202d7faebb2062da1f601 | refs/heads/master | 2021-08-03T00:09:05.154905 | 2020-12-27T17:44:45 | 2020-12-27T17:44:45 | 188,912,820 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | cpp | #include "Transform.h"
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtx/transform.hpp>
Transform::Transform() : scale(glm::vec3(1.0)), rotation(glm::quat()), position(glm::vec3(0)), previousPosition(glm::vec3(0)), transform(glm::mat4(1)), changed(true)
{
}
Transform::Transform(glm::vec3 pos, glm::vec3 rot, glm::vec3 scale) : Transform()
{
SetPosition(pos);
SetRotation(rot);
SetScale(scale);
changed = true;
}
Transform::~Transform()
{
}
void Transform::UpdateTransforms()
{
if (changed)
{
transform = glm::translate(position) * mat4_cast(rotation) * glm::scale(scale);
changed = false;
}
}
const bool Transform::GetChanged() const
{
return changed;
}
const glm::vec3 Transform::GetPosition() const
{
return position;
}
void Transform::SetPosition(const glm::vec3 v3)
{
position = v3;
changed = true;
}
void Transform::Move(const glm::vec3 v3)
{
previousPosition = position;
SetPosition(position + v3);
changed = true;
}
const glm::quat Transform::GetRotation() const
{
return rotation;
}
void Transform::SetRotation(const glm::quat q)
{
rotation = q;
changed = true;
}
void Transform::SetRotation(const glm::vec3 v3)
{
rotation = glm::quat(v3);
changed = true;
}
void Transform::Rotate(const glm::quat q)
{
SetRotation(rotation * q); changed = true;
}
void Transform::Rotate(const glm::vec3 v3)
{
SetRotation(rotation * glm::quat(glm::radians(v3)));
changed = true;
}
const glm::vec3 Transform::GetScale() const
{
return scale;
}
void Transform::SetScale(const glm::vec3 v3)
{
scale = v3; changed = true;
}
void Transform::Scale(const glm::vec3 v3)
{
scale *= v3;
changed = true;
}
const glm::mat4 Transform::GetTransform() const
{
return transform;
}
void Transform::SetTransform(const glm::mat4 m4)
{
transform = m4;
changed = true;
}
const glm::vec3 Transform::GetPreviousPosition() const
{
return previousPosition;
} | [
"connerweatherston@hotmail.co.uk"
] | connerweatherston@hotmail.co.uk |
0c53c175bd922525d6a151a3c88982e4d8e01332 | cfd33821398cede8c2aadd847d59b89d72d7e0a6 | /msnp24/src/msn.cpp | e4252711ccfdaf41ab8dd97ffa7792ebe636647c | [] | no_license | miranda-ng/deprecated | 1c922e502d7ec35371a454131b9e5fa019e241fd | 137526f743d2e8237845b7faea992989a7e8fbd7 | refs/heads/master | 2023-01-28T20:57:12.499530 | 2023-01-13T23:32:54 | 2023-01-13T23:32:54 | 71,989,840 | 3 | 3 | null | 2017-08-22T18:52:34 | 2016-10-26T09:53:01 | C++ | UTF-8 | C++ | false | false | 4,275 | cpp | /*
Plugin of Miranda IM for communicating with users of the MSN Messenger protocol.
Copyright (c) 2012-2014 Miranda NG Team
Copyright (c) 2006-2012 Boris Krasnovskiy.
Copyright (c) 2003-2005 George Hazan.
Copyright (c) 2002-2003 Richard Hughes (original version).
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "msn_global.h"
#include "msn_proto.h"
#include "version.h"
HINSTANCE hInst;
int hLangpack;
TIME_API tmi;
/////////////////////////////////////////////////////////////////////////////////////////
// Initialization routines
void MsnLinks_Init(void);
void MsnLinks_Destroy(void);
/////////////////////////////////////////////////////////////////////////////////////////
// Global variables
int avsPresent = -1;
static const PLUGININFOEX pluginInfo =
{
sizeof(PLUGININFOEX),
__PLUGIN_NAME,
PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM),
__DESCRIPTION,
__AUTHOR,
__AUTHOREMAIL,
__COPYRIGHT,
__AUTHORWEB,
UNICODE_AWARE,
// {97724AF9-F3FB-47d3-A3BF-EAA935C74E6D}
{0x97724af9, 0xf3fb, 0x47d3, {0xa3, 0xbf, 0xea, 0xa9, 0x35, 0xc7, 0x4e, 0x6d}}
};
int MSN_GCEventHook(WPARAM wParam, LPARAM lParam);
int MSN_GCMenuHook(WPARAM wParam, LPARAM lParam);
/////////////////////////////////////////////////////////////////////////////
// Protocol instances
static int sttCompareProtocols(const CMsnProto *p1, const CMsnProto *p2)
{
return _tcscmp(p1->m_tszUserName, p2->m_tszUserName);
}
OBJLIST<CMsnProto> g_Instances(1, sttCompareProtocols);
/////////////////////////////////////////////////////////////////////////////////////////
// Main DLL function
extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID)
{
if (fdwReason == DLL_PROCESS_ATTACH) {
hInst = hinstDLL;
DisableThreadLibraryCalls(hinstDLL);
}
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////////////////
// OnModulesLoaded - finalizes plugin's configuration on load
static int OnModulesLoaded(WPARAM, LPARAM)
{
avsPresent = ServiceExists(MS_AV_SETMYAVATART) != 0;
MsnLinks_Init();
return 0;
}
static CMsnProto* msnProtoInit(const char* pszProtoName, const TCHAR* tszUserName)
{
CMsnProto *ppro = new CMsnProto(pszProtoName, tszUserName);
g_Instances.insert(ppro);
return ppro;
}
static int msnProtoUninit(CMsnProto* ppro)
{
g_Instances.remove(ppro);
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// Performs a primary set of actions upon plugin loading
extern "C" int __declspec(dllexport) Load(void)
{
mir_getTMI(&tmi);
mir_getLP(&pluginInfo);
HookEvent(ME_SYSTEM_MODULESLOADED, OnModulesLoaded);
PROTOCOLDESCRIPTOR pd = { sizeof(pd) };
pd.szName = "MSN";
pd.fnInit = (pfnInitProto)msnProtoInit;
pd.fnUninit = (pfnUninitProto)msnProtoUninit;
pd.type = PROTOTYPE_PROTOCOL;
CallService(MS_PROTO_REGISTERMODULE, 0, (LPARAM)&pd);
MsnInitIcons();
MSN_InitContactMenu();
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// Unload a plugin
extern "C" int __declspec(dllexport) Unload(void)
{
MSN_RemoveContactMenus();
MsnLinks_Destroy();
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
// MirandaPluginInfoEx - returns an information about a plugin
extern "C" __declspec(dllexport) const PLUGININFOEX* MirandaPluginInfoEx(DWORD)
{
return &pluginInfo;
}
/////////////////////////////////////////////////////////////////////////////////////////
// MirandaInterfaces - returns the protocol interface to the core
extern "C" __declspec(dllexport) const MUUID MirandaInterfaces[] = { MIID_PROTOCOL, MIID_LAST };
| [
"watcherhd@gmail.com"
] | watcherhd@gmail.com |
236ffad97c075df64f0db31f90cedd6a397268d8 | 2252d70a654948b5aadb06a1158d97e646b8097f | /Competitive Programming/Codeforces/edu87(2)/4.cpp | 4da97da8438191d55f9278ecfd2423feb51def0a | [] | no_license | spashal/Competitive-Programming | 1b02aea6496f82920924b714eb857189c1542d63 | f68e7bdf05dad9eab41bee0c2d9558f92068c244 | refs/heads/master | 2023-07-26T16:26:36.633063 | 2021-09-09T04:15:21 | 2021-09-09T04:15:21 | 267,501,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,056 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long double ll;
ll mpi = 3.14159265;
ll t;
int n;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> t;
while( t-- > 0 ){
cin >> n;
if( n == 2 )
cout << "1.0000000" << endl;
else{
ll ans = 0;
if( (n-1)%2==0 ){
ll angler = (ll)(mpi*(n-1))/(n);
ll angle = angler/2;
for( int i = 0 ; i < (n-1)/2 ; i++ ){
ans += (ll)cos(angle);
cout << ans << " ";
angle = angler - (mpi/2) - ((mpi)/2 - angle);
}
}
else{
ll angler = (ll)(mpi*(n-1))/(n);
ll angle = angler - (mpi/2);
for( int i = 0 ; i < (n-1)/2 ; i++ ){
ans += (ll)cos(angle);
// cout << ans << " ";
angle = angler - (mpi/2) - ((mpi)/2 - angle);
}
ans += 0.500000000;
}
ans *= 2;
ans += 1;
cout << fixed << setprecision(6) << ans << endl;
// cout << fixed << setprecision(6) << 2 * ( ( ll)cos((ll)((n-1)*mpi)/( 2*n )) / ( 1 - cos( (ll)(mpi/n)))) << endl;
}
}
return(0);
} | [
"palash.sharma@students.iiit.ac.in"
] | palash.sharma@students.iiit.ac.in |
827314b59cde13e29647b53545413e0146d1a823 | 9547c22035266bf5fb414090bbe0e5bfb454cdbb | /src/main.cpp | 409f309dfb303483f984e917c1e3dd26d5dffb1f | [] | no_license | haohaoh4/my-compiler | 42f9c4e310fce7d82a0fc1b74709e152800f5489 | 67605df8dd2889716b96fb44663b88d3ac197e94 | refs/heads/master | 2020-12-03T00:17:49.567470 | 2017-07-02T09:32:02 | 2017-07-02T09:32:02 | 96,010,765 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,316 | cpp | #include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
enum
{
EOS, //end of setence
TYPE,
EXP, //±í´ïʽ
NAME,
OP,
ERR
};
string types[]=
{
"int",
"char"
};
bool is_a_var(string);
int get();
void pass();
bool com_exp();
int point=0;
string source;
int get()
{
char *p = const_cast<char*>(source.c_str());
p+=point;
string s;
int times=0;
if(point>=source.length())
return EOF;
while(p[point+times]!=' ' && point+times<s.length())
{
s+=p[point+times];
times++;
}
if(s=="")
return EOF;
if(s==";")
return EOS;
for(int i=0;i<sizeof(types)/sizeof(string);i++)
{
if(s==types[i])
return TYPE;
}
if(is_a_var(s))
return NAME;
for(int i=0;i<10;i++)
{
if(s[0]==i+'0')
return EXP;
}
return ERR;
}
string get_string()
{
char *p = const_cast<char*>(source.c_str());
string s;
int times=0;
while(p[point+times]!=' ' && point+times<source.length())
{
s+=p[point+times];
times++;
}
return s;
}
struct var
{
string name;
string type;
};
vector<var> vars;
bool is_a_var(string str)
{
for(vector<var>::iterator i=vars.begin();i!=vars.end();i++)
{
if((*i).name==str)
return true;
}
return false;
}
bool def_var()
{
var n;
n.type=get_string();
pass();
n.name=get_string();
pass();
vars.push_back(n);
cout<<"Define a var:"<<n.type<<" "<<n.name<<endl;
return true;
}
void pass()
{
if(point>=source.length())
return;
while(source[point]!=' ' && source[point+1]!=';')
point++;
int times=0;
while(source[point])
{
point++,times++;
}
return;
}
int main()
{
char file[255];
cout<<"enter the file name:[test.c]";
cin.getline(file,254);
cout<<endl;
ifstream fin(file);
if(!fin)
{
cout<<"failed";
return -1;
}
istreambuf_iterator<char> beg(fin), end;
string sour(beg, end);
source=sour;
while(get()!=EOF)
{
while(1)
{
int status=get();
switch (status)
{
case EOS:
pass();
cout<<"EOS"<<endl;
break;
case TYPE:
if(get()==OP)
com_exp();
else
if(!def_var())goto error;
break;
case NAME:
if(get()==OP)
if(!com_exp())goto error;
if(get()==EOS)
pass();
break;
case ERR:
error:
cout<<"ERROR "<<point<<endl;
pass();
}
}
}
return 0;
}
bool com_exp()
{
return true;
}
| [
"handahao@163.com"
] | handahao@163.com |
25549284cebfa914dc4dd0204d8e719d9356ebfd | f90b03c3cb72d6d066e984e8a91004cd9565e2c6 | /Arduino/libraries/IRremote/irRecv.cpp | 937372297ce843704a44b52990ff708d8c12fcd3 | [] | no_license | acid8x/RCRACING | 3af6612e2e00bc404e37127a0851de65d8a16bd9 | 0dbd9e6c4d7944d6c91c2828ff4f6a56508cd0c6 | refs/heads/master | 2021-01-11T20:26:30.027382 | 2018-04-24T04:46:09 | 2018-04-24T04:46:09 | 79,114,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,788 | cpp | #include "IRremote.h"
#include "IRremoteInt.h"
//+=============================================================================
// Decodes the received IR message
// Returns 0 if no data ready, 1 if data ready.
// Results of decoding are stored in results
//
int IRrecv::decode (decode_results *results)
{
results->rawbuf = irparams.rawbuf;
results->rawlen = irparams.rawlen;
results->overflow = irparams.overflow;
if (irparams.rcvstate != STATE_STOP) return false ;
#if DECODE_NEC
DBG_PRINTLN("Attempting NEC decode");
if (decodeNEC(results)) return true ;
#endif
#if DECODE_SONY
DBG_PRINTLN("Attempting Sony decode");
if (decodeSony(results)) return true ;
#endif
#if DECODE_SANYO
DBG_PRINTLN("Attempting Sanyo decode");
if (decodeSanyo(results)) return true ;
#endif
#if DECODE_MITSUBISHI
DBG_PRINTLN("Attempting Mitsubishi decode");
if (decodeMitsubishi(results)) return true ;
#endif
#if DECODE_RC5
DBG_PRINTLN("Attempting RC5 decode");
if (decodeRC5(results)) return true ;
#endif
#if DECODE_RC6
DBG_PRINTLN("Attempting RC6 decode");
if (decodeRC6(results)) return true ;
#endif
#if DECODE_PANASONIC
DBG_PRINTLN("Attempting Panasonic decode");
if (decodePanasonic(results)) return true ;
#endif
#if DECODE_LG
DBG_PRINTLN("Attempting LG decode");
if (decodeLG(results)) return true ;
#endif
#if DECODE_JVC
DBG_PRINTLN("Attempting JVC decode");
if (decodeJVC(results)) return true ;
#endif
#if DECODE_SAMSUNG
DBG_PRINTLN("Attempting SAMSUNG decode");
if (decodeSAMSUNG(results)) return true ;
#endif
#if DECODE_WHYNTER
DBG_PRINTLN("Attempting Whynter decode");
if (decodeWhynter(results)) return true ;
#endif
#if DECODE_AIWA_RC_T501
DBG_PRINTLN("Attempting Aiwa RC-T501 decode");
if (decodeAiwaRCT501(results)) return true ;
#endif
#if DECODE_DENON
DBG_PRINTLN("Attempting Denon decode");
if (decodeDenon(results)) return true ;
#endif
// decodeHash returns a hash on any input.
// Thus, it needs to be last in the list.
// If you add any decodes, add them before this.
if (decodeHash(results)) return true ;
// Throw away and start over
resume();
return false;
}
//+=============================================================================
IRrecv::IRrecv (int recvpin) : irparams()
{
irparams.recvpin = recvpin;
irparams.blinkflag = 0;
irparamslist[irparams_used] = &irparams;
irparams_used++;
}
IRrecv::IRrecv (int recvpin, int blinkpin)
{
irparams.recvpin = recvpin;
irparams.blinkpin = blinkpin;
pinMode(blinkpin, OUTPUT);
irparams.blinkflag = 0;
}
//+=============================================================================
// initialization
//
void IRrecv::enableIRIn ( )
{
cli();
// Setup pulse clock timer interrupt
// Prescale /8 (16M/8 = 0.5 microseconds per tick)
// Therefore, the timer interval can range from 0.5 to 128 microseconds
// Depending on the reset value (255 to 0)
TIMER_CONFIG_NORMAL();
// Timer2 Overflow Interrupt Enable
TIMER_ENABLE_INTR;
TIMER_RESET;
sei(); // enable interrupts
// Initialize state machine variables
irparams.rcvstate = STATE_IDLE;
irparams.rawlen = 0;
// Set pin modes
pinMode(irparams.recvpin, INPUT);
}
//+=============================================================================
// Enable/disable blinking of pin 13 on IR processing
//
void IRrecv::blink13 (int blinkflag)
{
irparams.blinkflag = blinkflag;
if (blinkflag) pinMode(BLINKLED, OUTPUT) ;
}
//+=============================================================================
// Return if receiving new IR signals
//
bool IRrecv::isIdle ( )
{
return (irparams.rcvstate == STATE_IDLE || irparams.rcvstate == STATE_STOP) ? true : false;
}
//+=============================================================================
// Restart the ISR state machine
//
void IRrecv::resume ( )
{
irparams.rcvstate = STATE_IDLE;
irparams.rawlen = 0;
}
//+=============================================================================
// hashdecode - decode an arbitrary IR code.
// Instead of decoding using a standard encoding scheme
// (e.g. Sony, NEC, RC5), the code is hashed to a 32-bit value.
//
// The algorithm: look at the sequence of MARK signals, and see if each one
// is shorter (0), the same length (1), or longer (2) than the previous.
// Do the same with the SPACE signals. Hash the resulting sequence of 0's,
// 1's, and 2's to a 32-bit value. This will give a unique value for each
// different code (probably), for most code systems.
//
// http://arcfn.com/2010/01/using-arbitrary-remotes-with-arduino.html
//
// Compare two tick values, returning 0 if newval is shorter,
// 1 if newval is equal, and 2 if newval is longer
// Use a tolerance of 20%
//
int IRrecv::compare (unsigned int oldval, unsigned int newval)
{
if (newval < oldval * .7) return 0 ;
else if (oldval < newval * .7) return 2 ;
else return 1 ;
}
//+=============================================================================
// Use FNV hash algorithm: http://isthe.com/chongo/tech/comp/fnv/#FNV-param
// Converts the raw code values into a 32-bit hash code.
// Hopefully this code is unique for each button.
// This isn't a "real" decoding, just an arbitrary value.
//
#define FNV_PRIME_32 16777619
#define FNV_BASIS_32 2166136261
long IRrecv::decodeHash (decode_results *results)
{
long hash = FNV_BASIS_32;
// Require at least 6 samples to prevent triggering on noise
if (results->rawlen < 6) return false ;
for (int i = 1; (i + 2) < results->rawlen; i++) {
int value = compare(results->rawbuf[i], results->rawbuf[i+2]);
// Add value into the hash
hash = (hash * FNV_PRIME_32) ^ value;
}
results->value = hash;
results->bits = 32;
results->decode_type = UNKNOWN;
return true;
}
| [
"acid8x@gmail.com"
] | acid8x@gmail.com |
9f25ab7aab811e48b4f23afcde2854306404691b | 50f8c138da0165fa140c3241291aa2b0a8a14f99 | /sequence with digits.cpp | 72ec3f360dcda2a3a95adc149073d422a2424842 | [] | no_license | Priybhanu99/My-Codes | c5da0821348939d75498e2751bc6c63d5e572294 | 4dc2e93fb941c4166b3b687a76358a1f309cc976 | refs/heads/master | 2021-05-19T12:22:09.830851 | 2021-01-17T15:22:23 | 2021-01-17T15:22:23 | 251,694,773 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | cpp | #include <bits/stdc++.h>
using namespace std;
#define int long long int
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t;
cin>>t; while(t--){
int n,k;
cin>>n>>k;
int mnm = INT_MAX;
int mxm = INT_MIN;
int count = 0;
while(mnm!=0 && count<k-1){
int temp = n;
mnm = INT_MAX;
mxm = INT_MIN;
while(temp){
int rem = temp%10;
if(rem<mnm){
mnm = rem;
}
if(rem>mxm){
mxm = rem;
}
temp /= 10;
}
n += mnm*mxm;
count++;
//cout<<n<<" ";
}
cout<<n<<"\n";
}
}
// 42
// 487
// 519
// 528
// 544
// 564
// 588
// 628
| [
"bhanuyadav1999.by@gmail.com"
] | bhanuyadav1999.by@gmail.com |
f1d159ad1b4676abeaaa9377d3e32ba7f3f0e890 | 6f6f5f3e2ca4f87415ce308edaa8374833f1f148 | /app/src/main/cpp/game_client.cpp | 1e7d88bef9ab14e85079dd4e8617964acc6a7f5a | [] | no_license | iplaycloud/xctx_project_p51_ModeSwitch | 1fe8462a42c09a3c179ef274d7282300a6ed9e0d | 8e5ef09176c12517a6709db59825a40c28a5f924 | refs/heads/master | 2020-06-18T23:40:26.205667 | 2016-12-05T02:51:07 | 2016-12-05T02:51:07 | 74,934,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,464 | cpp |
#include <fcntl.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <cutils/properties.h>
#include <utils/Log.h>
#include "IGameEventService.h"
using namespace android;
/* ./test_client <startService|stopService>
*/
int main(int argc, char **argv)
{
int cnt;
if (argc < 2){
ALOGI("Usage:\n");
ALOGI("%s <startService|stopService>\n", argv[0]);
return -1;
}
/* getService */
/* 打开驱动, mmap */
sp<ProcessState> proc(ProcessState::self());
/* 获得BpServiceManager */
sp<IServiceManager> sm = defaultServiceManager();
if (strcmp(argv[1], "startService") == 0)
{
sp<IBinder> binder = sm->getService(String16("GameEvent"));
if (binder == 0)
{
ALOGI("can't get GameEvent service\n");
return -1;
}
/* service肯定是BpHelloServie指针 */
sp<IGameEventService> service = interface_cast<IGameEventService>(binder);
/* 调用Service的函数 */
service->startService();
ALOGI("client call startService");
}
else
{
sp<IBinder> binder = sm->getService(String16("GameEvent"));
if (binder == 0)
{
ALOGI("can't get GameEvent service\n");
return -1;
}
/* service肯定是BpGoodbyeServie指针 */
sp<IGameEventService> service = interface_cast<IGameEventService>(binder);
/* 调用Service的函数 */
service->stopService();
ALOGI("client call stopService");
}
return 0;
}
| [
"iplaycloud@gmail.com"
] | iplaycloud@gmail.com |
8ea6b9ebedb383a93a4f77342f6d13eaabeab8d4 | 33a5e1bf4e09b84c2d895cd739ed732066d0486a | /hlesgx_test/App/App.cpp | 59e3ab70bdc51f3827d4f360e3dfb49dfaa1e0d9 | [] | no_license | StanPlatinum/tsx-in-sgx | d3bcde61bb881e16fff74c7809c4496bea4fef1f | 285e6b0b9d8c1a52faea8f19f80e5f4ccc1a4e66 | refs/heads/master | 2020-05-24T13:33:03.364075 | 2020-03-22T19:25:21 | 2020-03-22T19:25:21 | 187,291,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,435 | cpp | /*
* Copyright (C) 2011-2017 Intel Corporation. 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 Intel 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 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 <stdio.h>
#include <string.h>
#include <assert.h>
# include <unistd.h>
# include <pwd.h>
# define MAX_PATH FILENAME_MAX
#include "sgx_urts.h"
#include "App.h"
#include "Enclave_u.h"
/* Global EID shared by multiple threads */
sgx_enclave_id_t global_eid = 0;
typedef struct _sgx_errlist_t {
sgx_status_t err;
const char *msg;
const char *sug; /* Suggestion */
} sgx_errlist_t;
/* Error code returned by sgx_create_enclave */
static sgx_errlist_t sgx_errlist[] = {
{
SGX_ERROR_UNEXPECTED,
"Unexpected error occurred.",
NULL
},
{
SGX_ERROR_INVALID_PARAMETER,
"Invalid parameter.",
NULL
},
{
SGX_ERROR_OUT_OF_MEMORY,
"Out of memory.",
NULL
},
{
SGX_ERROR_ENCLAVE_LOST,
"Power transition occurred.",
"Please refer to the sample \"PowerTransition\" for details."
},
{
SGX_ERROR_INVALID_ENCLAVE,
"Invalid enclave image.",
NULL
},
{
SGX_ERROR_INVALID_ENCLAVE_ID,
"Invalid enclave identification.",
NULL
},
{
SGX_ERROR_INVALID_SIGNATURE,
"Invalid enclave signature.",
NULL
},
{
SGX_ERROR_OUT_OF_EPC,
"Out of EPC memory.",
NULL
},
{
SGX_ERROR_NO_DEVICE,
"Invalid SGX device.",
"Please make sure SGX module is enabled in the BIOS, and install SGX driver afterwards."
},
{
SGX_ERROR_MEMORY_MAP_CONFLICT,
"Memory map conflicted.",
NULL
},
{
SGX_ERROR_INVALID_METADATA,
"Invalid enclave metadata.",
NULL
},
{
SGX_ERROR_DEVICE_BUSY,
"SGX device was busy.",
NULL
},
{
SGX_ERROR_INVALID_VERSION,
"Enclave version was invalid.",
NULL
},
{
SGX_ERROR_INVALID_ATTRIBUTE,
"Enclave was not authorized.",
NULL
},
{
SGX_ERROR_ENCLAVE_FILE_ACCESS,
"Can't open enclave file.",
NULL
},
};
/* Check error conditions for loading enclave */
void print_error_message(sgx_status_t ret)
{
size_t idx = 0;
size_t ttl = sizeof sgx_errlist/sizeof sgx_errlist[0];
for (idx = 0; idx < ttl; idx++) {
if(ret == sgx_errlist[idx].err) {
if(NULL != sgx_errlist[idx].sug)
printf("Info: %s\n", sgx_errlist[idx].sug);
printf("Error: %s\n", sgx_errlist[idx].msg);
break;
}
}
if (idx == ttl)
printf("Error: Unexpected error occurred.\n");
}
/* Initialize the enclave:
* Step 1: try to retrieve the launch token saved by last transaction
* Step 2: call sgx_create_enclave to initialize an enclave instance
* Step 3: save the launch token if it is updated
*/
int initialize_enclave(void)
{
char token_path[MAX_PATH] = {'\0'};
sgx_launch_token_t token = {0};
sgx_status_t ret = SGX_ERROR_UNEXPECTED;
int updated = 0;
/* Step 1: try to retrieve the launch token saved by last transaction
* if there is no token, then create a new one.
*/
/* try to get the token saved in $HOME */
const char *home_dir = getpwuid(getuid())->pw_dir;
if (home_dir != NULL &&
(strlen(home_dir)+strlen("/")+sizeof(TOKEN_FILENAME)+1) <= MAX_PATH) {
/* compose the token path */
strncpy(token_path, home_dir, strlen(home_dir));
strncat(token_path, "/", strlen("/"));
strncat(token_path, TOKEN_FILENAME, sizeof(TOKEN_FILENAME)+1);
} else {
/* if token path is too long or $HOME is NULL */
strncpy(token_path, TOKEN_FILENAME, sizeof(TOKEN_FILENAME));
}
FILE *fp = fopen(token_path, "rb");
if (fp == NULL && (fp = fopen(token_path, "wb")) == NULL) {
printf("Warning: Failed to create/open the launch token file \"%s\".\n", token_path);
}
if (fp != NULL) {
/* read the token from saved file */
size_t read_num = fread(token, 1, sizeof(sgx_launch_token_t), fp);
if (read_num != 0 && read_num != sizeof(sgx_launch_token_t)) {
/* if token is invalid, clear the buffer */
memset(&token, 0x0, sizeof(sgx_launch_token_t));
printf("Warning: Invalid launch token read from \"%s\".\n", token_path);
}
}
/* Step 2: call sgx_create_enclave to initialize an enclave instance */
/* Debug Support: set 2nd parameter to 1 */
ret = sgx_create_enclave(ENCLAVE_FILENAME, SGX_DEBUG_FLAG, &token, &updated, &global_eid, NULL);
if (ret != SGX_SUCCESS) {
print_error_message(ret);
if (fp != NULL) fclose(fp);
return -1;
}
/* Step 3: save the launch token if it is updated */
if (updated == FALSE || fp == NULL) {
/* if the token is not updated, or file handler is invalid, do not perform saving */
if (fp != NULL) fclose(fp);
return 0;
}
/* reopen the file with write capablity */
fp = freopen(token_path, "wb", fp);
if (fp == NULL) return 0;
size_t write_num = fwrite(token, 1, sizeof(sgx_launch_token_t), fp);
if (write_num != sizeof(sgx_launch_token_t))
printf("Warning: Failed to save launch token to \"%s\".\n", token_path);
fclose(fp);
return 0;
}
/* OCall functions */
void Ocall_PrintString(const char *str){
printf("%s", str);
}
/* Application entry */
int SGX_CDECL main(int argc, char *argv[])
{
(void)(argc);
(void)(argv);
/* Initialize the enclave */
if(initialize_enclave() < 0){
printf("Please enter a character before exit ...\n");
getchar();
return -1;
}
/*
* to-do
*/
hle_test(global_eid);
/* Destroy the enclave */
sgx_destroy_enclave(global_eid);
return 0;
}
| [
"weijliu@bio-sgx.soic.indiana.edu"
] | weijliu@bio-sgx.soic.indiana.edu |
15cbaf7134a07afc078d2cde5c2920895e6b9f10 | 7274d5a3f1c78c2412205db504119487522e3dda | /CocoaEngine/include/cocoa/renderer/CameraStruct.h | aae127b84759d27a7342be9c6574bd53cca17e74 | [
"MIT"
] | permissive | ambrosiogabe/Cocoa | a7101ce7de24b5e0ac50239200bd60304ed834cd | c66539149c9963e354daba9dfd4ec444ca135b48 | refs/heads/master | 2023-09-04T06:50:56.325751 | 2023-08-19T21:09:44 | 2023-08-19T21:09:44 | 268,167,311 | 50 | 8 | MIT | 2023-08-19T21:09:45 | 2020-05-30T22:06:33 | C++ | UTF-8 | C++ | false | false | 573 | h | #ifndef COCOA_ENGINE_CAMERA_STRUCT_H
#define COCOA_ENGINE_CAMERA_STRUCT_H
#include "externalLibs.h"
#include "cocoa/renderer/Framebuffer.h"
namespace Cocoa
{
struct Camera
{
// Projection/View matrices for ortho and perspective
glm::mat4 viewMatrix;
glm::mat4 inverseView;
glm::mat4 projectionMatrix;
glm::mat4 inverseProjection;
glm::vec3 clearColor;
glm::vec2 projectionSize;
float projectionNearPlane;
float projectionFarPlane;
Framebuffer framebuffer;
float fov = 45.0f;
float aspect = 1920.0f / 1080.0f;
float zoom = 1.0f;
};
}
#endif
| [
"ambrosiogabe@gmail.com"
] | ambrosiogabe@gmail.com |
53cc9380c5a2ab04cd70a1ce7b13d37fa565cfa3 | 1f950ec13cc94459bea3f4f2903e688d123d4812 | /Brother_Task_Shader/main.cpp | baaf106b71856aef8711eb1ed1bf610929603070 | [] | no_license | katsuto-kawauchi/brother_task | b53a101257e331a0a61166fc377ca68fb0c5c74f | 8417417c8e75f0599983e1651943fb323824e822 | refs/heads/master | 2020-04-03T15:08:58.802944 | 2018-10-30T08:29:11 | 2018-10-30T08:29:11 | 155,352,373 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 21,893 | cpp | #pragma comment(lib,"d3d11.lib")
#pragma comment(lib,"d3dx11.lib")
#pragma comment(lib,"d3dx10.lib")
#pragma comment(lib,"d3dCompiler.lib")
#pragma comment(lib, "dinput8.lib")
#pragma comment(lib, "dxguid.lib")
#include <stdio.h>
#include <vector>
#include <d3dx11.h>
#include <d3dx10.h>
#include <DirectXMath.h>
#include <d3dCompiler.h>
#include <dinput.h>
#include <Windows.h>
#include "MoveCamera.h"
#define FILE_NAME "sword.obj"
using namespace std;
using namespace DirectX;
//安全に解放する
#define SAFE_RELEASE(x) if(x){x->Release(); x=NULL;}
//定数定義
#define WINDOW_WIDTH 1280 //ウィンドウ幅
#define WINDOW_HEIGHT 720 //ウィンドウ高さ
#define DIRECTINPUT_VERSION 0x0800
//グローバル変数
HWND hWnd = NULL;
HWND ActiveWnd = NULL;
ID3D11Device* Device = NULL; //デバイス
ID3D11DeviceContext* DeviceContext = NULL; //デバイスコンテキスト
IDXGISwapChain* SwapChain = NULL; //スワップチェイン
ID3D11RenderTargetView* RenderTargetView = NULL; //レンダーターゲットビュー
ID3D11DepthStencilView* DepthStencilView = NULL;
ID3D11Texture2D* DepthStencil = NULL;
ID3D11InputLayout* VertexLayout = NULL;
ID3D11VertexShader* VertexShader = NULL;//頂点シェーダー
ID3D11PixelShader* PixelShader = NULL;//ピクセルシェーダー
ID3D11Buffer* ConstantBuffer[2];//コンスタントバッファ
D3DXVECTOR3 LightDir(1, 1, -1);//ライト方向
D3DXVECTOR3 CameraEye(0.0, 0.0, -200.0);//カメラ視点
D3DXVECTOR3 CameraAt(0.0, 0.0, 0.0);//カメラ注視点
D3DXVECTOR2 CameraRad(XM_PI / 2, XM_PI / 2);//カメラアングル
ID3D11SamplerState* SampleLinear = NULL;//テクスチャーのサンプラー
ID3D11ShaderResourceView* Texture = NULL;//テクスチャー
LPDIRECTINPUT8 g_pDInput = NULL; // DirectInputオブジェクト
LPDIRECTINPUTDEVICE8 g_pDIMouse = NULL; // マウスデバイス
DIMOUSESTATE g_zdiMouseState;
//シェーダーに渡す値
struct SHADER_GLOBAL0
{
D3DXMATRIX mW;//ワールド行列
D3DXMATRIX mWVP;//ワールドから射影までの変換行列
D3DXVECTOR4 vLightDir;//ライト方向
D3DXVECTOR4 vEye;//カメラ位置
};
struct SHADER_GLOBAL1
{
D3DXVECTOR4 vAmbient;//アンビエント
D3DXVECTOR4 vDiffuse;//ディフューズ
D3DXVECTOR4 vSpecular;//鏡面反射
};
//マテリアル構造体
struct MATERIAL
{
CHAR Name[255];
D3DXVECTOR4 Ka;//アンビエント
D3DXVECTOR4 Kd;//ディフューズ
D3DXVECTOR4 Ks;//スペキュラー
CHAR TextureName[255];//テクスチャファイル名
ID3D11ShaderResourceView* pTexture;//テクスチャデータ
DWORD MaxFace;//ポリゴン数
}mat;
//頂点構造体
struct VERTEX
{
D3DXVECTOR3 Pos;//位置
D3DXVECTOR3 Normal;//法線
D3DXVECTOR2 UV;//UV
}vert;
//.OBJファイルクラス
class OBJ {
protected:
vector <MATERIAL> Material;//マテリアル
vector <VERTEX> Vertex;//頂点構造体
ID3D11Buffer* VertexBuffer;//頂点バッファ
ID3D11Buffer** IndexBuffer;//インデックスバッファ
HRESULT LoadMaterialFromFile(LPSTR FileName);//マテリアルファイル読み込み
public:
void Draw();//描画
HRESULT Load(LPSTR FileName);//読み込み
};
OBJ obj;
//メッシュの描画
void OBJ::Draw()
{
//バーテックスバッファをセット
UINT stride = sizeof(VERTEX);
UINT offset = 0;
DeviceContext->IASetVertexBuffers(0, 1, &VertexBuffer, &stride, &offset);
//マテリアルの数だけ、それぞれのマテリアルのインデックスバッファを描画
for (DWORD i = 0; i < Material.size(); i++)
{
//使用されていないマテリアル対策
if (Material[i].MaxFace == 0)
{
continue;
}
//インデックスバッファをセット
DeviceContext->IASetIndexBuffer(IndexBuffer[i], DXGI_FORMAT_R32_UINT, 0);
//プリミティブ・トポロジーをセット
DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
//マテリアルの各要素をシェーダーに渡す
D3D11_MAPPED_SUBRESOURCE pData;
if (SUCCEEDED(DeviceContext->Map(ConstantBuffer[1], 0, D3D11_MAP_WRITE_DISCARD, 0, &pData)))
{
SHADER_GLOBAL1 sg;
sg.vAmbient = Material[i].Ka;
sg.vDiffuse = Material[i].Kd;
sg.vSpecular = Material[i].Ks;
memcpy_s(pData.pData, pData.RowPitch, (void*)&sg, sizeof(SHADER_GLOBAL1));
DeviceContext->Unmap(ConstantBuffer[1], 0);
}
DeviceContext->VSSetConstantBuffers(1, 1, &ConstantBuffer[1]);
DeviceContext->PSSetConstantBuffers(1, 1, &ConstantBuffer[1]);
//テクスチャをシェーダーに渡す
if (Material[i].TextureName[0] != NULL)
{
DeviceContext->PSSetSamplers(0, 1, &SampleLinear);
DeviceContext->PSSetShaderResources(0, 1, &Material[i].pTexture);
}
DeviceContext->DrawIndexed(Material[i].MaxFace * 3, 0, 0);
}
}
//マテリアルファイルを読み込む関数
HRESULT OBJ::LoadMaterialFromFile(LPSTR FileName)
{
FILE* fp = NULL;
fopen_s(&fp, FileName, "rt");
char key[255] = { 0 };
bool flag = false;
D3DXVECTOR4 v(0, 0, 0, 0);
fseek(fp, SEEK_SET, 0);
while (!feof(fp))
{
//キーワード読み込み
fscanf_s(fp, "%s ", key, sizeof(key));
//マテリアル名
if (strcmp(key, "newmtl") == 0)
{
if (flag)Material.push_back(mat);
flag = true;
fscanf_s(fp, "%s ", key, sizeof(key));
strcpy_s(mat.Name, key);
}
//Ka アンビエント
if (strcmp(key, "Ka") == 0)
{
fscanf_s(fp, "%f %f %f", &v.x, &v.y, &v.z);
mat.Ka = v;
}
//Kd ディフューズ
if (strcmp(key, "Kd") == 0)
{
fscanf_s(fp, "%f %f %f", &v.x, &v.y, &v.z);
mat.Kd = v;
}
//Ks スペキュラー
if (strcmp(key, "Ks") == 0)
{
fscanf_s(fp, "%f %f %f", &v.x, &v.y, &v.z);
mat.Ks = v;
}
//map_Kd テクスチャ
if (strcmp(key, "map_Kd") == 0)
{
fscanf_s(fp, "%s", &mat.TextureName, sizeof(mat.TextureName));
//テクスチャを作成
if (FAILED(D3DX11CreateShaderResourceViewFromFileA(Device, mat.TextureName, NULL, NULL, &mat.pTexture, NULL)))
{
return E_FAIL;
}
}
}
fclose(fp);
if (flag)Material.push_back(mat);
return S_OK;
}
//OBJファイルからメッシュに必要な情報を読み込む
HRESULT OBJ::Load(LPSTR FileName)
{
//一時代入用
D3DXVECTOR3 vec3d;
D3DXVECTOR2 vec2d;
vector <D3DXVECTOR3> Pos;
vector <D3DXVECTOR3> Normal;
vector <D3DXVECTOR2> UV;
vector <int> FaceIndex;
int v1 = 0, v2 = 0, v3 = 0;
int vn1 = 0, vn2 = 0, vn3 = 0;
int vt1 = 0, vt2 = 0, vt3 = 0;
DWORD dwFCount = 0;//読み込みカウンタ
char key[255] = { 0 };
//OBJファイルを開いて内容を読み込む
FILE* fp = NULL;
fopen_s(&fp, FileName, "rt");
//読み込み
fseek(fp, SEEK_SET, 0);
while (!feof(fp))
{
//キーワード
ZeroMemory(key, sizeof(key));
fscanf_s(fp, "%s ", key, sizeof(key));
//マテリアル
if (strcmp(key, "mtllib") == 0)
{
fscanf_s(fp, "%s ", key, sizeof(key));
LoadMaterialFromFile(key);
}
//頂点
if (strcmp(key, "v") == 0)
{
fscanf_s(fp, "%f %f %f", &vec3d.x, &vec3d.y, &vec3d.z);
Pos.push_back(vec3d);
Vertex.push_back(vert);
}
//法線
if (strcmp(key, "vn") == 0)
{
fscanf_s(fp, "%f %f %f", &vec3d.x, &vec3d.y, &vec3d.z);
Normal.push_back(vec3d);
}
//テクスチャ
if (strcmp(key, "vt") == 0)
{
fscanf_s(fp, "%f %f", &vec2d.x, &vec2d.y);
UV.push_back(-vec2d);
}
//フェイス
if (strcmp(key, "f") == 0)
{
FaceIndex.push_back(0);
FaceIndex.push_back(0);
FaceIndex.push_back(0);
}
}
//マテリアルの数だけインデックスバッファを作成
IndexBuffer = new ID3D11Buffer*[Material.size()];
bool boFlag = false;
for (DWORD i = 0; i < Material.size(); i++)
{
fseek(fp, SEEK_SET, 0);
dwFCount = 0;
while (!feof(fp))
{
//キーワード
ZeroMemory(key, sizeof(key));
fscanf_s(fp, "%s ", key, sizeof(key));
//フェイス 読み込み→頂点インデックスに
if (strcmp(key, "usemtl") == 0)
{
fscanf_s(fp, "%s ", key, sizeof(key));
if (strcmp(key, Material[i].Name) == 0)
{
boFlag = true;
}
else
{
boFlag = false;
}
}
if (strcmp(key, "f") == 0 && boFlag == true)
{
fscanf_s(fp, "%d/%d/%d %d/%d/%d %d/%d/%d", &v1, &vt1, &vn1, &v2, &vt2, &vn2, &v3, &vt3, &vn3);
//if (Material[i].pTexture != NULL)//テクスチャーありサーフェイス
//{
// fscanf_s(fp, "%d/%d/%d %d/%d/%d %d/%d/%d", &v1, &vt1, &vn1, &v2, &vt2, &vn2, &v3, &vt3, &vn3);
//}
//else//テクスチャー無しサーフェイス
//{
// fscanf_s(fp, "%d//%d %d//%d %d//%d", &v1, &vn1, &v2, &vn2, &v3, &vn3);
//}
FaceIndex[dwFCount * 3] = v1 - 1;
FaceIndex[dwFCount * 3 + 1] = v2 - 1;
FaceIndex[dwFCount * 3 + 2] = v3 - 1;
dwFCount++;
//頂点構造体に代入
Vertex[v1 - 1].Pos = Pos[v1 - 1];
Vertex[v1 - 1].Normal = Normal[vn1 - 1];
Vertex[v1 - 1].UV = UV[vt1 - 1];
Vertex[v2 - 1].Pos = Pos[v2 - 1];
Vertex[v2 - 1].Normal = Normal[vn2 - 1];
Vertex[v2 - 1].UV = UV[vt2 - 1];
Vertex[v3 - 1].Pos = Pos[v3 - 1];
Vertex[v3 - 1].Normal = Normal[vn3 - 1];
Vertex[v3 - 1].UV = UV[vt3 - 1];
}
}
if (dwFCount == 0)//使用されていないマテリアル対策
{
IndexBuffer[i] = NULL;
continue;
}
//インデックスバッファを作成
D3D11_BUFFER_DESC bd;
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof(int) * dwFCount * 3;
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = &FaceIndex[0];
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;
if (FAILED(Device->CreateBuffer(&bd, &InitData, &IndexBuffer[i])))return FALSE;
Material[i].MaxFace = dwFCount;
}
FaceIndex.clear();
fclose(fp);
//バーテックスバッファを作成
D3D11_BUFFER_DESC bd;
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof(VERTEX) *Vertex.size();
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
bd.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = &Vertex[0];
if (FAILED(Device->CreateBuffer(&bd, &InitData, &VertexBuffer)))return FALSE;
Pos.clear();
Normal.clear();
UV.clear();
Vertex.clear();
return S_OK;
}
//Direct3Dの初期化関数
HRESULT InitD3D(HWND hWnd)
{
// デバイスとスワップチェーンの作成
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1; //バックバッファの数
sd.BufferDesc.Width = WINDOW_WIDTH; //バッファの幅
sd.BufferDesc.Height = WINDOW_HEIGHT; //バッファの高さ
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //バッファのフォーマット
sd.BufferDesc.RefreshRate.Numerator = 60; //リフレッシュレート
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
D3D_FEATURE_LEVEL FeatureLevel = D3D_FEATURE_LEVEL_11_0;
D3D_FEATURE_LEVEL* pFeatureLevel = NULL;
if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0,
&FeatureLevel, 1, D3D11_SDK_VERSION, &sd, &SwapChain, &Device, NULL, &DeviceContext)))
{
return FALSE;
}
//レンダーターゲットビューの作成
ID3D11Texture2D *BackBuffer;
SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&BackBuffer);
Device->CreateRenderTargetView(BackBuffer, NULL, &RenderTargetView);
SAFE_RELEASE(BackBuffer);
//深度ステンシルビューの作成
D3D11_TEXTURE2D_DESC descDepth;
descDepth.Width = WINDOW_WIDTH;
descDepth.Height = WINDOW_HEIGHT;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = DXGI_FORMAT_D32_FLOAT;
descDepth.SampleDesc.Count = 1;
descDepth.SampleDesc.Quality = 0;
descDepth.Usage = D3D11_USAGE_DEFAULT;
descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;
Device->CreateTexture2D(&descDepth, NULL, &DepthStencil);
Device->CreateDepthStencilView(DepthStencil, NULL, &DepthStencilView);
//レンダーターゲットビューと深度ステンシルビューをパイプラインにバインド
DeviceContext->OMSetRenderTargets(1, &RenderTargetView, DepthStencilView);
//ビューポートの設定
D3D11_VIEWPORT vp;
vp.Width = WINDOW_WIDTH;
vp.Height = WINDOW_HEIGHT;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
DeviceContext->RSSetViewports(1, &vp);
//hlslファイル読み込み
ID3DBlob *pCompiledShader = NULL;
ID3DBlob *pErrors = NULL;
//ブロブから頂点シェーダー作成
if (FAILED(D3DX11CompileFromFile("shader.hlsl", NULL, NULL, "VS", "vs_5_0", 0, 0, NULL, &pCompiledShader, &pErrors, NULL)))
{
MessageBox(0, "頂点シェーダー読み込み失敗", NULL, MB_OK);
return E_FAIL;
}
SAFE_RELEASE(pErrors);
if (FAILED(Device->CreateVertexShader(pCompiledShader->GetBufferPointer(), pCompiledShader->GetBufferSize(), NULL, &VertexShader)))
{
SAFE_RELEASE(pCompiledShader);
MessageBox(0, "頂点シェーダー作成失敗", NULL, MB_OK);
return E_FAIL;
}
//頂点インプットレイアウトを定義
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = sizeof(layout) / sizeof(layout[0]);
//頂点インプットレイアウトを作成
if (FAILED(Device->CreateInputLayout(layout, numElements, pCompiledShader->GetBufferPointer(), pCompiledShader->GetBufferSize(), &VertexLayout)))
return FALSE;
//頂点インプットレイアウトをセット
DeviceContext->IASetInputLayout(VertexLayout);
//ブロブからピクセルシェーダー作成
if (FAILED(D3DX11CompileFromFile("shader.hlsl", NULL, NULL, "PS", "ps_5_0", 0, 0, NULL, &pCompiledShader, &pErrors, NULL)))
{
MessageBox(0, "ピクセルシェーダー読み込み失敗", NULL, MB_OK);
return E_FAIL;
}
SAFE_RELEASE(pErrors);
if (FAILED(Device->CreatePixelShader(pCompiledShader->GetBufferPointer(), pCompiledShader->GetBufferSize(), NULL, &PixelShader)))
{
SAFE_RELEASE(pCompiledShader);
MessageBox(0, "ピクセルシェーダー作成失敗", NULL, MB_OK);
return E_FAIL;
}
SAFE_RELEASE(pCompiledShader);
//ラスタライズ設定
D3D11_RASTERIZER_DESC rdc;
ZeroMemory(&rdc, sizeof(rdc));
rdc.CullMode = D3D11_CULL_NONE;
rdc.FillMode = D3D11_FILL_SOLID;
ID3D11RasterizerState* pIr = NULL;
Device->CreateRasterizerState(&rdc, &pIr);
DeviceContext->RSSetState(pIr);
SAFE_RELEASE(pIr);
//コンスタントバッファー作成 ここでは変換行列渡し用
D3D11_BUFFER_DESC cb;
cb.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cb.ByteWidth = sizeof(SHADER_GLOBAL0);
cb.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cb.MiscFlags = 0;
cb.StructureByteStride = 0;
cb.Usage = D3D11_USAGE_DYNAMIC;
if (FAILED(Device->CreateBuffer(&cb, NULL, &ConstantBuffer[0])))
{
return E_FAIL;
}
//コンスタントバッファー作成 マテリアル渡し用
cb.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cb.ByteWidth = sizeof(SHADER_GLOBAL1);
cb.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cb.MiscFlags = 0;
cb.StructureByteStride = 0;
cb.Usage = D3D11_USAGE_DYNAMIC;
if (FAILED(Device->CreateBuffer(&cb, NULL, &ConstantBuffer[1])))
{
return E_FAIL;
}
//テクスチャー用サンプラー作成
D3D11_SAMPLER_DESC SamDesc;
ZeroMemory(&SamDesc, sizeof(D3D11_SAMPLER_DESC));
SamDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
SamDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
SamDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
SamDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
Device->CreateSamplerState(&SamDesc, &SampleLinear);
//OBJファイルからオリジナルメッシュを作成
obj.Load((LPSTR)FILE_NAME);
return S_OK;
}
//レンダリング
VOID Render()
{
//マウスの状態を取得
HRESULT hr = g_pDIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &g_zdiMouseState);
float ClearColor[4] = { 0,0,1,1 }; // クリア色作成 RGBAの順
DeviceContext->ClearRenderTargetView(RenderTargetView, ClearColor);//画面クリア
DeviceContext->ClearDepthStencilView(DepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);//深度バッファクリア
//変換行列作成
D3DXMATRIX mWorld;
D3DXMATRIX mView;
D3DXMATRIX mProj;
//ワールド行列
static float angle = 0;
//angle += 0.03f;
D3DXMATRIX mRot;
D3DXMatrixRotationY(&mRot, (float)D3DXToRadian(angle));
mWorld = mRot;
//ビュー行列操作
MoveCamera(&g_zdiMouseState, &CameraAt, &CameraEye, &CameraRad);
D3DXVECTOR3 Up(0.0f, 1.0f, 0.0f);
D3DXMatrixLookAtLH(&mView, &CameraEye, &CameraAt, &Up);
//プロジェクション行列
D3DXMatrixPerspectiveFovLH(&mProj, (float)D3DX_PI / 4, (float)WINDOW_WIDTH / (float)WINDOW_HEIGHT, 0.1f, 1000.0f);
//ワールド・ビュー・プロジェクション行列をシェーダーに渡す
DeviceContext->VSSetConstantBuffers(0, 1, &ConstantBuffer[0]);
D3D11_MAPPED_SUBRESOURCE pData;
if (SUCCEEDED(DeviceContext->Map(ConstantBuffer[0], 0, D3D11_MAP_WRITE_DISCARD, 0, &pData)))
{
SHADER_GLOBAL0 sg;
sg.mW = mWorld;
D3DXMatrixTranspose(&sg.mW, &sg.mW);
sg.mWVP = mWorld * mView*mProj;
D3DXMatrixTranspose(&sg.mWVP, &sg.mWVP);
sg.vLightDir = D3DXVECTOR4(LightDir.x, LightDir.y, LightDir.z, 0.0f);
sg.vEye = D3DXVECTOR4(CameraEye.x, CameraEye.y, CameraEye.z, 0);
memcpy_s(pData.pData, pData.RowPitch, (void*)&sg, sizeof(SHADER_GLOBAL0));
DeviceContext->Unmap(ConstantBuffer[0], 0);
}
DeviceContext->VSSetConstantBuffers(0, 1, &ConstantBuffer[0]);
DeviceContext->PSSetConstantBuffers(0, 1, &ConstantBuffer[0]);
//使用するシェーダーの登録
DeviceContext->VSSetShader(VertexShader, NULL, 0);
DeviceContext->PSSetShader(PixelShader, NULL, 0);
//メッシュを描画
obj.Draw();
ShowCursor(true);
SwapChain->Present(0, 0);//フリップ
}
//終了時解放処理
VOID Cleanup()
{
SAFE_RELEASE(SampleLinear);
SAFE_RELEASE(Texture);
SAFE_RELEASE(DepthStencil);
SAFE_RELEASE(DepthStencilView);
SAFE_RELEASE(VertexShader);
SAFE_RELEASE(PixelShader);
SAFE_RELEASE(ConstantBuffer[0]);
SAFE_RELEASE(ConstantBuffer[1]);
SAFE_RELEASE(VertexLayout);
SAFE_RELEASE(SwapChain);
SAFE_RELEASE(RenderTargetView);
SAFE_RELEASE(DeviceContext);
SAFE_RELEASE(Device);
SAFE_RELEASE(g_pDInput);
SAFE_RELEASE(g_pDIMouse);
}
//メッセージプロシージャ
LRESULT CALLBACK MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY://終了時
Cleanup();
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
bool InitMouse(HINSTANCE hInst) {
//入力関係初期化
HRESULT ret = DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&g_pDInput, NULL);
if (FAILED(ret)) {
return false; // 作成に失敗
}
if (g_pDInput == NULL) {
return false;
}
// マウス用にデバイスオブジェクトを作成
ret = g_pDInput->CreateDevice(GUID_SysMouse, &g_pDIMouse, NULL);
if (FAILED(ret)) {
// デバイスの作成に失敗
return false;
}
// データフォーマットを設定
ret = g_pDIMouse->SetDataFormat(&c_dfDIMouse); // マウス用のデータ・フォーマットを設定
if (FAILED(ret)) {
// データフォーマットに失敗
return false;
}
// モードを設定(フォアグラウンド&非排他モード)
ret = g_pDIMouse->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
if (FAILED(ret)) {
// モードの設定に失敗
return false;
}
// デバイスの設定
DIPROPDWORD diprop;
diprop.diph.dwSize = sizeof(diprop);
diprop.diph.dwHeaderSize = sizeof(diprop.diph);
diprop.diph.dwObj = 0;
diprop.diph.dwHow = DIPH_DEVICE;
diprop.dwData = DIPROPAXISMODE_REL; // 相対値モードで設定(絶対値はDIPROPAXISMODE_ABS)
ret = g_pDIMouse->SetProperty(DIPROP_AXISMODE, &diprop.diph);
if (FAILED(ret)) {
// デバイスの設定に失敗
return false;
}
// 入力制御開始
g_pDIMouse->Acquire();
return true;
}
//メイン関数
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR szStr, INT iCmdShow)
{
//ウインドウクラスの登録
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
"Window1", NULL };
RegisterClassEx(&wc);
//タイトルバーとウインドウ枠の分を含めてウインドウサイズを設定
RECT rect;
SetRect(&rect, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
rect.right = rect.right - rect.left;
rect.bottom = rect.bottom - rect.top;
rect.top = 0;
rect.left = 0;
//ウインドウの生成
hWnd = CreateWindow("Window1", "OBJローダ",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rect.right, rect.bottom,
NULL, NULL, wc.hInstance, NULL);
MSG msg;
ZeroMemory(&msg, sizeof(msg));
//Direct3D初期化
if (!SUCCEEDED(InitD3D(hWnd))) {
return false;
}
//ウインドウ表示
ShowWindow(hWnd, SW_NORMAL);
UpdateWindow(hWnd);
while (msg.message != WM_QUIT)
{
bool nowActive = true;
ActiveWnd = GetActiveWindow();
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
if (g_pDInput == NULL) {
InitMouse(hInst);
}
Render();
}
//Escキーが押されたら終了
BYTE key[256];
GetKeyboardState(key);
if (key[VK_ESCAPE] & 0x80) {
break;
}
if (hWnd == ActiveWnd) {
if (nowActive == false) {
if (InitMouse(hInst)) {
nowActive = true;
}
}
}
else {
SAFE_RELEASE(g_pDInput);
SAFE_RELEASE(g_pDIMouse);
nowActive = false;
}
}
} | [
"katsuto-kawauchi@koeitecmo.co.jp"
] | katsuto-kawauchi@koeitecmo.co.jp |
b11716018f39a8f16761d6e1785d3c6d73b11e40 | b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1 | /tensorflow/compiler/xla/service/hlo_instruction.cc | afe4680ed9ade4dcfb190ed3f05a41c0058992f2 | [
"Apache-2.0"
] | permissive | uve/tensorflow | e48cb29f39ed24ee27e81afd1687960682e1fbef | e08079463bf43e5963acc41da1f57e95603f8080 | refs/heads/master | 2020-11-29T11:30:40.391232 | 2020-01-11T13:43:10 | 2020-01-11T13:43:10 | 230,088,347 | 0 | 0 | Apache-2.0 | 2019-12-25T10:49:15 | 2019-12-25T10:49:14 | null | UTF-8 | C++ | false | false | 144,979 | cc | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include <algorithm>
#include <ostream>
#include <set>
#include <unordered_set>
#include <utility>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/memory/memory.h"
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/types/span.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/protobuf_util.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_sharding_metadata.h"
#include "tensorflow/compiler/xla/service/name_uniquer.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/platform/human_readable_json.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
using absl::CEscape;
using absl::StrAppend;
using absl::StrCat;
using absl::StrJoin;
/* static */
StatusOr<std::unique_ptr<HloInstruction>> HloInstruction::CreateFromProto(
const HloInstructionProto& proto,
const absl::flat_hash_map<int64, HloInstruction*>& instruction_map,
const absl::flat_hash_map<int64, HloComputation*>& computation_map) {
TF_RET_CHECK(!proto.opcode().empty());
HloOpcode opcode;
auto opcode_or = StringToHloOpcode(proto.opcode());
absl::optional<ComparisonDirection> comparison_direction;
if (opcode_or.ok()) {
opcode = opcode_or.ConsumeValueOrDie();
} else {
// Unknown opcode. Try auto-upgrading deprecated "less-than",
// "greater-than", etc opcodes, which are now rolled into the kCompare
// opcode.
if (proto.opcode() == "equal-to") {
comparison_direction = ComparisonDirection::kEq;
} else if (proto.opcode() == "not-equal-to") {
comparison_direction = ComparisonDirection::kNe;
} else if (proto.opcode() == "greater-than-or-equal-to") {
comparison_direction = ComparisonDirection::kGe;
} else if (proto.opcode() == "greater-than") {
comparison_direction = ComparisonDirection::kGt;
} else if (proto.opcode() == "less-than-or-equal-to") {
comparison_direction = ComparisonDirection::kLe;
} else if (proto.opcode() == "less-than") {
comparison_direction = ComparisonDirection::kLt;
}
if (comparison_direction) {
opcode = HloOpcode::kCompare;
} else {
return InvalidArgument("Unknown opcode: %s", proto.opcode());
}
}
TF_RET_CHECK(proto.has_shape());
std::unique_ptr<HloInstruction> instruction;
const auto operands = [&instruction_map, &proto](int index) {
return instruction_map.at(proto.operand_ids(index));
};
const auto all_operands = [&instruction_map, &proto]() {
std::vector<HloInstruction*> result(proto.operand_ids_size());
std::transform(proto.operand_ids().begin(), proto.operand_ids().end(),
result.begin(), [&instruction_map](int64 operand_id) {
return instruction_map.at(operand_id);
});
return result;
};
const auto computations = [&computation_map, &proto](int index) {
return computation_map.at(proto.called_computation_ids(index));
};
const auto all_computations = [&computation_map, &proto]() {
std::vector<HloComputation*> result(proto.called_computation_ids_size());
std::transform(proto.called_computation_ids().begin(),
proto.called_computation_ids().end(), result.begin(),
[&computation_map](int64 computation_id) {
return computation_map.at(computation_id);
});
return result;
};
TF_RET_CHECK(
absl::c_all_of(proto.operand_ids(),
[&](int64 id) { return instruction_map.contains(id); }))
<< proto.name() << " instruction contains invalid operand id(s)";
TF_RET_CHECK(
absl::c_all_of(proto.called_computation_ids(),
[&](int64 id) { return computation_map.contains(id); }))
<< proto.name() << " instruction references invalid computation id(s)";
Shape shape(proto.shape());
TF_RETURN_IF_ERROR(ShapeUtil::ValidateShapeWithOptionalLayout(shape));
absl::optional<int> arity = HloOpcodeArity(opcode);
if (arity) {
TF_RET_CHECK(proto.operand_ids_size() == *arity)
<< proto.opcode() << " instruction should have " << *arity
<< " operands but sees " << proto.operand_ids_size();
}
switch (opcode) {
// Ops migrated to subclasses.
case HloOpcode::kBatchNormTraining:
instruction =
CreateBatchNormTraining(shape, operands(0), operands(1), operands(2),
proto.epsilon(), proto.feature_index());
break;
case HloOpcode::kBatchNormInference:
instruction = CreateBatchNormInference(
shape, operands(0), operands(1), operands(2), operands(3),
operands(4), proto.epsilon(), proto.feature_index());
break;
case HloOpcode::kBatchNormGrad:
instruction = CreateBatchNormGrad(shape, operands(0), operands(1),
operands(2), operands(3), operands(4),
proto.epsilon(), proto.feature_index());
break;
case HloOpcode::kFft: {
std::vector<int64> fft_length(proto.fft_length().begin(),
proto.fft_length().end());
instruction = CreateFft(shape, operands(0), proto.fft_type(),
absl::Span<const int64>(fft_length));
break;
}
case HloOpcode::kCompare: {
// Auto-upgraded from deprecated opcode skips the following.
if (!comparison_direction) {
TF_ASSIGN_OR_RETURN(
comparison_direction,
StringToComparisonDirection(proto.comparison_direction()));
}
instruction =
CreateCompare(shape, operands(0), operands(1), *comparison_direction);
break;
}
case HloOpcode::kTriangularSolve: {
instruction = CreateTriangularSolve(shape, operands(0), operands(1),
proto.triangular_solve_options());
break;
}
case HloOpcode::kCholesky: {
instruction =
CreateCholesky(shape, operands(0), proto.cholesky_options());
break;
}
case HloOpcode::kSend:
instruction = CreateSend(operands(0), operands(1), proto.channel_id(),
proto.is_host_transfer());
break;
case HloOpcode::kSendDone:
instruction = CreateSendDone(operands(0), proto.is_host_transfer());
break;
case HloOpcode::kRecv:
instruction = CreateRecv(shape.tuple_shapes(0), operands(0),
proto.channel_id(), proto.is_host_transfer());
break;
case HloOpcode::kRecvDone:
instruction = CreateRecvDone(operands(0), proto.is_host_transfer());
break;
case HloOpcode::kReverse:
instruction = CreateReverse(shape, operands(0),
std::vector<int64>(proto.dimensions().begin(),
proto.dimensions().end()));
break;
case HloOpcode::kConcatenate:
TF_RET_CHECK(proto.dimensions_size() == 1)
<< "Concatenate instruction should have 1 dimension but sees "
<< proto.dimensions_size();
instruction =
CreateConcatenate(shape, all_operands(), proto.dimensions(0));
break;
case HloOpcode::kConditional: {
TF_RET_CHECK(proto.called_computation_ids_size() > 0)
<< "conditional should have at least 1 called computation";
if (operands(0)->shape().element_type() == PRED) {
TF_RET_CHECK(proto.called_computation_ids_size() == 2)
<< "conditional should have exactly 2 called computations but got "
<< proto.called_computation_ids_size();
}
TF_RET_CHECK(proto.operand_ids_size() ==
proto.called_computation_ids_size() + 1)
<< "conditional should have one branch_index operand plus one "
"operand per called computation but got "
<< proto.operand_ids_size() << " operands for "
<< proto.called_computation_ids_size() << " branch computations";
auto cond_operands = all_operands();
instruction =
CreateConditional(shape, cond_operands[0], all_computations(),
absl::MakeSpan(cond_operands).subspan(1));
break;
}
case HloOpcode::kReduce:
TF_RET_CHECK(proto.operand_ids_size() % 2 == 0)
<< "Reduce instruction should have an even number of operands but "
"sees "
<< proto.operand_ids_size();
TF_RET_CHECK(proto.called_computation_ids_size() == 1)
<< "Reduce instruction should have 1 called computation but sees "
<< proto.called_computation_ids_size();
{
const auto reduce_operands = all_operands();
auto inputs = absl::MakeSpan(reduce_operands)
.subspan(0, reduce_operands.size() / 2);
auto init_values =
absl::MakeSpan(reduce_operands)
.subspan(reduce_operands.size() / 2, reduce_operands.size());
instruction =
CreateReduce(shape, inputs, init_values,
std::vector<int64>(proto.dimensions().begin(),
proto.dimensions().end()),
computations(0));
}
break;
case HloOpcode::kSort: {
TF_RET_CHECK(proto.operand_ids_size() >= 1)
<< "Sort instruction should have at least 1 operand but has "
<< proto.operand_ids_size();
TF_RET_CHECK(proto.dimensions().size() == 1)
<< "Sort instruction should have 1 dimension";
TF_RET_CHECK(proto.called_computation_ids_size() == 1)
<< "Sort instruction should one called computation but sees "
<< proto.called_computation_ids_size();
auto sort_operands = all_operands();
instruction = CreateSort(shape, proto.dimensions(0), all_operands(),
computations(0), proto.is_stable());
break;
}
case HloOpcode::kTranspose:
instruction =
CreateTranspose(shape, operands(0),
std::vector<int64>(proto.dimensions().begin(),
proto.dimensions().end()));
break;
case HloOpcode::kBroadcast:
instruction =
CreateBroadcast(shape, operands(0),
std::vector<int64>(proto.dimensions().begin(),
proto.dimensions().end()));
break;
case HloOpcode::kMap:
TF_RET_CHECK(proto.called_computation_ids_size() == 1)
<< "Map instruction should have 1 called computation but sees "
<< proto.called_computation_ids_size();
instruction = CreateMap(shape, all_operands(), computations(0));
break;
case HloOpcode::kSlice: {
std::vector<int64> slice_starts, slice_limits, slice_strides;
for (const HloInstructionProto::SliceDimensions& slice_dimensions :
proto.slice_dimensions()) {
slice_starts.push_back(slice_dimensions.start());
slice_limits.push_back(slice_dimensions.limit());
slice_strides.push_back(slice_dimensions.stride());
}
instruction = CreateSlice(shape, operands(0), slice_starts, slice_limits,
slice_strides);
break;
}
case HloOpcode::kConstant: {
// TODO(b/110214922): Revert this to CHECK(proto.has_literal()).
if (proto.has_literal()) {
TF_ASSIGN_OR_RETURN(auto literal,
Literal::CreateFromProto(proto.literal()));
instruction = CreateConstant(std::move(literal));
// Literal's shape may have no/different tiling info.
TF_RET_CHECK(Shape::Equal().MinorToMajorOnlyInLayout()(
instruction->shape(), shape));
*instruction->mutable_shape() = shape;
} else {
instruction = absl::make_unique<HloConstantInstruction>(shape);
}
break;
}
case HloOpcode::kTrace: {
TF_RET_CHECK(proto.has_literal());
TF_ASSIGN_OR_RETURN(auto literal,
Literal::CreateFromProto(proto.literal()));
instruction = CreateTrace(literal.GetR1U8AsString(), operands(0));
break;
}
case HloOpcode::kFusion: {
// In the proto, fused computations are held exclusively within the
// HloInstructionProto and do not appear as an HloComputationProto within
// the HloModuleProto.
TF_RET_CHECK(!proto.fusion_kind().empty());
TF_ASSIGN_OR_RETURN(FusionKind fusion_kind,
StringToFusionKind(proto.fusion_kind()));
// Find the fused computation and set its fusion instruction.
TF_RET_CHECK(proto.called_computation_ids_size() == 1)
<< "Expect 1 called computation for fusion instruction but sees "
<< proto.called_computation_ids_size();
const int64 fusion_id = proto.called_computation_ids(0);
auto* fused_computation =
tensorflow::gtl::FindPtrOrNull(computation_map, fusion_id);
TF_RET_CHECK(fused_computation != nullptr)
<< "No fusion computation with id " << fusion_id;
instruction =
CreateFusion(shape, fusion_kind, all_operands(), fused_computation);
break;
}
case HloOpcode::kRng:
instruction = CreateRng(shape, proto.distribution(), all_operands());
break;
case HloOpcode::kRngGetAndUpdateState:
instruction = CreateRngGetAndUpdateState(shape, proto.delta());
break;
case HloOpcode::kParameter:
instruction =
CreateParameter(proto.parameter_number(), shape, proto.name());
if (!proto.parameter_replication().replicated_at_leaf_buffers().empty()) {
instruction->set_parameter_replicated_at_leaf_buffers(
proto.parameter_replication().replicated_at_leaf_buffers());
}
break;
case HloOpcode::kGetTupleElement:
instruction =
CreateGetTupleElement(shape, operands(0), proto.tuple_index());
break;
case HloOpcode::kReducePrecision:
instruction = CreateReducePrecision(
shape, operands(0), proto.exponent_bits(), proto.mantissa_bits());
break;
case HloOpcode::kInfeed: {
TF_RET_CHECK(shape.IsTuple() &&
(ShapeUtil::TupleElementCount(shape) == 2))
<< "Infeed should have a tuple shape with 2 operands, but has: "
<< shape;
const Shape& data_shape = ShapeUtil::GetTupleElementShape(shape, 0);
instruction =
CreateInfeed(data_shape, operands(0), proto.infeed_config());
} break;
case HloOpcode::kOutfeed: {
Shape outfeed_shape(proto.outfeed_shape());
TF_RETURN_IF_ERROR(
ShapeUtil::ValidateShapeWithOptionalLayout(outfeed_shape));
instruction = CreateOutfeed(outfeed_shape, operands(0), operands(1),
proto.outfeed_config());
break;
}
case HloOpcode::kAllReduce: {
TF_RET_CHECK(proto.called_computation_ids_size() == 1)
<< "AllReduce should have 1 called computation but sees "
<< proto.called_computation_ids_size();
TF_RET_CHECK(proto.channel_id() <= 0 || proto.all_reduce_id() <= 0)
<< "AllReduce cannot have both channel_id() and all_reduce_id()";
absl::optional<int64> channel_id;
if (proto.channel_id() > 0) {
channel_id = proto.channel_id();
}
if (proto.all_reduce_id() > 0) {
channel_id = proto.all_reduce_id();
}
instruction = CreateAllReduce(
shape, all_operands(), computations(0),
/*replica_groups=*/
std::vector<ReplicaGroup>(proto.replica_groups().begin(),
proto.replica_groups().end()),
/*channel_id=*/channel_id);
break;
}
case HloOpcode::kAllToAll: {
instruction = CreateAllToAll(
shape, all_operands(),
/*replica_groups=*/
std::vector<ReplicaGroup>(proto.replica_groups().begin(),
proto.replica_groups().end()));
break;
}
case HloOpcode::kCollectivePermute: {
std::vector<std::pair<int64, int64>> source_target_pairs(
proto.source_target_pairs_size());
absl::optional<int64> channel_id;
if (proto.channel_id() > 0) {
channel_id = proto.channel_id();
}
for (int i = 0; i < source_target_pairs.size(); i++) {
source_target_pairs[i].first = proto.source_target_pairs(i).source();
source_target_pairs[i].second = proto.source_target_pairs(i).target();
}
instruction = CreateCollectivePermute(shape, operands(0),
source_target_pairs, channel_id);
break;
}
case HloOpcode::kReplicaId: {
instruction = CreateReplicaId();
break;
}
case HloOpcode::kPartitionId: {
instruction = CreatePartitionId();
break;
}
case HloOpcode::kConvolution: {
TF_RET_CHECK(proto.has_window());
TF_RET_CHECK(proto.has_convolution_dimension_numbers());
PrecisionConfig precision_config = proto.precision_config();
precision_config.mutable_operand_precision()->Resize(
proto.operand_ids_size(), PrecisionConfig::DEFAULT);
instruction = CreateConvolve(
shape, operands(0), operands(1),
std::max<int64>(proto.feature_group_count(), 1),
std::max<int64>(proto.batch_group_count(), 1), proto.window(),
proto.convolution_dimension_numbers(), precision_config);
break;
}
case HloOpcode::kReduceWindow:
TF_RET_CHECK(proto.called_computation_ids_size() == 1)
<< "ReduceWindow should have 1 called computation but sees "
<< proto.called_computation_ids_size();
instruction = CreateReduceWindow(shape, operands(0), operands(1),
proto.window(), computations(0));
break;
case HloOpcode::kSelectAndScatter:
TF_RET_CHECK(proto.called_computation_ids_size() == 2)
<< "SelectAndScatter should have 2 called computations but sees "
<< proto.called_computation_ids_size();
instruction = CreateSelectAndScatter(shape, operands(0), computations(0),
proto.window(), operands(1),
operands(2), computations(1));
break;
case HloOpcode::kCustomCall: {
if (proto.constrain_layout()) {
// A proto RepeatedPtrField cannot be converted to a Span (it is a
// vector of pointers essentially) so create a vector of shapes to pass
// in.
std::vector<Shape> operand_shapes;
for (const ShapeProto& shape_proto :
proto.operand_shapes_with_layout()) {
operand_shapes.emplace_back(shape_proto);
}
instruction =
CreateCustomCall(shape, all_operands(), proto.custom_call_target(),
operand_shapes, proto.backend_config());
} else {
instruction =
CreateCustomCall(shape, all_operands(), proto.custom_call_target(),
proto.backend_config());
}
auto custom_call_instr =
Cast<HloCustomCallInstruction>(instruction.get());
if (proto.has_window()) {
custom_call_instr->set_window(proto.window());
}
if (proto.has_convolution_dimension_numbers()) {
custom_call_instr->set_convolution_dimension_numbers(
proto.convolution_dimension_numbers());
}
custom_call_instr->set_feature_group_count(
std::max(static_cast<int64>(proto.feature_group_count()), 1LL));
custom_call_instr->set_batch_group_count(
std::max(static_cast<int64>(proto.batch_group_count()), 1LL));
custom_call_instr->set_custom_call_has_side_effect(
proto.custom_call_has_side_effect());
break;
}
case HloOpcode::kPad:
TF_RET_CHECK(proto.has_padding_config());
instruction =
CreatePad(shape, operands(0), operands(1), proto.padding_config());
break;
case HloOpcode::kDynamicSlice: {
std::vector<int64> slice_sizes(proto.dynamic_slice_sizes_size());
absl::c_copy(proto.dynamic_slice_sizes(), slice_sizes.begin());
TF_RET_CHECK(proto.operand_ids_size() >= 1)
<< "DynamicSlice instruction should have at least 1 operands but "
"sees "
<< proto.operand_ids_size();
// TODO(b/118437727): Old form, make the check unconditional.
if (proto.operand_ids_size() != 2 || operands(1)->shape().rank() != 1) {
auto expected_operands = 1 + operands(0)->shape().rank();
TF_RET_CHECK(proto.operand_ids_size() == expected_operands)
<< "DynamicSlice instruction should have " << expected_operands
<< " operands, but has " << proto.operand_ids_size();
}
const auto& operand_vector = all_operands();
instruction = CreateDynamicSlice(
shape, operands(0), absl::MakeSpan(operand_vector).subspan(1),
slice_sizes);
break;
}
case HloOpcode::kDynamicUpdateSlice: {
TF_RET_CHECK(proto.operand_ids_size() >= 2)
<< "DynamicUpdateSlice instruction should have at least 2 operands "
"but sees "
<< proto.operand_ids_size();
// TODO(b/118437727): Old form, make the check unconditional.
if (proto.operand_ids_size() != 3 || operands(2)->shape().rank() != 1) {
auto expected_operands = 2 + operands(0)->shape().rank();
TF_RET_CHECK(proto.operand_ids_size() == expected_operands)
<< "DynamicUpdateSlice instruction should have "
<< expected_operands << " operands, but has "
<< proto.operand_ids_size();
}
const auto& operand_vector = all_operands();
instruction =
CreateDynamicUpdateSlice(shape, operands(0), operands(1),
absl::MakeSpan(operand_vector).subspan(2));
break;
}
case HloOpcode::kGather: {
TF_RET_CHECK(proto.has_gather_dimension_numbers())
<< "Gather instruction should have GatherDimensionNumbers set.";
std::unique_ptr<GatherDimensionNumbers> gather_dimension_numbers =
absl::make_unique<GatherDimensionNumbers>(
proto.gather_dimension_numbers());
std::vector<int64> gather_slice_sizes;
for (int64 bound : proto.gather_slice_sizes()) {
gather_slice_sizes.push_back(bound);
}
instruction = CreateGather(shape, operands(0), operands(1),
*gather_dimension_numbers, gather_slice_sizes);
break;
}
case HloOpcode::kScatter: {
TF_RET_CHECK(proto.has_scatter_dimension_numbers())
<< "Scatter instruction should have ScatterDimensionNumbers set.";
TF_RET_CHECK(proto.called_computation_ids_size() == 1)
<< "Scatter instruction should have 1 called computation but sees "
<< proto.called_computation_ids_size();
auto scatter_dimension_numbers =
absl::make_unique<ScatterDimensionNumbers>(
proto.scatter_dimension_numbers());
instruction = CreateScatter(shape, operands(0), operands(1), operands(2),
computations(0), *scatter_dimension_numbers);
break;
}
case HloOpcode::kIota:
TF_RET_CHECK(proto.dimensions_size() == 1)
<< "Iota instruction should have 1 dimension but sees "
<< proto.dimensions_size();
instruction = CreateIota(shape, proto.dimensions(0));
break;
case HloOpcode::kDot: {
TF_RET_CHECK(proto.has_dot_dimension_numbers())
<< "Dot instruction should have dot_dimension_numbers.";
PrecisionConfig precision_config = proto.precision_config();
precision_config.mutable_operand_precision()->Resize(
proto.operand_ids_size(), PrecisionConfig::DEFAULT);
instruction = absl::make_unique<HloDotInstruction>(
shape, operands(0), operands(1), proto.dot_dimension_numbers(),
precision_config);
break;
}
case HloOpcode::kDomain: {
std::shared_ptr<const HloSharding> entry_hlo_sharding;
std::shared_ptr<const HloSharding> exit_hlo_sharding;
if (proto.has_domain_entry_sharding()) {
TF_ASSIGN_OR_RETURN(
HloSharding sharding,
HloSharding::FromProto(proto.domain_entry_sharding()));
entry_hlo_sharding = std::make_shared<const HloSharding>(sharding);
}
if (proto.has_domain_exit_sharding()) {
TF_ASSIGN_OR_RETURN(
HloSharding sharding,
HloSharding::FromProto(proto.domain_exit_sharding()));
exit_hlo_sharding = std::make_shared<const HloSharding>(sharding);
}
instruction = absl::make_unique<HloDomainInstruction>(
shape, operands(0),
absl::make_unique<ShardingMetadata>(entry_hlo_sharding),
absl::make_unique<ShardingMetadata>(exit_hlo_sharding));
break;
}
case HloOpcode::kGetDimensionSize:
TF_RET_CHECK(proto.dimensions_size() == 1);
instruction =
CreateGetDimensionSize(shape, operands(0), proto.dimensions(0));
break;
case HloOpcode::kReshape: {
int64 inferred_dimension = -1;
if (!proto.dimensions().empty()) {
inferred_dimension = proto.dimensions()[0];
}
TF_RET_CHECK(shape.IsArray() && operands(0)->shape().IsArray() &&
ShapeUtil::ElementsIn(shape) ==
ShapeUtil::ElementsIn(operands(0)->shape()))
<< "shape: " << ShapeUtil::HumanString(shape)
<< " operand: " << ShapeUtil::HumanString(operands(0)->shape());
instruction = CreateReshape(shape, operands(0), inferred_dimension);
break;
}
default: {
instruction = absl::WrapUnique(new HloInstruction(opcode, shape));
for (const int64 operand_id : proto.operand_ids()) {
instruction->AppendOperand(instruction_map.at(operand_id));
}
if (instruction->opcode() != HloOpcode::kFusion) {
if (instruction->opcode() == HloOpcode::kCall) {
TF_RET_CHECK(proto.called_computation_ids_size() == 1)
<< "Call should have 1 called computation but has "
<< proto.called_computation_ids_size();
}
for (const int64 computation_id : proto.called_computation_ids()) {
instruction->called_computations_.push_back(
computation_map.at(computation_id));
}
}
TF_RET_CHECK(!proto.has_precision_config())
<< instruction->opcode() << proto.DebugString();
TF_RET_CHECK(!proto.has_dot_dimension_numbers()) << instruction->opcode();
break;
}
}
for (const int64 predecessor_id : proto.control_predecessor_ids()) {
TF_RET_CHECK(ContainsKey(instruction_map, predecessor_id))
<< "No instruction with id " << predecessor_id;
TF_RETURN_IF_ERROR(instruction_map.at(predecessor_id)
->AddControlDependencyTo(instruction.get()));
}
TF_RET_CHECK(!proto.name().empty());
instruction->SetAndSanitizeName(proto.name());
instruction->metadata_ = proto.metadata();
instruction->backend_config_ = proto.backend_config();
instruction->outer_dimension_partitions_.assign(
proto.outer_dimension_partitions().begin(),
proto.outer_dimension_partitions().end());
TF_RET_CHECK(proto.id() >= 0)
<< "Instruction with negative id: " << proto.id();
TF_RET_CHECK(proto.id() <= INT_MAX)
<< "Instruction with id > INT_MAX: " << proto.id();
instruction->unique_id_ = proto.id();
if (proto.has_sharding()) {
TF_ASSIGN_OR_RETURN(const auto& sharding,
HloSharding::FromProto(proto.sharding()));
instruction->set_sharding(sharding);
}
return std::move(instruction);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateParameter(
int64 parameter_number, const Shape& shape, const string& name) {
return absl::make_unique<HloParameterInstruction>(parameter_number, shape,
name);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTrace(
const string& tag, HloInstruction* operand) {
return absl::make_unique<HloTraceInstruction>(tag, operand);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConstant(
Literal literal) {
return absl::make_unique<HloConstantInstruction>(std::move(literal));
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateIota(
const Shape& shape, int64 iota_dimension) {
return absl::make_unique<HloIotaInstruction>(shape, iota_dimension);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateGetTupleElement(const Shape& shape,
HloInstruction* operand, int64 index) {
return absl::make_unique<HloGetTupleElementInstruction>(shape, operand,
index);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateRng(
const Shape& shape, RandomDistribution distribution,
absl::Span<HloInstruction* const> parameters) {
return absl::make_unique<HloRngInstruction>(shape, distribution, parameters);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateRngGetAndUpdateState(const Shape& shape, int64 delta) {
return absl::make_unique<HloRngGetAndUpdateStateInstruction>(shape, delta);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateNary(
const Shape& shape, HloOpcode opcode,
absl::Span<HloInstruction* const> operands) {
if (opcode == HloOpcode::kCopy) {
// It is impossible to copy an opaque shape, we don't know how big it is.
CHECK(!shape.IsOpaque());
}
auto instruction = absl::WrapUnique(new HloInstruction(opcode, shape));
for (auto operand : operands) {
instruction->AppendOperand(operand);
}
return instruction;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateUnary(
const Shape& shape, HloOpcode opcode, HloInstruction* operand) {
// Only certain opcodes are supported with CreateUnary: opcodes of unary
// instructions with no auxiliary fields.
switch (opcode) {
case HloOpcode::kAbs:
case HloOpcode::kRoundNearestAfz:
case HloOpcode::kBitcast:
case HloOpcode::kCeil:
case HloOpcode::kCopy:
case HloOpcode::kCopyStart:
case HloOpcode::kCopyDone:
case HloOpcode::kCos:
case HloOpcode::kClz:
case HloOpcode::kExp:
case HloOpcode::kExpm1:
case HloOpcode::kFloor:
case HloOpcode::kImag:
case HloOpcode::kIsFinite:
case HloOpcode::kLog:
case HloOpcode::kLog1p:
case HloOpcode::kNot:
case HloOpcode::kNegate:
case HloOpcode::kPopulationCount:
case HloOpcode::kReal:
case HloOpcode::kRsqrt:
case HloOpcode::kSign:
case HloOpcode::kSin:
case HloOpcode::kSqrt:
case HloOpcode::kTanh:
break;
default:
LOG(FATAL) << "Invalid unary instruction opcode "
<< HloOpcodeString(opcode);
}
return CreateNary(shape, opcode, {operand});
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBinary(
const Shape& shape, HloOpcode opcode, HloInstruction* lhs,
HloInstruction* rhs) {
// Only certain opcodes are supported with CreateBinary: opcodes of binary
// instructions with no auxiliary fields.
switch (opcode) {
case HloOpcode::kAdd:
case HloOpcode::kAtan2:
case HloOpcode::kDivide:
case HloOpcode::kComplex:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kMultiply:
case HloOpcode::kPower:
case HloOpcode::kRemainder:
case HloOpcode::kSubtract:
case HloOpcode::kAnd:
case HloOpcode::kOr:
case HloOpcode::kXor:
case HloOpcode::kShiftLeft:
case HloOpcode::kShiftRightArithmetic:
case HloOpcode::kShiftRightLogical:
break;
default:
LOG(FATAL) << "Invalid binary instruction opcode "
<< HloOpcodeString(opcode);
}
return CreateNary(shape, opcode, {lhs, rhs});
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTernary(
const Shape& shape, HloOpcode opcode, HloInstruction* lhs,
HloInstruction* rhs, HloInstruction* ehs) {
// Only certain opcodes are supported with CreateTernary: opcodes of ternary
// instructions with no auxiliary fields.
switch (opcode) {
case HloOpcode::kClamp:
case HloOpcode::kSelect:
case HloOpcode::kTupleSelect:
break;
default:
LOG(FATAL) << "Invalid ternary instruction opcode "
<< HloOpcodeString(opcode);
}
return CreateNary(shape, opcode, {lhs, rhs, ehs});
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateVariadic(
const Shape& shape, HloOpcode opcode,
absl::Span<HloInstruction* const> operands) {
CHECK_EQ(HloOpcode::kTuple, opcode);
return CreateNary(shape, opcode, operands);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateMap(
const Shape& shape, absl::Span<HloInstruction* const> operands,
HloComputation* map_computation) {
return absl::make_unique<HloMapInstruction>(shape, operands, map_computation);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConvolve(
const Shape& shape, HloInstruction* lhs, HloInstruction* rhs,
int64 feature_group_count, int64 batch_group_count, const Window& window,
const ConvolutionDimensionNumbers& dimension_numbers,
const PrecisionConfig& precision_config) {
return absl::make_unique<HloConvolutionInstruction>(
shape, lhs, rhs, feature_group_count, batch_group_count, window,
dimension_numbers, precision_config);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateFft(
const Shape& shape, HloInstruction* operand, FftType fft_type,
absl::Span<const int64> fft_length) {
return absl::make_unique<HloFftInstruction>(shape, operand, fft_type,
fft_length);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCompare(
const Shape& shape, HloInstruction* lhs, HloInstruction* rhs,
ComparisonDirection direction) {
return absl::make_unique<HloCompareInstruction>(shape, lhs, rhs, direction);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateTriangularSolve(const Shape& shape, HloInstruction* a,
HloInstruction* b,
const TriangularSolveOptions& options) {
return absl::make_unique<HloTriangularSolveInstruction>(shape, a, b, options);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCholesky(
const Shape& shape, HloInstruction* a, const CholeskyOptions& options) {
return absl::make_unique<HloCholeskyInstruction>(shape, a, options);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateDot(
const Shape& shape, HloInstruction* lhs, HloInstruction* rhs,
const DotDimensionNumbers& dimension_numbers,
const PrecisionConfig& precision_config) {
return absl::make_unique<HloDotInstruction>(
shape, lhs, rhs, dimension_numbers, precision_config);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateReducePrecision(const Shape& shape,
HloInstruction* operand,
const int exponent_bits,
const int mantissa_bits) {
return absl::make_unique<HloReducePrecisionInstruction>(
shape, operand, exponent_bits, mantissa_bits);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateAllReduce(
const Shape& shape, absl::Span<HloInstruction* const> operands,
HloComputation* reduce_computation,
const std::vector<ReplicaGroup>& replica_groups,
const absl::optional<int64>& channel_id) {
return absl::make_unique<HloAllReduceInstruction>(
shape, operands, reduce_computation, replica_groups, channel_id);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateAllToAll(
const Shape& shape, absl::Span<HloInstruction* const> operands,
const std::vector<ReplicaGroup>& replica_groups) {
return absl::make_unique<HloAllToAllInstruction>(shape, operands,
replica_groups);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateCollectivePermute(
const Shape& shape, HloInstruction* operand,
const std::vector<std::pair<int64, int64>>& source_target_pairs,
const absl::optional<int64>& channel_id) {
return absl::make_unique<HloCollectivePermuteInstruction>(
shape, operand, source_target_pairs, channel_id);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReplicaId() {
return absl::WrapUnique(
new HloInstruction(HloOpcode::kReplicaId, ShapeUtil::MakeShape(U32, {})));
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreatePartitionId() {
return absl::WrapUnique(new HloInstruction(HloOpcode::kPartitionId,
ShapeUtil::MakeShape(U32, {})));
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateInfeed(
const Shape& infeed_shape, HloInstruction* token_operand,
const string& config) {
return absl::make_unique<HloInfeedInstruction>(infeed_shape, token_operand,
config);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateOutfeed(
const Shape& outfeed_shape, HloInstruction* operand,
HloInstruction* token_operand, absl::string_view outfeed_config) {
return absl::make_unique<HloOutfeedInstruction>(
outfeed_shape, operand, token_operand, outfeed_config);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSend(
HloInstruction* operand, HloInstruction* token, int64 channel_id,
bool is_host_transfer) {
return absl::make_unique<HloSendInstruction>(operand, token, channel_id,
is_host_transfer);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSendDone(
HloInstruction* operand, bool is_host_transfer) {
auto send_operand = DynCast<HloSendInstruction>(operand);
CHECK(send_operand != nullptr)
<< "SendDone must take the context operand from Send";
return absl::make_unique<HloSendDoneInstruction>(send_operand,
is_host_transfer);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateRecv(
const Shape& shape, HloInstruction* token, int64 channel_id,
bool is_host_transfer) {
return absl::make_unique<HloRecvInstruction>(shape, token, channel_id,
is_host_transfer);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateRecvDone(
HloInstruction* operand, bool is_host_transfer) {
auto recv_operand = DynCast<HloRecvInstruction>(operand);
CHECK(recv_operand != nullptr)
<< "RecvDone must take the context operand from Recv";
return absl::make_unique<HloRecvDoneInstruction>(recv_operand,
is_host_transfer);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReverse(
const Shape& shape, HloInstruction* operand,
absl::Span<const int64> dimensions) {
return absl::make_unique<HloReverseInstruction>(shape, operand, dimensions);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateAfterAll(
absl::Span<HloInstruction* const> operands) {
CHECK(!operands.empty());
auto instruction = absl::WrapUnique(
new HloInstruction(HloOpcode::kAfterAll, ShapeUtil::MakeTokenShape()));
for (auto operand : operands) {
instruction->AppendOperand(operand);
}
return instruction;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateToken() {
return absl::WrapUnique(
new HloInstruction(HloOpcode::kAfterAll, ShapeUtil::MakeTokenShape()));
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateAddDependency(HloInstruction* data_operand,
HloInstruction* token_operand) {
auto instruction = absl::WrapUnique(
new HloInstruction(HloOpcode::kAddDependency, data_operand->shape()));
instruction->AppendOperand(data_operand);
instruction->AppendOperand(token_operand);
return instruction;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateWhile(
const Shape& shape, HloComputation* condition, HloComputation* body,
HloInstruction* init) {
auto instruction =
absl::WrapUnique(new HloInstruction(HloOpcode::kWhile, shape));
instruction->AppendOperand(init);
// Body comes before condition computation in the vector.
instruction->called_computations_.push_back(body);
instruction->called_computations_.push_back(condition);
return instruction;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConditional(
const Shape& shape, HloInstruction* pred,
HloInstruction* true_computation_arg, HloComputation* true_computation,
HloInstruction* false_computation_arg, HloComputation* false_computation) {
auto instruction =
absl::WrapUnique(new HloInstruction(HloOpcode::kConditional, shape));
instruction->AppendOperand(pred);
instruction->AppendOperand(true_computation_arg);
instruction->AppendOperand(false_computation_arg);
// In called_computations_, the index of true_computation must be 0 and that
// of false computation must be 1, as defined by kTrueComputationIndex and
// kFalseComputationIndex.
instruction->called_computations_.push_back(true_computation);
instruction->called_computations_.push_back(false_computation);
return instruction;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConditional(
const Shape& shape, HloInstruction* branch_index,
absl::Span<HloComputation* const> branch_computations,
absl::Span<HloInstruction* const> branch_computation_args) {
auto instruction =
absl::WrapUnique(new HloInstruction(HloOpcode::kConditional, shape));
instruction->AppendOperand(branch_index);
CHECK_EQ(branch_computations.size(), branch_computation_args.size());
for (int i = 0; i < branch_computations.size(); ++i) {
instruction->called_computations_.push_back(branch_computations[i]);
instruction->AppendOperand(branch_computation_args[i]);
}
return instruction;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSlice(
const Shape& shape, HloInstruction* operand,
absl::Span<const int64> start_indices,
absl::Span<const int64> limit_indices, absl::Span<const int64> strides) {
return absl::make_unique<HloSliceInstruction>(shape, operand, start_indices,
limit_indices, strides);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateDynamicSlice(
const Shape& shape, HloInstruction* operand,
absl::Span<HloInstruction* const> start_indices,
absl::Span<const int64> slice_sizes) {
return absl::make_unique<HloDynamicSliceInstruction>(
shape, operand, start_indices, slice_sizes);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateDynamicUpdateSlice(
const Shape& shape, HloInstruction* operand, HloInstruction* update,
absl::Span<HloInstruction* const> start_indices) {
return absl::make_unique<HloDynamicUpdateSliceInstruction>(
shape, operand, update, start_indices);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConcatenate(
const Shape& shape, absl::Span<HloInstruction* const> operands,
int64 dimension) {
return absl::make_unique<HloConcatenateInstruction>(shape, operands,
dimension);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateConvert(
const Shape& shape, HloInstruction* operand) {
auto instruction =
absl::WrapUnique(new HloInstruction(HloOpcode::kConvert, shape));
instruction->AppendOperand(operand);
return instruction;
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateBitcastConvert(const Shape& shape,
HloInstruction* operand) {
auto instruction =
absl::WrapUnique(new HloInstruction(HloOpcode::kBitcastConvert, shape));
instruction->AppendOperand(operand);
return instruction;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBitcast(
const Shape& shape, HloInstruction* operand) {
auto instruction =
absl::WrapUnique(new HloInstruction(HloOpcode::kBitcast, shape));
instruction->AppendOperand(operand);
return instruction;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReduce(
const Shape& shape, HloInstruction* operand, HloInstruction* init_value,
absl::Span<const int64> dimensions_to_reduce,
HloComputation* reduce_computation) {
auto instruction = absl::WrapUnique(new HloReduceInstruction(
shape, {operand, init_value}, dimensions_to_reduce, reduce_computation));
return std::move(instruction);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReduce(
const Shape& shape, absl::Span<HloInstruction* const> operands,
absl::Span<HloInstruction* const> init_values,
absl::Span<const int64> dimensions_to_reduce,
HloComputation* reduce_computation) {
std::vector<HloInstruction*> all_args;
all_args.reserve(operands.size() * 2);
all_args.insert(all_args.end(), operands.begin(), operands.end());
all_args.insert(all_args.end(), init_values.begin(), init_values.end());
return absl::make_unique<HloReduceInstruction>(
shape, all_args, dimensions_to_reduce, reduce_computation);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReduceWindow(
const Shape& shape, HloInstruction* operand, HloInstruction* init_value,
const Window& window, HloComputation* reduce_computation) {
return absl::make_unique<HloReduceWindowInstruction>(
shape, operand, init_value, window, reduce_computation);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateBatchNormTraining(const Shape& shape,
HloInstruction* operand,
HloInstruction* scale,
HloInstruction* offset, float epsilon,
int64 feature_index) {
return absl::make_unique<HloBatchNormTrainingInstruction>(
shape, operand, scale, offset, epsilon, feature_index);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateBatchNormInference(
const Shape& shape, HloInstruction* operand, HloInstruction* scale,
HloInstruction* offset, HloInstruction* mean, HloInstruction* variance,
float epsilon, int64 feature_index) {
return absl::make_unique<HloBatchNormInferenceInstruction>(
shape, operand, scale, offset, mean, variance, epsilon, feature_index);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateBatchNormGrad(const Shape& shape, HloInstruction* operand,
HloInstruction* scale, HloInstruction* mean,
HloInstruction* variance,
HloInstruction* grad_output, float epsilon,
int64 feature_index) {
return absl::make_unique<HloBatchNormGradInstruction>(
shape, operand, scale, mean, variance, grad_output, epsilon,
feature_index);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateSelectAndScatter(
const Shape& shape, HloInstruction* operand, HloComputation* select,
const Window& window, HloInstruction* source, HloInstruction* init_value,
HloComputation* scatter) {
return absl::make_unique<HloSelectAndScatterInstruction>(
shape, operand, select, window, source, init_value, scatter);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateBroadcast(
const Shape& shape, HloInstruction* operand,
absl::Span<const int64> broadcast_dimensions) {
return absl::make_unique<HloBroadcastInstruction>(shape, operand,
broadcast_dimensions);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateGetDimensionSize(const Shape& shape,
HloInstruction* operand,
int64 dimension) {
return absl::make_unique<HloGetDimensionSizeInstruction>(shape, operand,
dimension);
}
/* static */ std::unique_ptr<HloInstruction>
HloInstruction::CreateBroadcastSequence(
const Shape& output_shape, HloInstruction* operand,
const std::function<HloInstruction*(std::unique_ptr<HloInstruction>)>&
adder) {
CHECK(ShapeUtil::IsScalar(operand->shape()) ||
operand->shape().rank() == output_shape.rank());
Shape broadcast_shape = ShapeUtil::ChangeElementType(
output_shape, operand->shape().element_type());
// Do explicit broadcast for scalar.
if (ShapeUtil::IsScalar(operand->shape())) {
auto broadcast =
HloInstruction::CreateBroadcast(broadcast_shape, operand, {});
broadcast->set_metadata(operand->metadata());
if (operand->has_sharding()) {
broadcast->set_sharding(operand->sharding());
}
return broadcast;
}
// Do explicit broadcast for degenerate broadcast.
std::vector<int64> broadcast_dimensions;
std::vector<int64> reshaped_dimensions;
for (int i = 0; i < operand->shape().rank(); i++) {
if (operand->shape().dimensions(i) == output_shape.dimensions(i)) {
broadcast_dimensions.push_back(i);
reshaped_dimensions.push_back(operand->shape().dimensions(i));
} else {
CHECK_EQ(operand->shape().dimensions(i), 1)
<< "An explicit broadcast sequence requires the broadcasted "
"dimensions to be trivial; operand: "
<< operand->ToString() << "; output_shape: " << output_shape;
}
}
// Eliminate the size one dimensions.
HloInstruction* reshaped_operand = adder(HloInstruction::CreateReshape(
ShapeUtil::MakeShape(operand->shape().element_type(),
reshaped_dimensions),
operand));
reshaped_operand->set_metadata(operand->metadata());
if (operand->has_sharding()) {
reshaped_operand->set_sharding(operand->sharding());
}
// Broadcast 'reshape' up to the larger size.
auto broadcast = HloInstruction::CreateBroadcast(
broadcast_shape, reshaped_operand, broadcast_dimensions);
broadcast->set_metadata(operand->metadata());
if (operand->has_sharding()) {
broadcast->set_sharding(operand->sharding());
}
return broadcast;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreatePad(
const Shape& shape, HloInstruction* operand, HloInstruction* padding_value,
const PaddingConfig& padding_config) {
return absl::make_unique<HloPadInstruction>(shape, operand, padding_value,
padding_config);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateReshape(
const Shape& shape, HloInstruction* operand, int64 inferred_dimension) {
CHECK_EQ(ShapeUtil::ElementsIn(shape),
ShapeUtil::ElementsIn(operand->shape()))
<< "shape: " << ShapeUtil::HumanString(shape)
<< " operand: " << ShapeUtil::HumanString(operand->shape());
return absl::make_unique<HloReshapeInstruction>(shape, operand,
inferred_dimension);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTranspose(
const Shape& shape, HloInstruction* operand,
absl::Span<const int64> dimensions) {
return absl::make_unique<HloTransposeInstruction>(shape, operand, dimensions);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateSort(
const Shape& shape, int64 dimension,
absl::Span<HloInstruction* const> operands, HloComputation* compare,
bool is_stable) {
return absl::make_unique<HloSortInstruction>(shape, dimension, operands,
compare, is_stable);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateFusion(
const Shape& shape, FusionKind fusion_kind, HloInstruction* fused_root) {
return absl::make_unique<HloFusionInstruction>(shape, fusion_kind,
fused_root);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateFusion(
const Shape& shape, FusionKind fusion_kind,
absl::Span<HloInstruction* const> operands,
HloComputation* fusion_computation) {
return absl::make_unique<HloFusionInstruction>(shape, fusion_kind, operands,
fusion_computation);
}
void HloInstruction::set_single_sharding(const HloSharding& sharding) {
CHECK(!sharding.IsTuple()) << sharding;
if (shape().IsTuple()) {
set_sharding(HloSharding::Tuple(sharding.GetAsShapeTree(shape())));
} else {
set_sharding(sharding);
}
}
void HloInstruction::SetupDerivedInstruction(
HloInstruction* derived_instruction) const {
if (sharding_ != nullptr && ShapeUtil::CompatibleIgnoringElementType(
shape_, derived_instruction->shape())) {
// Only copy sharding if the shape of the two instruction is compatible
// because copying it between differently shaped instructions can produce
// invalid shardings.
derived_instruction->set_sharding(*sharding_);
} else {
derived_instruction->clear_sharding();
}
derived_instruction->set_metadata(metadata_);
}
bool HloInstruction::HasSideEffectNoRecurse() const {
switch (opcode_) {
case HloOpcode::kSend:
case HloOpcode::kSendDone:
case HloOpcode::kRecv:
case HloOpcode::kRecvDone:
case HloOpcode::kRng:
case HloOpcode::kRngGetAndUpdateState:
case HloOpcode::kInfeed:
case HloOpcode::kOutfeed:
case HloOpcode::kTrace:
return true;
case HloOpcode::kAllReduce:
return channel_id().has_value();
case HloOpcode::kCustomCall:
return Cast<HloCustomCallInstruction>(this)
->custom_call_has_side_effect();
default:
return false;
}
}
bool HloInstruction::HasSideEffect() const {
if (HasSideEffectNoRecurse()) {
return true;
}
// Check if any of the called computations has a side effect.
for (const auto& computation : called_computations()) {
if (computation->HasSideEffect()) {
return true;
}
}
return false;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCall(
const Shape& shape, absl::Span<HloInstruction* const> operands,
HloComputation* computation) {
std::unique_ptr<HloInstruction> instruction =
absl::WrapUnique(new HloInstruction(HloOpcode::kCall, shape));
for (auto operand : operands) {
instruction->AppendOperand(operand);
}
instruction->called_computations_.push_back(computation);
return instruction;
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCustomCall(
const Shape& shape, absl::Span<HloInstruction* const> operands,
absl::string_view custom_call_target, string opaque) {
return absl::make_unique<HloCustomCallInstruction>(
shape, operands, custom_call_target, std::move(opaque));
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateCustomCall(
const Shape& shape, absl::Span<HloInstruction* const> operands,
absl::string_view custom_call_target,
absl::Span<const Shape> operand_shapes_with_layout, string opaque) {
return absl::make_unique<HloCustomCallInstruction>(
shape, operands, custom_call_target, std::move(opaque),
operand_shapes_with_layout);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateTuple(
absl::Span<HloInstruction* const> elements) {
std::vector<Shape> element_shapes;
for (auto element : elements) {
element_shapes.push_back(element->shape());
}
Shape tuple_shape = ShapeUtil::MakeTupleShape(element_shapes);
return CreateVariadic(tuple_shape, HloOpcode::kTuple, elements);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateGather(
const Shape& shape, HloInstruction* operand, HloInstruction* start_indices,
const GatherDimensionNumbers& gather_dim_numbers,
absl::Span<const int64> slice_sizes) {
return absl::make_unique<HloGatherInstruction>(
shape, operand, start_indices, gather_dim_numbers, slice_sizes);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateScatter(
const Shape& shape, HloInstruction* operand,
HloInstruction* scatter_indices, HloInstruction* updates,
HloComputation* update_computation,
const ScatterDimensionNumbers& scatter_dim_numbers) {
return absl::make_unique<HloScatterInstruction>(
shape, operand, scatter_indices, updates, update_computation,
scatter_dim_numbers);
}
/* static */ std::unique_ptr<HloInstruction> HloInstruction::CreateDomain(
const Shape& shape, HloInstruction* operand,
std::unique_ptr<DomainMetadata> operand_side_metadata,
std::unique_ptr<DomainMetadata> user_side_metadata) {
return absl::make_unique<HloDomainInstruction>(
shape, operand, std::move(operand_side_metadata),
std::move(user_side_metadata));
}
std::unique_ptr<HloInstruction> HloInstruction::CloneWithNewOperands(
const Shape& shape, absl::Span<HloInstruction* const> new_operands,
HloCloneContext* context) const {
VLOG(3) << "CloneWithNewOperands:\n " << ToString();
VLOG(3) << " new operands:";
for (const HloInstruction* new_operand : new_operands) {
VLOG(3) << " %" << new_operand->name();
}
std::unique_ptr<HloInstruction> clone;
// Explicitly call the factory for the instruction type. This is more robust
// in the face of code changes than copying fields explicitly. This also
// properly sets the user fields of the operands.
switch (opcode_) {
// Ops migrated to subclasses.
// TODO(b/80131774): Remove this switch when migration is complete.
case HloOpcode::kBatchNormTraining:
case HloOpcode::kBatchNormInference:
case HloOpcode::kBatchNormGrad:
case HloOpcode::kFft:
case HloOpcode::kCompare:
case HloOpcode::kSend:
case HloOpcode::kSendDone:
case HloOpcode::kRecv:
case HloOpcode::kRecvDone:
case HloOpcode::kReverse:
case HloOpcode::kConcatenate:
case HloOpcode::kReduce:
case HloOpcode::kTranspose:
case HloOpcode::kBroadcast:
case HloOpcode::kReshape:
case HloOpcode::kMap:
case HloOpcode::kSlice:
case HloOpcode::kConstant:
case HloOpcode::kTrace:
case HloOpcode::kFusion:
case HloOpcode::kRng:
case HloOpcode::kRngGetAndUpdateState:
case HloOpcode::kParameter:
case HloOpcode::kGetTupleElement:
case HloOpcode::kReducePrecision:
case HloOpcode::kAllReduce:
case HloOpcode::kAllToAll:
case HloOpcode::kCollectivePermute:
case HloOpcode::kInfeed:
case HloOpcode::kOutfeed:
case HloOpcode::kConvolution:
case HloOpcode::kCustomCall:
case HloOpcode::kReduceWindow:
case HloOpcode::kSelectAndScatter:
case HloOpcode::kPad:
case HloOpcode::kDynamicSlice:
case HloOpcode::kSort:
case HloOpcode::kGather:
case HloOpcode::kScatter:
case HloOpcode::kIota:
case HloOpcode::kDot:
case HloOpcode::kDomain:
case HloOpcode::kGetDimensionSize:
case HloOpcode::kTriangularSolve:
case HloOpcode::kCholesky:
clone = CloneWithNewOperandsImpl(shape, new_operands, context);
break;
// Unary ops.
case HloOpcode::kAbs:
case HloOpcode::kRoundNearestAfz:
case HloOpcode::kBitcast:
case HloOpcode::kCeil:
case HloOpcode::kClz:
case HloOpcode::kCopy:
case HloOpcode::kCopyStart:
case HloOpcode::kCopyDone:
case HloOpcode::kCos:
case HloOpcode::kExp:
case HloOpcode::kExpm1:
case HloOpcode::kImag:
case HloOpcode::kIsFinite:
case HloOpcode::kFloor:
case HloOpcode::kLog:
case HloOpcode::kLog1p:
case HloOpcode::kNot:
case HloOpcode::kNegate:
case HloOpcode::kPopulationCount:
case HloOpcode::kReal:
case HloOpcode::kRsqrt:
case HloOpcode::kSign:
case HloOpcode::kSin:
case HloOpcode::kSqrt:
case HloOpcode::kTanh:
CHECK_EQ(new_operands.size(), 1);
clone = CreateUnary(shape, opcode_, new_operands[0]);
break;
// Binary ops.
case HloOpcode::kAdd:
case HloOpcode::kAtan2:
case HloOpcode::kComplex:
case HloOpcode::kDivide:
case HloOpcode::kMultiply:
case HloOpcode::kSubtract:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kPower:
case HloOpcode::kRemainder:
case HloOpcode::kAnd:
case HloOpcode::kOr:
case HloOpcode::kXor:
case HloOpcode::kShiftLeft:
case HloOpcode::kShiftRightArithmetic:
case HloOpcode::kShiftRightLogical:
CHECK_EQ(new_operands.size(), 2);
clone = CreateBinary(shape, opcode_, new_operands[0], new_operands[1]);
break;
// Ternary ops.
case HloOpcode::kClamp:
case HloOpcode::kSelect:
case HloOpcode::kTupleSelect:
CHECK_EQ(new_operands.size(), 3);
clone = CreateTernary(shape, opcode_, new_operands[0], new_operands[1],
new_operands[2]);
break;
// Other supported ops.
case HloOpcode::kCall:
clone = CreateCall(shape, new_operands, to_apply());
break;
case HloOpcode::kConvert:
CHECK_EQ(new_operands.size(), 1);
clone = CreateConvert(shape, new_operands[0]);
break;
case HloOpcode::kBitcastConvert:
CHECK_EQ(new_operands.size(), 1);
clone = CreateBitcastConvert(shape, new_operands[0]);
break;
case HloOpcode::kDynamicUpdateSlice:
clone = CreateDynamicUpdateSlice(shape, new_operands[0], new_operands[1],
new_operands.subspan(2));
break;
case HloOpcode::kTuple:
clone = CreateTuple(new_operands);
*clone->mutable_shape() = shape;
break;
case HloOpcode::kWhile:
CHECK_EQ(new_operands.size(), 1);
clone =
CreateWhile(shape, while_condition(), while_body(), new_operands[0]);
break;
case HloOpcode::kConditional:
CHECK_EQ(new_operands.size(), branch_count() + 1);
clone = CreateConditional(shape, new_operands[0],
absl::MakeSpan(branch_computations()),
new_operands.subspan(1));
break;
case HloOpcode::kAfterAll:
if (new_operands.empty()) {
clone = CreateToken();
} else {
clone = CreateAfterAll(new_operands);
}
break;
case HloOpcode::kAddDependency:
CHECK_EQ(new_operands.size(), 2);
clone = CreateAddDependency(new_operands[0], new_operands[1]);
break;
case HloOpcode::kReplicaId:
CHECK_EQ(new_operands.size(), 0);
clone = CreateReplicaId();
break;
case HloOpcode::kPartitionId:
CHECK_EQ(new_operands.size(), 0);
clone = CreatePartitionId();
break;
}
// SetupDerivedInstruction will setup the precision_config_ field.
SetupDerivedInstruction(clone.get());
clone->set_parent(parent_);
clone->set_outer_dimension_partitions(outer_dimension_partitions_);
clone->set_raw_backend_config_string(backend_config_);
if (context != nullptr) {
context->MapInstruction(this, clone.get());
clone->ReplaceCalledComputations([&](HloComputation* callee) {
return callee->parent() != context->module()
? context->module()->DeepCloneComputation(callee, context)
: callee;
});
}
return clone;
}
HloInstruction::~HloInstruction() {
// Detach from operands. An instruction may be repeated as an operand. To
// avoid calling RemoveUser twice on the same operand, check before remove.
for (int64 operand_num = 0; operand_num < operand_count(); ++operand_num) {
HloInstruction* operand = operands_[operand_num];
if (operand == nullptr) {
continue;
}
if (operand->user_set_.find(this) != operand->user_set_.end()) {
operand->RemoveUser(this);
}
operands_[operand_num] = nullptr;
}
// Update users. Set `nullptr` to the correpsonding operand slot for users.
for (auto& user : this->users()) {
for (int i = 0; i < user->operand_count(); ++i) {
if (user->operands_[i] == this) {
user->operands_[i] = nullptr;
}
}
}
}
std::unique_ptr<HloInstruction> HloInstruction::Clone(
const string& suffix, HloCloneContext* context) const {
std::unique_ptr<HloInstruction> clone =
CloneWithNewOperands(shape_, operands_, context);
if (suffix.empty()) {
clone->name_ = name();
} else {
// If an instruction is cloned multiple times avoid names like
// foo.suffix.suffix.suffix. Instead of repeating the suffix add a numeric
// suffix. Specifically, the clone of foo.suffix is named foo.suffix2, the
// clone of foo.suffix2 is named foo.suffix3 and so on.
const string dot_suffix = "." + suffix;
size_t index = name().rfind(dot_suffix);
if (index == string::npos) {
// Existing name does not include ".suffix".
clone->name_ = name() + dot_suffix;
} else {
// Existing name includes ".suffix". Determine if substring after
// ".suffix" is numeric and should be replaced with an incremented number.
string after_suffix = name().substr(index + dot_suffix.size());
if (after_suffix.empty()) {
// Existing name ends in ".suffix". New name should end in ".suffix2".
clone->name_ = name() + "2";
} else {
// If names ends with .suffix[0-9]+ then replace with a suffix with the
// numeric value incremented.
int64 numeric_suffix;
if (absl::SimpleAtoi(after_suffix, &numeric_suffix)) {
clone->name_ =
StrCat(name().substr(0, index), dot_suffix, numeric_suffix + 1);
} else {
// Substring after ".suffix" is non-numeric.
clone->name_ = name() + dot_suffix;
}
}
}
}
return clone;
}
std::pair<const HloInstruction*, ShapeIndex>
HloInstruction::LatestNonGteAncestorAndIndex() const {
const HloInstruction* hlo = this;
ShapeIndex index;
while (hlo->opcode() == HloOpcode::kGetTupleElement) {
index.push_back(hlo->tuple_index());
hlo = hlo->operand(0);
}
// We built up index in the reverse order from what we want.
std::reverse(index.begin(), index.end());
return {hlo, index};
}
const HloInstruction* HloInstruction::LatestNonGteAncestor() const {
const HloInstruction* hlo = this;
while (hlo->opcode() == HloOpcode::kGetTupleElement) {
hlo = hlo->operand(0);
}
return hlo;
}
const HloInstruction* HloInstruction::operand(int64 i) const {
return operands_.at(i);
}
HloInstruction* HloInstruction::mutable_operand(int64 i) {
CHECK(operands_[i] != nullptr);
return operands_.at(i);
}
int64 HloInstruction::operand_index(const HloInstruction* target) const {
for (int64 i = 0; i < operand_count(); ++i) {
if (target == operand(i)) {
return i;
}
}
LOG(FATAL) << "target was not an operand: " << target->ToString();
}
HloInstruction::InstructionVector HloInstruction::unique_operands() const {
InstructionVector unique;
absl::flat_hash_set<const HloInstruction*> seen;
for (HloInstruction* operand : operands()) {
if (seen.insert(operand).second) {
unique.push_back(operand);
}
}
return unique;
}
Status HloInstruction::AddControlDependencyTo(HloInstruction* instruction) {
TF_RET_CHECK(instruction->parent() == parent());
if (!absl::c_linear_search(control_successors_, instruction)) {
control_successors_.push_back(instruction);
TF_RET_CHECK(
!absl::c_linear_search(instruction->control_predecessors_, this));
instruction->control_predecessors_.push_back(this);
}
return Status::OK();
}
Status HloInstruction::RemoveControlDependencyTo(HloInstruction* instruction) {
TF_RET_CHECK(instruction->parent() == parent());
TF_RETURN_IF_ERROR(EraseElementFromVector(&control_successors_, instruction));
TF_RETURN_IF_ERROR(
EraseElementFromVector(&instruction->control_predecessors_, this));
return Status::OK();
}
Status HloInstruction::DropAllControlDeps() {
for (auto* ctrl_succ : control_successors_) {
TF_RETURN_IF_ERROR(
EraseElementFromVector(&ctrl_succ->control_predecessors_, this));
}
for (auto* ctrl_pred : control_predecessors_) {
TF_RETURN_IF_ERROR(
EraseElementFromVector(&ctrl_pred->control_successors_, this));
}
control_successors_.clear();
control_predecessors_.clear();
return Status::OK();
}
Status HloInstruction::CopyAllControlDepsFrom(const HloInstruction* inst) {
for (auto* ctrl_pred : inst->control_predecessors()) {
TF_RETURN_IF_ERROR(ctrl_pred->AddControlDependencyTo(this));
}
for (auto* ctrl_succ : inst->control_successors()) {
TF_RETURN_IF_ERROR(this->AddControlDependencyTo(ctrl_succ));
}
return Status::OK();
}
void HloInstruction::AppendOperand(HloInstruction* operand) {
operands_.push_back(operand);
operand->AddUser(this);
}
void HloInstruction::RemoveOperandsAtAscendingIndices(
absl::Span<const int> ascending_indices) {
if (ascending_indices.empty()) {
return;
}
int next_index = 0;
int removed_count = 0;
for (int to_remove : ascending_indices) {
while (next_index < to_remove) {
operands_[next_index - removed_count] = operands_[next_index];
++next_index;
}
CHECK_LT(to_remove, operands_.size());
++removed_count;
++next_index;
}
while (next_index < operands_.size()) {
operands_[next_index - removed_count] = operands_[next_index];
++next_index;
}
CHECK_EQ(removed_count, ascending_indices.size());
operands_.resize(operands_.size() - removed_count);
}
void HloInstruction::AddUser(HloInstruction* user) {
if (!ContainsKey(user_set_, user)) {
user_set_.insert(user);
users_.push_back(user);
}
}
bool HloInstruction::HasConstantOperand() const {
for (const HloInstruction* operand : operands_) {
if (operand->IsConstant()) {
return true;
}
}
return false;
}
bool HloInstruction::IdenticalSlowPath(
const HloInstruction& other,
const std::function<bool(const HloComputation*, const HloComputation*)>&
eq_computations) const {
// Perform opcode specific checks.
switch (opcode()) {
// The result of these instructions only depend upon their opcode and
// operands.
case HloOpcode::kAbs:
case HloOpcode::kAtan2:
case HloOpcode::kAdd:
case HloOpcode::kBitcast:
case HloOpcode::kBitcastConvert:
case HloOpcode::kCeil:
case HloOpcode::kClamp:
case HloOpcode::kClz:
case HloOpcode::kComplex:
case HloOpcode::kConvert:
case HloOpcode::kCopy:
case HloOpcode::kCopyStart:
case HloOpcode::kCopyDone:
case HloOpcode::kCos:
case HloOpcode::kDivide:
case HloOpcode::kDynamicUpdateSlice:
case HloOpcode::kExp:
case HloOpcode::kExpm1:
case HloOpcode::kFloor:
case HloOpcode::kImag:
case HloOpcode::kIsFinite:
case HloOpcode::kLog:
case HloOpcode::kLog1p:
case HloOpcode::kAnd:
case HloOpcode::kNot:
case HloOpcode::kOr:
case HloOpcode::kXor:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kMultiply:
case HloOpcode::kNegate:
case HloOpcode::kPartitionId:
case HloOpcode::kPopulationCount:
case HloOpcode::kPower:
case HloOpcode::kReal:
case HloOpcode::kRemainder:
case HloOpcode::kReshape:
case HloOpcode::kReplicaId:
case HloOpcode::kRoundNearestAfz:
case HloOpcode::kRsqrt:
case HloOpcode::kSelect:
case HloOpcode::kShiftLeft:
case HloOpcode::kShiftRightArithmetic:
case HloOpcode::kShiftRightLogical:
case HloOpcode::kSign:
case HloOpcode::kSin:
case HloOpcode::kSqrt:
case HloOpcode::kSubtract:
case HloOpcode::kTanh:
case HloOpcode::kTuple:
case HloOpcode::kTupleSelect:
return true;
// This opcode has complex or special behavior so just return false.
case HloOpcode::kAfterAll:
case HloOpcode::kAddDependency:
return false;
// Remaining instructions with special values.
case HloOpcode::kCall:
return eq_computations(to_apply(), other.to_apply());
case HloOpcode::kConditional:
for (int j = 0; j < branch_count(); ++j) {
if (!eq_computations(branch_computation(j),
other.branch_computation(j))) {
return false;
}
}
return true;
case HloOpcode::kWhile:
return (eq_computations(while_body(), other.while_body()) &&
eq_computations(while_condition(), other.while_condition()));
// Ops migrated to subclasses should never come to this line.
// TODO(b/80131774): Remove this switch when migration is complete.
case HloOpcode::kBatchNormTraining:
case HloOpcode::kBatchNormInference:
case HloOpcode::kBatchNormGrad:
case HloOpcode::kFft:
case HloOpcode::kCompare:
case HloOpcode::kSend:
case HloOpcode::kSendDone:
case HloOpcode::kRecv:
case HloOpcode::kRecvDone:
case HloOpcode::kReverse:
case HloOpcode::kConcatenate:
case HloOpcode::kReduce:
case HloOpcode::kSort:
case HloOpcode::kTranspose:
case HloOpcode::kBroadcast:
case HloOpcode::kMap:
case HloOpcode::kSlice:
case HloOpcode::kConstant:
case HloOpcode::kIota:
case HloOpcode::kTrace:
case HloOpcode::kFusion:
case HloOpcode::kRng:
case HloOpcode::kRngGetAndUpdateState:
case HloOpcode::kParameter:
case HloOpcode::kGetTupleElement:
case HloOpcode::kReducePrecision:
case HloOpcode::kInfeed:
case HloOpcode::kOutfeed:
case HloOpcode::kAllReduce:
case HloOpcode::kAllToAll:
case HloOpcode::kCollectivePermute:
case HloOpcode::kConvolution:
case HloOpcode::kCustomCall:
case HloOpcode::kReduceWindow:
case HloOpcode::kSelectAndScatter:
case HloOpcode::kPad:
case HloOpcode::kDynamicSlice:
case HloOpcode::kGather:
case HloOpcode::kScatter:
case HloOpcode::kDot:
case HloOpcode::kDomain:
case HloOpcode::kGetDimensionSize:
case HloOpcode::kTriangularSolve:
case HloOpcode::kCholesky:
LOG(FATAL) << "Base class impl called for opcode with subclass: "
<< opcode();
}
return false;
}
static uint64 HashOperand(const HloInstruction* hlo) {
return ShapeUtil::Hash(hlo->shape());
}
uint64 HloInstruction::Hash(
const std::function<uint64(const HloInstruction*)>& hash_operand) const {
using tensorflow::Hash64Combine;
uint64 hash_value = Hash64Combine(0, static_cast<uint64>(opcode()));
hash_value = Hash64Combine(hash_value, ShapeUtil::Hash(shape()));
if (!IsCrossModuleAllReduce()) {
if (!operands().empty()) {
for (size_t i = 0; i < operands().size(); ++i) {
hash_value = Hash64Combine(hash_value, hash_operand(operand(i)));
}
}
}
hash_value = Hash64Combine(hash_value, InnerHash());
return hash_value;
}
uint64 HloInstruction::Hash() const {
// Use HashOperand as an argument to prevent non-termination.
return Hash(HashOperand);
}
uint64 HloInstruction::InnerHash() const { return 13; }
void HloInstruction::RemoveUser(HloInstruction* user) {
auto set_it = user_set_.find(user);
CHECK(set_it != user_set_.end());
user_set_.erase(set_it);
// This is linear in the number of the users, but a vector provides a stable
// iteration order and much faster traversal.
auto vec_it = absl::c_find(users_, user);
CHECK(vec_it != users_.end());
users_.erase(vec_it);
}
Status HloInstruction::ReplaceUseWith(HloInstruction* user,
HloInstruction* new_producer) {
TF_RET_CHECK(
ShapeUtil::CompatibleIgnoringFpPrecision(shape(), new_producer->shape()))
<< "this shape: " << ShapeUtil::HumanString(shape())
<< ", replacement shape: "
<< ShapeUtil::HumanString(new_producer->shape());
return ReplaceUseWithDifferentShape(user, new_producer);
}
Status HloInstruction::ReplaceUseWithDifferentShape(
HloInstruction* user, HloInstruction* new_producer) {
VLOG(3) << "Replacing uses of " << name() << " in " << user->name()
<< " with " << new_producer->name();
RemoveUser(user);
TF_RET_CHECK(absl::c_count(user->operands_, this) >= 0);
std::replace(user->operands_.begin(), user->operands_.end(), this,
new_producer);
new_producer->AddUser(user);
// Custom fusions may not be able to handle deduplicated operands.
if (user->opcode() == HloOpcode::kFusion) {
TF_RETURN_IF_ERROR(
Cast<HloFusionInstruction>(user)->DeduplicateFusionOperands());
}
return Status::OK();
}
Status HloInstruction::ReplaceOperandWith(int64 operand_num,
HloInstruction* new_operand) {
auto old_operand = operand(operand_num);
TF_RET_CHECK(ShapeUtil::CompatibleIgnoringFpPrecision(old_operand->shape(),
new_operand->shape()))
<< old_operand->shape() << " is not compatible with "
<< new_operand->shape();
return ReplaceOperandWithDifferentShape(operand_num, new_operand);
}
Status HloInstruction::ReplaceOperandWithDifferentShape(
int64 operand_num, HloInstruction* new_operand) {
TF_RET_CHECK(operand_num >= 0);
TF_RET_CHECK(operand_num < operand_count());
HloInstruction* old_operand = mutable_operand(operand_num);
if (old_operand == new_operand) {
return Status::OK();
}
operands_[operand_num] = new_operand;
VLOG(3) << "Replacing operand " << operand_num << " of " << name() << " with "
<< new_operand->name() << ", was " << old_operand->name();
if (!absl::c_linear_search(operands_, old_operand)) {
old_operand->RemoveUser(this);
}
new_operand->AddUser(this);
return Status::OK();
}
Status HloInstruction::ReplaceAllUsesWith(HloInstruction* new_producer) {
TF_RET_CHECK(
ShapeUtil::CompatibleIgnoringFpPrecision(shape(), new_producer->shape()))
<< shape() << " is not compatible with " << new_producer->shape();
return ReplaceAllUsesWithDifferentShape(new_producer);
}
Status HloInstruction::ReplaceAllUsesWithDifferentShape(
HloInstruction* new_producer) {
bool new_producer_is_user = false;
for (HloInstruction* user : users()) {
if (user == new_producer) {
// It's possible that new_producer is a user of this instruction as might
// be the case when replacing an instruction with a kCopy of itself. In
// this case, don't do the replacement to avoid creating a cycle in the
// graph. new_producer remains the only user of this instruction.
new_producer_is_user = true;
} else {
std::replace(user->operands_.begin(), user->operands_.end(), this,
new_producer);
new_producer->AddUser(user);
if (user->opcode() == HloOpcode::kFusion) {
TF_RETURN_IF_ERROR(
Cast<HloFusionInstruction>(user)->DeduplicateFusionOperands());
}
}
}
users_.clear();
user_set_.clear();
if (new_producer_is_user) {
AddUser(new_producer);
}
if (parent_ && parent_->root_instruction() == this) {
parent_->set_root_instruction(new_producer,
/*accept_different_shape=*/true);
}
return Status::OK();
}
HloComputation* HloInstruction::to_apply() const {
switch (opcode_) {
case HloOpcode::kCall:
case HloOpcode::kMap:
case HloOpcode::kReduceWindow:
case HloOpcode::kReduce:
case HloOpcode::kAllReduce:
case HloOpcode::kScatter:
case HloOpcode::kSort:
CHECK_EQ(called_computations_.size(), 1);
return called_computations_[0];
default:
LOG(FATAL) << "Invalid opcode for to_apply(): "
<< HloOpcodeString(opcode());
}
}
void HloInstruction::set_to_apply(HloComputation* computation) {
// Don't allow changing the computation for fused instructions so we don't
// have to recompute called_instructions for the entire fusion instruction.
CHECK(!IsFused());
switch (opcode_) {
case HloOpcode::kCall:
case HloOpcode::kMap:
case HloOpcode::kReduceWindow:
case HloOpcode::kReduce:
case HloOpcode::kAllReduce:
case HloOpcode::kScatter:
case HloOpcode::kSort:
CHECK_EQ(called_computations_.size(), 1);
called_computations_[0] = computation;
break;
default:
LOG(FATAL) << "Invalid opcode for to_apply(): "
<< HloOpcodeString(opcode());
}
}
HloComputation* HloInstruction::while_condition() const {
CHECK_EQ(HloOpcode::kWhile, opcode_);
return called_computations_[kConditionComputationIndex];
}
HloComputation* HloInstruction::while_body() const {
CHECK_EQ(HloOpcode::kWhile, opcode_);
return called_computations_[kBodyComputationIndex];
}
void HloInstruction::set_while_condition(HloComputation* computation) {
// Don't allow changing the computation for fused instructions so we don't
// have to recompute called_instructions for the entire fusion instruction.
CHECK(!IsFused());
CHECK_EQ(HloOpcode::kWhile, opcode_);
called_computations_[kConditionComputationIndex] = computation;
}
void HloInstruction::set_while_body(HloComputation* computation) {
// Don't allow changing the computation for fused instructions so we don't
// have to recompute called_instructions for the entire fusion instruction.
CHECK(!IsFused());
CHECK_EQ(HloOpcode::kWhile, opcode_);
called_computations_[kBodyComputationIndex] = computation;
}
HloInstruction* HloInstruction::while_init() const {
CHECK_EQ(HloOpcode::kWhile, opcode_);
return operands_[0];
}
HloComputation* HloInstruction::true_computation() const {
CHECK_EQ(HloOpcode::kConditional, opcode_);
CHECK_EQ(PRED, operand(0)->shape().element_type());
return called_computations_[kTrueComputationIndex];
}
HloComputation* HloInstruction::false_computation() const {
CHECK_EQ(HloOpcode::kConditional, opcode_);
CHECK_EQ(PRED, operand(0)->shape().element_type());
return called_computations_[kFalseComputationIndex];
}
const std::vector<HloComputation*>& HloInstruction::branch_computations()
const {
CHECK(HloOpcode::kConditional == opcode_);
return called_computations_;
}
int HloInstruction::branch_count() const {
CHECK(HloOpcode::kConditional == opcode_);
return called_computations_.size();
}
HloComputation* HloInstruction::branch_computation(int b) const {
CHECK(HloOpcode::kConditional == opcode_);
CHECK_GE(b, 0);
CHECK_LT(b, called_computations_.size());
return called_computations_[b];
}
void HloInstruction::set_branch_computation(int b,
HloComputation* computation) {
// Don't allow changing the computation for fused instructions so we don't
// have to recompute called_instructions for the entire fusion instruction.
CHECK(!IsFused());
CHECK_EQ(HloOpcode::kConditional, opcode_);
called_computations_[b] = computation;
}
string HloInstruction::SignatureString() const {
string operands =
StrJoin(operands_, ", ", [](string* out, HloInstruction* operand) {
StrAppend(out, ShapeUtil::HumanString(operand->shape()));
});
return StrCat("(", operands, ") -> ", ShapeUtil::HumanString(shape()));
}
string PrintName(const string& name, bool print_ids) {
if (print_ids) {
return name;
} else {
auto dot_position = name.find_first_of(".");
return name.substr(0, dot_position);
}
}
namespace {
string PrintNameInternal(const string& name, const HloPrintOptions& options) {
return StrCat(options.print_percent() ? "%" : "",
PrintName(name, options.print_ids()));
}
} // namespace
string HloInstruction::ToString(const HloPrintOptions& options) const {
CanonicalNameMap new_map;
return ToStringWithCanonicalNameMap(options, &new_map);
}
bool HloInstruction::IsElementwiseImpl(
const absl::optional<int64>& operand_idx) const {
switch (opcode_) {
// Unary elementwise operations.
case HloOpcode::kAbs:
case HloOpcode::kRoundNearestAfz:
case HloOpcode::kCeil:
case HloOpcode::kClz:
case HloOpcode::kConvert:
case HloOpcode::kBitcastConvert:
case HloOpcode::kCopy:
case HloOpcode::kCos:
case HloOpcode::kExp:
case HloOpcode::kExpm1:
case HloOpcode::kFloor:
case HloOpcode::kImag:
case HloOpcode::kIsFinite:
case HloOpcode::kLog:
case HloOpcode::kLog1p:
case HloOpcode::kNot:
case HloOpcode::kNegate:
case HloOpcode::kPopulationCount:
case HloOpcode::kReal:
case HloOpcode::kReducePrecision:
case HloOpcode::kRsqrt:
case HloOpcode::kSign:
case HloOpcode::kSin:
case HloOpcode::kSqrt:
case HloOpcode::kTanh:
CHECK_EQ(1, operand_count());
return true;
// Binary elementwise operations, the same as in IsElementwiseBinary().
case HloOpcode::kAdd:
case HloOpcode::kAtan2:
case HloOpcode::kCompare:
case HloOpcode::kComplex:
case HloOpcode::kDivide:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kMultiply:
case HloOpcode::kPower:
case HloOpcode::kRemainder:
case HloOpcode::kSubtract:
case HloOpcode::kAnd:
case HloOpcode::kOr:
case HloOpcode::kXor:
case HloOpcode::kShiftLeft:
case HloOpcode::kShiftRightArithmetic:
case HloOpcode::kShiftRightLogical:
CHECK_EQ(2, operand_count());
return true;
// Ternary elementwise operations.
case HloOpcode::kSelect:
case HloOpcode::kClamp:
return true;
case HloOpcode::kDynamicUpdateSlice:
return operand_idx.has_value() && operand_idx.value() == 0;
default:
return false;
}
}
bool HloInstruction::IsCrossModuleAllReduce() const {
return opcode() == HloOpcode::kAllReduce && channel_id();
}
bool HloInstruction::IsCrossReplicaAllReduce() const {
return opcode() == HloOpcode::kAllReduce && !channel_id();
}
string HloInstruction::ToStringWithCanonicalNameMap(
const HloPrintOptions& options,
CanonicalNameMap* canonical_name_map) const {
string result = "";
// Logic to print the instruction name (e.g. "%foo = ").
if (options.canonicalize_instruction_names()) {
if (options.is_in_nested_computation()) {
// If we are canonicalizing instruction names and this is a top-level
// HloInstruction::ToString() call, don't print an instruction name.
StrAppend(&result,
PrintNameInternal(canonical_name_map->LookupOrInsert(name()),
options),
" = ");
}
} else {
StrAppend(&result, PrintNameInternal(name(), options), " = ");
}
// Print shape.
if (options.include_layout_in_shapes()) {
StrAppend(&result, ShapeUtil::HumanStringWithLayout(shape()));
} else {
StrAppend(&result, ShapeUtil::HumanString(shape()));
}
// Print opcode, operand(s).
StrAppend(&result, " ", HloOpcodeString(opcode()), "(",
OperandsToStringWithCanonicalNameMap(options, canonical_name_map),
")");
// Print additional attributes. If an instruction contains a subcomputation,
// the subcomputation is also printed here.
for (const string& extra : ExtraAttributesToString(options)) {
StrAppend(&result, ", ", extra);
}
if (options.print_metadata() &&
(!metadata_.op_type().empty() || !metadata_.op_name().empty() ||
!metadata_.source_file().empty())) {
StrAppend(&result, ", metadata={", xla::OpMetadataToString(metadata_), "}");
}
if (options.print_backend_config() && !backend_config_.empty()) {
StrAppend(&result, ", backend_config=\"", CEscape(backend_config_), "\"");
}
return result;
}
string HloInstruction::OperandsToString(const HloPrintOptions& options) const {
CanonicalNameMap new_map;
return OperandsToStringWithCanonicalNameMap(options, &new_map);
}
string HloInstruction::OperandsToStringWithCanonicalNameMap(
const HloPrintOptions& options,
CanonicalNameMap* canonical_name_map) const {
string operands;
absl::Span<HloInstruction* const> slice(operands_);
const int64 kMaxOperandsToShowIfCompact = 4;
if (options.compact_operands() &&
slice.size() > kMaxOperandsToShowIfCompact) {
slice.remove_suffix(slice.size() - kMaxOperandsToShowIfCompact);
}
operands = StrJoin(slice, ", ", [&](string* out, HloInstruction* operand) {
// If operand is already been deleted, put `null` to the string output.
if (operand == nullptr) {
StrAppend(out, "null ");
return;
}
std::vector<string> str;
if (options.print_operand_shape()) {
if (options.include_layout_in_shapes()) {
str.push_back(ShapeUtil::HumanStringWithLayout(operand->shape()));
} else {
str.push_back(ShapeUtil::HumanString(operand->shape()));
}
}
// In a top-level HloInstruction::ToString() call, the operand name is not
// part of the canonical string.
if (options.canonicalize_instruction_names() &&
options.is_in_nested_computation()) {
str.push_back(PrintNameInternal(
canonical_name_map->LookupOrInsert(operand->name()), options));
} else if (options.print_operand_names()) {
str.push_back(PrintNameInternal(operand->name(), options));
}
StrAppend(out, StrJoin(str, " "));
});
const int64 remaining = operands_.size() - slice.size();
if (slice.size() != operands_.size()) {
StrAppend(&operands, ", ...(+", remaining, ")");
}
return operands;
}
std::vector<string> HloInstruction::ExtraAttributesToString(
const HloPrintOptions& options) const {
std::vector<string> extra = ExtraAttributesToStringImpl(options);
if (options.print_subcomputation_mode() ==
HloPrintOptions::PrintSubcomputationMode::kNameOnly) {
if (opcode() == HloOpcode::kWhile) {
extra.push_back(StrCat(
"condition=", PrintNameInternal(while_condition()->name(), options)));
extra.push_back(
StrCat("body=", PrintNameInternal(while_body()->name(), options)));
} else if (opcode() == HloOpcode::kSelectAndScatter) {
extra.push_back(
StrCat("select=", PrintNameInternal(select()->name(), options)));
extra.push_back(
StrCat("scatter=", PrintNameInternal(scatter()->name(), options)));
} else if (opcode() == HloOpcode::kConditional) {
if (operand(0)->shape().element_type() == PRED) {
extra.push_back(
StrCat("true_computation=",
PrintNameInternal(true_computation()->name(), options)));
extra.push_back(
StrCat("false_computation=",
PrintNameInternal(false_computation()->name(), options)));
} else {
extra.push_back(StrCat(
"branch_computations={",
StrJoin(branch_computations(), ", ",
[&](string* out, const HloComputation* computation) {
StrAppend(
out, PrintNameInternal(computation->name(), options));
}),
"}"));
}
} else if (opcode() == HloOpcode::kCall || opcode() == HloOpcode::kMap ||
opcode() == HloOpcode::kReduceWindow ||
opcode() == HloOpcode::kReduce ||
opcode() == HloOpcode::kAllReduce ||
opcode() == HloOpcode::kScatter ||
opcode() == HloOpcode::kSort) {
extra.push_back(
StrCat("to_apply=", PrintNameInternal(to_apply()->name(), options)));
} else if (!called_computations().empty()) {
extra.push_back(StrCat(
"calls=",
StrJoin(called_computations(), ", ",
[&](string* out, const HloComputation* computation) {
StrAppend(out,
PrintNameInternal(computation->name(), options));
})));
}
} else if (options.print_subcomputation_mode() ==
HloPrintOptions::PrintSubcomputationMode::kFullBodies) {
HloPrintOptions new_options = options;
new_options.set_is_in_nested_computation(true);
switch (opcode()) {
case HloOpcode::kWhile:
extra.push_back(
StrCat("condition=\n", while_condition()->ToString(new_options)));
extra.push_back(StrCat("body=\n", while_body()->ToString(new_options)));
break;
case HloOpcode::kSelectAndScatter:
extra.push_back(StrCat("select=\n", select()->ToString(new_options)));
extra.push_back(StrCat("scatter=\n", scatter()->ToString(new_options)));
break;
case HloOpcode::kConditional:
if (operand(0)->shape().element_type() == PRED) {
extra.push_back(StrCat("true_computation=\n",
true_computation()->ToString(new_options)));
extra.push_back(StrCat("false_computation=\n",
false_computation()->ToString(new_options)));
} else {
extra.push_back(StrCat(
"branch_computations={\n",
StrJoin(branch_computations(), ",\n",
[&](string* out, const HloComputation* computation) {
StrAppend(out, computation->ToString(new_options));
}),
"\n}"));
}
break;
case HloOpcode::kCall:
case HloOpcode::kMap:
case HloOpcode::kReduceWindow:
case HloOpcode::kReduce:
case HloOpcode::kAllReduce:
case HloOpcode::kScatter:
case HloOpcode::kSort:
extra.push_back(
StrCat("to_apply=\n", to_apply()->ToString(new_options)));
break;
default:
if (!called_computations().empty()) {
extra.push_back(StrCat(
"calls=\n",
StrJoin(called_computations(), ", ",
[&](string* out, const HloComputation* computation) {
StrAppend(out, computation->ToString(new_options));
})));
}
break;
}
}
if (has_sharding()) {
extra.push_back(StrCat("sharding=", sharding().ToString()));
}
if (!outer_dimension_partitions_.empty()) {
extra.push_back(absl::StrFormat("outer_dimension_partitions={%s}",
StrJoin(outer_dimension_partitions_, ",")));
}
if (options.print_control_dependencies() && !control_predecessors_.empty()) {
extra.push_back(StrCat("control-predecessors={",
StrJoin(control_predecessors_, ", ",
[&](string* out, HloInstruction* pre) {
StrAppend(out, PrintNameInternal(
pre->name(), options));
}),
"}"));
}
return extra;
}
string HloInstruction::ToShortString() const {
return StrCat("%", name(), " = ", HloOpcodeString(opcode()), "(",
StrJoin(operands_, ", ",
[](string* out, HloInstruction* operand) {
StrAppend(out, "%", operand->name());
}),
")");
}
HloInstructionProto HloInstruction::ToProto() const {
HloInstructionProto proto;
CHECK(unique_id_ != -1)
<< "This instruction does not have a valid id. Please make sure the "
"instruction is inside a module before dumping it.";
proto.set_id(unique_id_);
proto.set_name(name_);
proto.set_opcode(HloOpcodeString(opcode_));
*proto.mutable_shape() = shape_.ToProto();
for (const HloInstruction* operand : operands_) {
proto.add_operand_ids(operand->unique_id());
}
for (const HloInstruction* control : control_predecessors_) {
proto.add_control_predecessor_ids(control->unique_id());
}
*proto.mutable_metadata() = metadata_;
proto.set_backend_config(backend_config_);
if (opcode() != HloOpcode::kFusion) {
for (const HloComputation* computation : called_computations_) {
proto.add_called_computation_ids(computation->unique_id());
}
}
if (has_sharding()) {
*proto.mutable_sharding() = sharding().ToProto();
}
if (!outer_dimension_partitions_.empty()) {
for (const auto& idx : outer_dimension_partitions_) {
proto.mutable_outer_dimension_partitions()->Add(idx);
}
}
return proto;
}
string HloInstruction::ToCategory() const {
if (opcode() == HloOpcode::kTranspose || opcode() == HloOpcode::kCopy ||
opcode() == HloOpcode::kReshape) {
return "data formatting";
}
if (IsElementwise()) {
return "non-fusion elementwise";
}
return HloOpcodeString(opcode());
}
HloInstruction* HloInstruction::tracing() const { return trace_instruction_; }
void HloInstruction::set_tracing(HloInstruction* trace_instruction) {
trace_instruction_ = trace_instruction;
}
bool HloInstruction::IsFused() const { return parent_->IsFusionComputation(); }
bool HloInstruction::IsInputFusion() const {
return opcode() == HloOpcode::kFusion && fusion_kind() == FusionKind::kInput;
}
bool HloInstruction::IsLoopFusion() const {
return opcode() == HloOpcode::kFusion && fusion_kind() == FusionKind::kLoop;
}
bool HloInstruction::IsOutputFusion() const {
return opcode() == HloOpcode::kFusion && fusion_kind() == FusionKind::kOutput;
}
bool HloInstruction::IsCustomFusion() const {
return opcode() == HloOpcode::kFusion && fusion_kind() == FusionKind::kCustom;
}
bool HloInstruction::IsFusible() const {
// Instructions which are traced should not be fused.
if (tracing()) {
return false;
}
// Some kinds of instructions don't make sense to fuse.
switch (opcode_) {
case HloOpcode::kDomain:
case HloOpcode::kParameter:
return false;
// Side effecting instrutions cannot be fused.
default:
return !HasSideEffect();
}
}
HloInstruction::HloInstruction(HloOpcode opcode, const Shape& shape)
: unique_id_(-1),
opcode_(opcode),
shape_(shape),
name_(HloOpcodeString(opcode)) {
TF_DCHECK_OK(ShapeUtil::ValidateShapeWithOptionalLayout(shape_));
}
template <typename HloInstructionPtr>
Status HloInstruction::Visit(DfsHloVisitorBase<HloInstructionPtr>* visitor) {
switch (opcode_) {
case HloOpcode::kAbs:
return visitor->HandleAbs(this);
case HloOpcode::kAtan2:
return visitor->HandleAtan2(this);
case HloOpcode::kRoundNearestAfz:
return visitor->HandleRound(this);
case HloOpcode::kBatchNormTraining:
return visitor->HandleBatchNormTraining(this);
case HloOpcode::kBatchNormInference:
return visitor->HandleBatchNormInference(this);
case HloOpcode::kBatchNormGrad:
return visitor->HandleBatchNormGrad(this);
case HloOpcode::kSign:
return visitor->HandleSign(this);
case HloOpcode::kConstant:
return visitor->HandleConstant(this);
case HloOpcode::kGetTupleElement:
return visitor->HandleGetTupleElement(this);
case HloOpcode::kParameter:
return visitor->HandleParameter(this);
case HloOpcode::kCompare:
return visitor->HandleCompare(this);
case HloOpcode::kComplex:
return visitor->HandleComplex(this);
case HloOpcode::kAdd:
return visitor->HandleAdd(this);
case HloOpcode::kDivide:
return visitor->HandleDivide(this);
case HloOpcode::kSubtract:
return visitor->HandleSubtract(this);
case HloOpcode::kMaximum:
return visitor->HandleMaximum(this);
case HloOpcode::kMinimum:
return visitor->HandleMinimum(this);
case HloOpcode::kAnd:
return visitor->HandleAnd(this);
case HloOpcode::kOr:
return visitor->HandleOr(this);
case HloOpcode::kXor:
return visitor->HandleXor(this);
case HloOpcode::kShiftLeft:
return visitor->HandleShiftLeft(this);
case HloOpcode::kShiftRightArithmetic:
return visitor->HandleShiftRightArithmetic(this);
case HloOpcode::kShiftRightLogical:
return visitor->HandleShiftRightLogical(this);
case HloOpcode::kConcatenate:
return visitor->HandleConcatenate(this);
case HloOpcode::kConvert:
return visitor->HandleConvert(this);
case HloOpcode::kBitcastConvert:
return visitor->HandleBitcastConvert(this);
case HloOpcode::kCopy:
return visitor->HandleCopy(this);
case HloOpcode::kMultiply:
return visitor->HandleMultiply(this);
case HloOpcode::kDot:
return visitor->HandleDot(this);
case HloOpcode::kPower:
return visitor->HandlePower(this);
case HloOpcode::kRemainder:
return visitor->HandleRemainder(this);
case HloOpcode::kSelect:
return visitor->HandleSelect(this);
case HloOpcode::kTupleSelect:
return visitor->HandleTupleSelect(this);
case HloOpcode::kConvolution:
return visitor->HandleConvolution(this);
case HloOpcode::kFft:
return visitor->HandleFft(this);
case HloOpcode::kAllReduce:
return visitor->HandleAllReduce(this);
case HloOpcode::kAllToAll:
return visitor->HandleAllToAll(this);
case HloOpcode::kCollectivePermute:
return visitor->HandleCollectivePermute(this);
case HloOpcode::kReplicaId:
return visitor->HandleReplicaId(this);
case HloOpcode::kPartitionId:
return visitor->HandlePartitionId(this);
case HloOpcode::kTuple:
return visitor->HandleTuple(this);
case HloOpcode::kMap:
return visitor->HandleMap(this);
case HloOpcode::kClamp:
return visitor->HandleClamp(this);
case HloOpcode::kReduce:
return visitor->HandleReduce(this);
case HloOpcode::kReduceWindow:
return visitor->HandleReduceWindow(this);
case HloOpcode::kSelectAndScatter:
return visitor->HandleSelectAndScatter(this);
case HloOpcode::kNegate:
return visitor->HandleNegate(this);
case HloOpcode::kExp:
return visitor->HandleExp(this);
case HloOpcode::kExpm1:
return visitor->HandleExpm1(this);
case HloOpcode::kFloor:
return visitor->HandleFloor(this);
case HloOpcode::kCeil:
return visitor->HandleCeil(this);
case HloOpcode::kClz:
return visitor->HandleClz(this);
case HloOpcode::kLog:
return visitor->HandleLog(this);
case HloOpcode::kLog1p:
return visitor->HandleLog1p(this);
case HloOpcode::kTanh:
return visitor->HandleTanh(this);
case HloOpcode::kCos:
return visitor->HandleCos(this);
case HloOpcode::kSin:
return visitor->HandleSin(this);
case HloOpcode::kSqrt:
return visitor->HandleSqrt(this);
case HloOpcode::kRsqrt:
return visitor->HandleRsqrt(this);
case HloOpcode::kReal:
return visitor->HandleReal(this);
case HloOpcode::kImag:
return visitor->HandleImag(this);
case HloOpcode::kIsFinite:
return visitor->HandleIsFinite(this);
case HloOpcode::kNot:
return visitor->HandleNot(this);
case HloOpcode::kPopulationCount:
return visitor->HandlePopulationCount(this);
case HloOpcode::kBitcast:
return visitor->HandleBitcast(this);
case HloOpcode::kBroadcast:
return visitor->HandleBroadcast(this);
case HloOpcode::kPad:
return visitor->HandlePad(this);
case HloOpcode::kReshape:
return visitor->HandleReshape(this);
case HloOpcode::kTranspose:
return visitor->HandleTranspose(this);
case HloOpcode::kReverse:
return visitor->HandleReverse(this);
case HloOpcode::kReducePrecision:
return visitor->HandleReducePrecision(this);
case HloOpcode::kSlice:
return visitor->HandleSlice(this);
case HloOpcode::kDynamicSlice:
return visitor->HandleDynamicSlice(this);
case HloOpcode::kDynamicUpdateSlice:
return visitor->HandleDynamicUpdateSlice(this);
case HloOpcode::kSort:
return visitor->HandleSort(this);
case HloOpcode::kInfeed:
return visitor->HandleInfeed(this);
case HloOpcode::kOutfeed:
return visitor->HandleOutfeed(this);
case HloOpcode::kRng:
return visitor->HandleRng(this);
case HloOpcode::kRngGetAndUpdateState:
return visitor->HandleRngGetAndUpdateState(this);
case HloOpcode::kWhile:
return visitor->HandleWhile(this);
case HloOpcode::kFusion:
return visitor->HandleFusion(this);
case HloOpcode::kCall:
return visitor->HandleCall(this);
case HloOpcode::kConditional:
return visitor->HandleConditional(this);
case HloOpcode::kCustomCall:
return visitor->HandleCustomCall(this);
case HloOpcode::kCopyStart:
return visitor->HandleCopyStart(this);
case HloOpcode::kCopyDone:
return visitor->HandleCopyDone(this);
case HloOpcode::kRecv:
return visitor->HandleRecv(this);
case HloOpcode::kRecvDone:
return visitor->HandleRecvDone(this);
case HloOpcode::kSend:
return visitor->HandleSend(this);
case HloOpcode::kSendDone:
return visitor->HandleSendDone(this);
case HloOpcode::kGather:
return visitor->HandleGather(this);
case HloOpcode::kScatter:
return visitor->HandleScatter(this);
case HloOpcode::kDomain:
return visitor->HandleDomain(this);
case HloOpcode::kAfterAll:
return visitor->HandleAfterAll(this);
case HloOpcode::kAddDependency:
return visitor->HandleAddDependency(this);
case HloOpcode::kIota:
return visitor->HandleIota(this);
case HloOpcode::kGetDimensionSize:
return visitor->HandleGetDimensionSize(this);
case HloOpcode::kTriangularSolve:
return visitor->HandleTriangularSolve(this);
case HloOpcode::kCholesky:
return visitor->HandleCholesky(this);
// These opcodes are not handled here.
case HloOpcode::kTrace:
break;
}
return InternalError(
"Unhandled HloOpcode for DfsHloVisitor: %s. This should not happen - "
"please file a bug for XLA.",
HloOpcodeString(opcode_));
}
// Explicit instantiations.
template Status HloInstruction::Visit(DfsHloVisitor* visitor);
template Status HloInstruction::Visit(ConstDfsHloVisitor* visitor);
using DFSStack = absl::InlinedVector<std::pair<int, HloInstruction*>, 16>;
// Push "child" onto the dfs_stack if not already visited. Returns false if a
// cycle was detected, and true otherwise.
template <typename Visitor>
inline bool PushDFSChild(Visitor* visitor, DFSStack* dfs_stack,
HloInstruction* child) {
CHECK(child != nullptr);
const int id = child->unique_id();
CHECK_GE(id, 0) << "instruction may not have a parent computation";
switch (visitor->GetVisitState(id)) {
case Visitor::kVisiting:
return false;
case Visitor::kVisited:
// Nothing to do
return true;
case Visitor::kNotVisited:
dfs_stack->push_back(std::make_pair(id, child));
return true;
}
}
using InternalCompareFunction =
std::function<bool(std::pair<int, const HloInstruction*>,
std::pair<int, const HloInstruction*>)>;
template <typename Visitor>
static Status PostOrderDFS(HloInstruction* root, Visitor* visitor,
const InternalCompareFunction* operand_order,
bool ignore_control_predecessors) {
// Calculating the instruction count within a module can be expensive on large
// models so only do it if the visit state is empty. This will help when the
// same visitor is reused across many computations of a single module.
if (visitor->VisitStateCapacity() == 0) {
visitor->ReserveVisitStates(root->GetModule()->instruction_count());
}
// dfs_stack holds pairs of <HloInstruction*->unique_id(), HloInstruction*>.
//
// We need to keep track of both the id and the instruction because
// instructions can get deleted while they are on the stack, so we
// can't always use the (potentially dead) instruction object to grab
// its id.
DFSStack dfs_stack;
dfs_stack.emplace_back(root->unique_id(), root);
do {
DCHECK(!dfs_stack.empty());
int current_id = dfs_stack.back().first;
HloInstruction* current_node = dfs_stack.back().second;
CHECK_GE(current_id, 0) << current_id << ": " << current_node
<< ": instruction may not have parent computation";
typename Visitor::VisitState visit_state =
visitor->GetVisitState(current_id);
if (visit_state == Visitor::kVisited) {
dfs_stack.pop_back();
VLOG(3) << "Not visiting HLO %" << current_node->name()
<< " as it was already visited.";
continue;
}
if (visit_state == Visitor::kVisiting) {
dfs_stack.pop_back();
TF_RETURN_IF_ERROR(visitor->Preprocess(current_node));
VLOG(2) << "Visiting HLO %" << current_node->name();
TF_RETURN_IF_ERROR(current_node->Visit(visitor));
visitor->SetVisitState(current_id, Visitor::kVisited);
TF_RETURN_IF_ERROR(visitor->Postprocess(current_node));
continue;
}
visitor->SetVisitState(current_id, Visitor::kVisiting);
const size_t old_dfs_stack_size = dfs_stack.size();
for (HloInstruction* child : current_node->operands()) {
if (!TF_PREDICT_TRUE(PushDFSChild(visitor, &dfs_stack, child))) {
return FailedPrecondition(
"A cycle is detected while visiting instruction %s",
current_node->ToString());
}
}
if (!ignore_control_predecessors) {
for (HloInstruction* child : current_node->control_predecessors()) {
if (!TF_PREDICT_TRUE(PushDFSChild(visitor, &dfs_stack, child))) {
return FailedPrecondition(
"A cycle is detected while visiting instruction %s",
current_node->ToString());
}
}
}
if (operand_order != nullptr) {
std::sort(dfs_stack.begin() + old_dfs_stack_size, dfs_stack.end(),
*operand_order);
}
// This makes the traversal order the same as what you'd expect
// out of a recursive algorithm.
std::reverse(dfs_stack.begin() + old_dfs_stack_size, dfs_stack.end());
} while (!dfs_stack.empty());
return Status::OK();
}
template <typename HloInstructionPtr>
Status HloInstruction::Accept(DfsHloVisitorBase<HloInstructionPtr>* visitor,
bool call_finish_visit,
bool ignore_control_predecessors) {
VLOG(3) << "HloInstruction::Accept(%" << name() << ")";
TF_RETURN_IF_ERROR(
PostOrderDFS(this, visitor, nullptr, ignore_control_predecessors));
if (call_finish_visit) {
TF_RETURN_IF_ERROR(visitor->FinishVisit(this));
}
return Status::OK();
}
// Explicit instantiations.
template Status HloInstruction::Accept(DfsHloVisitor*, bool, bool);
template Status HloInstruction::Accept(ConstDfsHloVisitor*, bool, bool);
Status HloInstruction::AcceptWithOperandOrder(
DfsHloVisitor* visitor, const CompareFunction& operand_order,
bool call_finish_visit) {
VLOG(2) << "HloInstruction::AcceptWithOperandOrder(%" << name() << ")";
InternalCompareFunction func = [&operand_order](
std::pair<int, const HloInstruction*> a,
std::pair<int, const HloInstruction*> b) {
// Call the client's comparison function on the actual HloInstruction*
// objects (ignoring the internal ids we also have in our stack entries)
return operand_order(a.second, b.second);
};
TF_RETURN_IF_ERROR(PostOrderDFS(this, visitor, &func,
/*ignore_control_predecessors=*/false));
if (call_finish_visit) {
VLOG(3) << "HloInstruction::AcceptWithOperandOrder BEFORE FINISH VISIT";
TF_RETURN_IF_ERROR(visitor->FinishVisit(this));
VLOG(3) << "HloInstruction::AcceptWithOperandOrder AFTER FINISH VISIT";
}
VLOG(2) << "HloInstruction::AcceptWithOperandOrder EXIT";
return Status::OK();
}
const Shape& HloInstruction::shape() const { return shape_; }
std::vector<int64> HloInstruction::OperandIndices(
const HloInstruction* operand) const {
std::vector<int64> result;
for (int64 i = 0; i < operand_count(); ++i) {
if (this->operand(i) == operand) {
result.push_back(i);
}
}
return result;
}
bool HloInstruction::IsElementwiseBinary() const {
return IsElementwise() && operand_count() == 2;
}
bool HloInstruction::IsElementwise() const {
return IsElementwiseImpl(absl::nullopt);
}
bool HloInstruction::IsElementwiseOnOperand(int64 operand_idx) const {
return IsElementwiseImpl(operand_idx);
}
// A helper class for memoized, recursive computation of HloOpcode::kFusion
// in HloInstruction::OperandElementUse below.
class HloInstruction::FusionReusesParamElements {
public:
using UseKind = HloInstruction::UseKind;
// We could rather iterate backwards through fused_instructions_ here, as it
// is in reverse postorder, and compute whether each fused instruction reuses
// the value of this parameter, which would save stack space but not allow us
// to finish early if we find a reuse.
static UseKind Compute(int64 i, const HloInstruction& hlo) {
absl::flat_hash_map<const HloInstruction*, UseKind> memoization_cache;
return ComputeInternal(i, hlo, &memoization_cache);
}
private:
static UseKind ComputeInternal(
int64 i, const HloInstruction& hlo,
absl::flat_hash_map<const HloInstruction*, UseKind>* cache) {
if (auto hlo_param = DynCast<HloParameterInstruction>(&hlo)) {
if (hlo_param->parameter_number() == i) {
return UseKind::kUse;
}
}
auto p = cache->emplace(&hlo, UseKind::kNoUse);
auto value_it = p.first;
const bool key_is_new = p.second;
if (key_is_new) {
for (int64 j = 0; j < hlo.operands_.size(); ++j) {
UseKind old_val = value_it->second;
// The next operation invalidates iterators.
UseKind new_val =
Fold(old_val,
FoldUseMandatory(hlo.OperandElementUse(j),
ComputeInternal(i, *hlo.operand(j), cache)));
// Re-acquire the iterator. We could work harder to do this only if
// absolutely necessary, but this code is not hot enough to warrant
// that.
value_it = cache->find(&hlo);
value_it->second = new_val;
}
}
return value_it->second;
}
// Combines two UseKinds.
//
// This is the min operation on the lattice
//
// kReuse < kUse < kNoUse.
//
// Two kUses uses which have different permutations count as kReuse.
static UseKind Fold(UseKind a, UseKind b) {
// Without loss of generality, let `b` be the operation with the larger use
// kind.
if (b.kind < a.kind) {
std::swap(a, b);
}
// If the kinds are different, return the smaller one, namely `a`.
if (a.kind != b.kind) {
return a;
}
// If the kinds are both kUse, check that they're the same permutation.
if (a.kind == UseKind::kUse && b.kind == UseKind::kUse &&
a.permutation_instr != b.permutation_instr) {
return UseKind::kReuse;
}
return a; // They're the same.
}
// Combines two UseKinds differently than Fold().
//
// This is the min operation on the lattice
//
// kNoUse < kReuse < kUse.
//
// If `a` and `b` are both kUse and one has a non-null permutation
// instruction, returns kUse with that permutation. OTOH if both have
// different, non-null permutation instructions, returns kReuse.
//
// You can think of this sort of as a conjunction, whereas Fold is sort of a
// disjunction. FoldUseMandatory() says "no use" if either input isn't used,
// whereas Fold() would say "use".
static UseKind FoldUseMandatory(UseKind a, UseKind b) {
if (a.kind == UseKind::kNoUse || b.kind == UseKind::kNoUse) {
return UseKind::kNoUse;
}
if (a.kind == UseKind::kReuse || b.kind == UseKind::kReuse) {
return UseKind::kReuse;
}
if (a.permutation_instr == b.permutation_instr) {
return a; // They're the same.
}
if (b.permutation_instr == nullptr) {
return a;
}
if (a.permutation_instr == nullptr) {
return b;
}
return UseKind::kReuse;
}
};
HloInstruction::UseKind HloInstruction::OperandElementUse(
int64 operand_num) const {
switch (opcode_) {
case HloOpcode::kBitcast:
// A bitcast that only adds or removes degenerate (i.e. size 1) dimensions
// doesn't permute its elements, so it counts as a plain, non-permuting
// use.
return ShapeUtil::DropDegenerateDimensions(shape()) ==
ShapeUtil::DropDegenerateDimensions(operand(0)->shape())
? UseKind::kUse
: UseKind::Permuting(this);
case HloOpcode::kConcatenate:
case HloOpcode::kReshape:
case HloOpcode::kReverse:
case HloOpcode::kSlice:
case HloOpcode::kTranspose:
return UseKind::Permuting(this);
case HloOpcode::kPad:
// Pad reuses the padding value but not the padded array elements.
return operand_num > 0 ? UseKind::kReuse : UseKind::Permuting(this);
case HloOpcode::kReduce:
// Reduce reuses the init values but not the operand array elements.
return operand_num >= Cast<HloReduceInstruction>(this)->input_count()
? UseKind::kReuse
: UseKind::Permuting(this);
case HloOpcode::kFusion:
// Uses the memoizing, recursive computation defined above.
return FusionReusesParamElements::Compute(operand_num,
*fused_expression_root());
case HloOpcode::kDot:
// Matrix-vector dots do not reuse the matrix operand.
if (shape().dimensions_size() <= 1) {
if ((operand_num == 0 && operand(1)->shape().rank() <= 1) ||
(operand_num == 1 && operand(0)->shape().rank() <= 1)) {
return UseKind::kUse;
}
}
return UseKind::kReuse;
case HloOpcode::kDynamicUpdateSlice:
// Dynamic-update-slice reuses only start_indices.
if (operand_num == 0 || operand_num == 1) {
return UseKind::kUse;
}
return UseKind::kReuse;
case HloOpcode::kGather:
// Gather reads its indices in a linear fashion, and it permutes the
// vector it's gathering from.
return operand_num == 0 ? UseKind::kUse : UseKind::Permuting(this);
default:
return IsElementwise() ? UseKind::kUse : UseKind::kReuse;
}
}
std::tuple<bool, std::vector<int64>, std::vector<int64>>
HloInstruction::ReshapeMerelyInsertsOrDeletes1SizedDimensions() const {
if (HloOpcode::kReshape != opcode_) {
return std::make_tuple(false, std::vector<int64>(), std::vector<int64>());
}
return ShapeUtil::InsertedOrDeleted1SizedDimensions(operand(0)->shape_,
shape_);
}
string ToString(HloInstruction::FusionKind kind) {
switch (kind) {
case HloInstruction::FusionKind::kLoop:
return "kLoop";
case HloInstruction::FusionKind::kInput:
return "kInput";
case HloInstruction::FusionKind::kOutput:
return "kOutput";
case HloInstruction::FusionKind::kCustom:
return "kCustom";
}
}
StatusOr<HloInstruction::FusionKind> StringToFusionKind(
const string& kind_name) {
if (kind_name == "kLoop") {
return HloInstruction::FusionKind::kLoop;
}
if (kind_name == "kInput") {
return HloInstruction::FusionKind::kInput;
}
if (kind_name == "kOutput") {
return HloInstruction::FusionKind::kOutput;
}
if (kind_name == "kCustom") {
return HloInstruction::FusionKind::kCustom;
}
return InvalidArgument("Unknown fusion kind: %s", kind_name);
}
string PaddingConfigToString(const PaddingConfig& padding) {
bool has_interior_padding =
absl::c_any_of(padding.dimensions(),
[](const PaddingConfig::PaddingConfigDimension& dim) {
return dim.interior_padding() != 0;
});
return StrJoin(
padding.dimensions(), "x",
[&](string* out, const PaddingConfig::PaddingConfigDimension& dim) {
StrAppend(
out, dim.edge_padding_low(), "_", dim.edge_padding_high(),
has_interior_padding ? StrCat("_", dim.interior_padding()) : "");
});
}
string OpMetadataToString(const OpMetadata& metadata) {
std::vector<string> result;
if (!metadata.op_type().empty()) {
result.push_back(StrCat("op_type=\"", CEscape(metadata.op_type()), "\""));
}
if (!metadata.op_name().empty()) {
result.push_back(StrCat("op_name=\"", CEscape(metadata.op_name()), "\""));
}
if (!metadata.source_file().empty()) {
result.push_back(
StrCat("source_file=\"", CEscape(metadata.source_file()), "\""));
}
if (metadata.source_line() != 0) {
result.push_back(StrCat("source_line=", metadata.source_line()));
}
return StrJoin(result, " ");
}
string RandomDistributionToString(const RandomDistribution& distribution) {
return absl::AsciiStrToLower(RandomDistribution_Name(distribution));
}
string PrecisionToString(const PrecisionConfig::Precision& precision) {
return absl::AsciiStrToLower(PrecisionConfig::Precision_Name(precision));
}
string ConvolutionDimensionNumbersToString(
const ConvolutionDimensionNumbers& dnums) {
// lhs_dims[i] is the symbol of the logical dimension i for the lhs
// operand. E.g. if batch has dimension number 2, then lhs_dims[2] == "b".
std::vector<string> lhs_dims(2 + dnums.input_spatial_dimensions().size());
lhs_dims[dnums.input_batch_dimension()] = 'b';
lhs_dims[dnums.input_feature_dimension()] = 'f';
for (int64 i = 0; i < dnums.input_spatial_dimensions().size(); ++i) {
lhs_dims[dnums.input_spatial_dimensions(i)] = StrCat(i);
}
std::vector<string> rhs_dims(2 + dnums.kernel_spatial_dimensions().size());
rhs_dims[dnums.kernel_input_feature_dimension()] = "i";
rhs_dims[dnums.kernel_output_feature_dimension()] = "o";
for (int64 i = 0; i < dnums.kernel_spatial_dimensions().size(); ++i) {
rhs_dims[dnums.kernel_spatial_dimensions(i)] = StrCat(i);
}
std::vector<string> output_dims(2 + dnums.output_spatial_dimensions().size());
output_dims[dnums.output_batch_dimension()] = 'b';
output_dims[dnums.output_feature_dimension()] = 'f';
for (int64 i = 0; i < dnums.output_spatial_dimensions().size(); ++i) {
output_dims[dnums.output_spatial_dimensions(i)] = StrCat(i);
}
return StrCat(StrJoin(lhs_dims, ""), "_", StrJoin(rhs_dims, ""), "->",
StrJoin(output_dims, ""));
}
string ReplicaGroupsToString(const std::vector<ReplicaGroup>& replica_groups) {
std::vector<string> replica_group_str;
replica_group_str.reserve(replica_groups.size());
for (const ReplicaGroup& group : replica_groups) {
replica_group_str.push_back(
StrCat("{", StrJoin(group.replica_ids(), ","), "}"));
}
return StrCat("{", StrJoin(replica_group_str, ","), "}");
}
StatusOr<RandomDistribution> StringToRandomDistribution(const string& name) {
static std::unordered_map<string, RandomDistribution>* map = [] {
static auto* map = new std::unordered_map<string, RandomDistribution>;
for (int i = 0; i < RandomDistribution_ARRAYSIZE; i++) {
if (RandomDistribution_IsValid(i)) {
auto value = static_cast<RandomDistribution>(i);
(*map)[RandomDistributionToString(value)] = value;
}
}
return map;
}();
auto found = map->find(absl::AsciiStrToLower(name));
if (found == map->end()) {
return InvalidArgument("Unknown distribution");
}
return found->second;
}
StatusOr<PrecisionConfig::Precision> StringToPrecision(const string& name) {
static std::unordered_map<string, PrecisionConfig::Precision>* map = [] {
static auto* map =
new std::unordered_map<string, PrecisionConfig::Precision>;
for (int i = 0; i < PrecisionConfig::Precision_ARRAYSIZE; i++) {
if (PrecisionConfig::Precision_IsValid(i)) {
auto value = static_cast<PrecisionConfig::Precision>(i);
(*map)[PrecisionToString(value)] = value;
}
}
return map;
}();
auto found = map->find(absl::AsciiStrToLower(name));
if (found == map->end()) {
return InvalidArgument("Unknown distribution");
}
return found->second;
}
std::ostream& operator<<(std::ostream& os, HloInstruction::FusionKind kind) {
return os << ToString(kind);
}
bool HloPtrComparator::operator()(const HloInstruction* const& lhs,
const HloInstruction* const& rhs) const {
if (rhs == nullptr) {
// Nothing compares less than nullptr.
return false;
}
if (lhs == nullptr) {
return true;
}
auto lhs_module = lhs->GetModule();
auto rhs_module = rhs->GetModule();
CHECK((lhs_module == nullptr && rhs_module == nullptr) ||
(lhs_module != nullptr && rhs_module != nullptr));
if (lhs_module != nullptr &&
lhs_module->unique_id() != rhs_module->unique_id()) {
return lhs_module->unique_id() < rhs_module->unique_id();
}
return lhs->unique_id() < rhs->unique_id();
}
bool HloInstruction::CouldBeBitcast() const {
switch (opcode_) {
case HloOpcode::kTranspose:
return true;
case HloOpcode::kReshape:
return std::get<0>(ReshapeMerelyInsertsOrDeletes1SizedDimensions());
default:
return false;
}
}
Status HloInstruction::GetBackendConfigInternal(
tensorflow::protobuf::Message* proto) const {
proto->Clear();
// Empty string does not parse as valid JSON, but it's a valid backend config,
// corresponding to the empty proto.
if (backend_config_.empty()) {
return Status::OK();
}
return tensorflow::HumanReadableJsonToProto(backend_config_, proto);
}
Status HloInstruction::set_backend_config(
const tensorflow::protobuf::Message& proto) {
TF_ASSIGN_OR_RETURN(backend_config_, BackendConfigToRawString(proto));
return Status::OK();
}
/* static */ StatusOr<string> HloInstruction::BackendConfigToRawString(
const tensorflow::protobuf::Message& proto) {
string ret;
// Pass ignore_accuracy_loss = true because estimated_cycles field can be
// INT64_MAX. If ignore_accuracy_loss = false and estimated_cycles =
// INT64_MAX, JsonFormat will return an error status, although there is no
// accuracy loss for int64.
TF_RETURN_IF_ERROR(tensorflow::ProtoToHumanReadableJson(
proto, &ret, /*ignore_accuracy_loss=*/true));
return ret;
}
const PrecisionConfig& HloInstruction::precision_config() const {
if (auto* convolution = DynCast<HloConvolutionInstruction>(this)) {
return convolution->precision_config();
}
if (auto* dot = DynCast<HloDotInstruction>(this)) {
return dot->precision_config();
}
LOG(FATAL) << "Unimplemented method.";
}
PrecisionConfig* HloInstruction::mutable_precision_config() {
if (auto* convolution = DynCast<HloConvolutionInstruction>(this)) {
return convolution->mutable_precision_config();
}
if (auto* dot = DynCast<HloDotInstruction>(this)) {
return dot->mutable_precision_config();
}
LOG(FATAL) << "Unimplemented method.";
}
HloModule* HloInstruction::GetModule() const {
if (parent_) {
return parent_->parent();
}
return nullptr;
}
void HloInstruction::UniquifyName(NameUniquer* name_uniquer) {
string parent_str = parent() == nullptr ? "noparent" : parent()->name();
name_ = name_uniquer->GetUniqueName(name_);
}
void HloInstruction::set_outer_dimension_partitions(
const std::vector<int64>& outer_dimension_partitions) {
outer_dimension_partitions_ = outer_dimension_partitions;
}
// TODO(b/80131774): Remove these temporary methods after transition.
int64 HloInstruction::feature_index() const {
return Cast<HloBatchNormInstruction>(this)->feature_index();
}
float HloInstruction::epsilon() const {
return Cast<HloBatchNormInstruction>(this)->epsilon();
}
FftType HloInstruction::fft_type() const {
return Cast<HloFftInstruction>(this)->fft_type();
}
const std::vector<int64>& HloInstruction::fft_length() const {
return Cast<HloFftInstruction>(this)->fft_length();
}
int64 HloInstruction::concatenate_dimension() const {
return Cast<HloConcatenateInstruction>(this)->concatenate_dimension();
}
int64 HloInstruction::dimension() const {
return Cast<HloGetDimensionSizeInstruction>(this)->dimension();
}
int64 HloInstruction::inferred_dimension() const {
return Cast<HloReshapeInstruction>(this)->inferred_dimension();
}
bool HloInstruction::IsRank2Transpose() const {
auto transpose = DynCast<HloTransposeInstruction>(this);
return transpose != nullptr && transpose->IsRank2Transpose();
}
int64 HloInstruction::slice_starts(int64 dimension) const {
return Cast<HloSliceInstruction>(this)->slice_starts(dimension);
}
const std::vector<int64>& HloInstruction::slice_starts() const {
return Cast<HloSliceInstruction>(this)->slice_starts();
}
int64 HloInstruction::slice_limits(int64 dimension) const {
return Cast<HloSliceInstruction>(this)->slice_limits(dimension);
}
const std::vector<int64>& HloInstruction::slice_limits() const {
return Cast<HloSliceInstruction>(this)->slice_limits();
}
int64 HloInstruction::slice_strides(int64 dimension) const {
return Cast<HloSliceInstruction>(this)->slice_strides(dimension);
}
const std::vector<int64>& HloInstruction::slice_strides() const {
return Cast<HloSliceInstruction>(this)->slice_strides();
}
const Literal& HloInstruction::literal() const {
return Cast<HloConstantInstruction>(this)->literal();
}
bool HloInstruction::IsConstant() const {
return DynCast<HloConstantInstruction>(this) != nullptr;
}
void HloInstruction::RelayoutConstant(const Layout& new_layout,
const ShapeIndex& shape_index) {
Cast<HloConstantInstruction>(this)->RelayoutConstant(new_layout, shape_index);
}
string HloInstruction::TracingTag() const {
return Cast<HloTraceInstruction>(this)->TracingTag();
}
HloInstruction* HloInstruction::AddFusionOperand(HloInstruction* new_operand) {
return Cast<HloFusionInstruction>(this)->AddFusionOperand(new_operand);
}
// Delegates to HloFusionInstruction::MergeFusionInstruction.
void HloInstruction::MergeFusionInstruction(
HloInstruction* instruction_to_merge) {
return Cast<HloFusionInstruction>(this)->MergeFusionInstruction(
Cast<HloFusionInstruction>(instruction_to_merge));
}
// Delegates to HloFusionInstruction::MergeFusionInstructionIntoMultiOutput.
void HloInstruction::MergeFusionInstructionIntoMultiOutput(
HloInstruction* instruction_to_merge) {
return Cast<HloFusionInstruction>(this)
->MergeFusionInstructionIntoMultiOutput(
Cast<HloFusionInstruction>(instruction_to_merge));
}
HloInstruction* HloInstruction::FuseInstruction(
HloInstruction* instruction_to_fuse) {
return Cast<HloFusionInstruction>(this)->FuseInstruction(instruction_to_fuse);
}
HloInstruction* HloInstruction::FuseInstructionIntoMultiOutput(
HloInstruction* instruction_to_fuse) {
return Cast<HloFusionInstruction>(this)->FuseInstructionIntoMultiOutput(
instruction_to_fuse);
}
HloComputation* HloInstruction::fused_instructions_computation() const {
return Cast<HloFusionInstruction>(this)->fused_instructions_computation();
}
HloInstruction* HloInstruction::fused_expression_root() const {
return Cast<HloFusionInstruction>(this)->fused_expression_root();
}
const tensorflow::gtl::iterator_range<UnwrappingIterator<
std::list<std::unique_ptr<HloInstruction>>::const_iterator>>
HloInstruction::fused_instructions() const {
return Cast<HloFusionInstruction>(this)->fused_instructions();
}
const tensorflow::gtl::iterator_range<
UnwrappingIterator<std::list<std::unique_ptr<HloInstruction>>::iterator>>
HloInstruction::fused_instructions() {
return Cast<HloFusionInstruction>(this)->fused_instructions();
}
int64 HloInstruction::fused_instruction_count() const {
return Cast<HloFusionInstruction>(this)->fused_instruction_count();
}
HloInstruction* HloInstruction::fused_parameter(int64 parameter_number) const {
return Cast<HloFusionInstruction>(this)->fused_parameter(parameter_number);
}
const std::vector<HloInstruction*>& HloInstruction::fused_parameters() const {
return Cast<HloFusionInstruction>(this)->fused_parameters();
}
const bool HloInstruction::IsMultiOutputFusion() const {
const HloFusionInstruction* fusion = DynCast<HloFusionInstruction>(this);
return fusion != nullptr && fusion->IsMultiOutputFusion();
}
HloInstruction::FusionKind HloInstruction::fusion_kind() const {
return Cast<HloFusionInstruction>(this)->fusion_kind();
}
void HloInstruction::set_fusion_kind(FusionKind kind) {
return Cast<HloFusionInstruction>(this)->set_fusion_kind(kind);
}
RandomDistribution HloInstruction::random_distribution() const {
return Cast<HloRngInstruction>(this)->random_distribution();
}
int64 HloInstruction::parameter_number() const {
return Cast<HloParameterInstruction>(this)->parameter_number();
}
void HloInstruction::set_parameter_replicated_at_leaf_buffers(
absl::Span<const bool> parameter_replicated_at_leaf_buffers) {
return Cast<HloParameterInstruction>(this)
->set_parameter_replicated_at_leaf_buffers(
parameter_replicated_at_leaf_buffers);
}
void HloInstruction::set_parameter_replicated_at_leaf_buffers(
const std::vector<bool>& parameter_replicated_at_leaf_buffers) {
return Cast<HloParameterInstruction>(this)
->set_parameter_replicated_at_leaf_buffers(
parameter_replicated_at_leaf_buffers);
}
const absl::optional<std::vector<bool>>&
HloInstruction::parameter_replicated_at_leaf_buffers() const {
return Cast<HloParameterInstruction>(this)
->parameter_replicated_at_leaf_buffers();
}
int64 HloInstruction::tuple_index() const {
return Cast<HloGetTupleElementInstruction>(this)->tuple_index();
}
void HloInstruction::set_tuple_index(int64 new_tuple_index) {
return Cast<HloGetTupleElementInstruction>(this)->set_tuple_index(
new_tuple_index);
}
int32 HloInstruction::exponent_bits() const {
return Cast<HloReducePrecisionInstruction>(this)->exponent_bits();
}
int32 HloInstruction::mantissa_bits() const {
return Cast<HloReducePrecisionInstruction>(this)->mantissa_bits();
}
string HloInstruction::infeed_config() const {
return Cast<HloInfeedInstruction>(this)->infeed_config();
}
void HloInstruction::set_infeed_config(const string& config) {
return Cast<HloInfeedInstruction>(this)->set_infeed_config(config);
}
const Shape& HloInstruction::outfeed_shape() const {
return Cast<HloOutfeedInstruction>(this)->outfeed_shape();
}
const string& HloInstruction::outfeed_config() const {
return Cast<HloOutfeedInstruction>(this)->outfeed_config();
}
const std::vector<ReplicaGroup>& HloInstruction::replica_groups() const {
return Cast<HloCollectiveInstruction>(this)->replica_groups();
}
const std::vector<std::pair<int64, int64>>&
HloInstruction::source_target_pairs() const {
return Cast<HloCollectivePermuteInstruction>(this)->source_target_pairs();
}
absl::optional<int64> HloInstruction::channel_id() const {
return Cast<HloChannelInstruction>(this)->channel_id();
}
void HloInstruction::set_channel_id(const absl::optional<int64>& channel_id) {
return Cast<HloChannelInstruction>(this)->set_channel_id(channel_id);
}
const ConvolutionDimensionNumbers&
HloInstruction::convolution_dimension_numbers() const {
if (auto convolution = DynCast<HloConvolutionInstruction>(this)) {
return convolution->convolution_dimension_numbers();
}
if (auto custom_call = DynCast<HloCustomCallInstruction>(this)) {
return custom_call->convolution_dimension_numbers();
}
LOG(FATAL) << "Unimplemented method.";
}
void HloInstruction::set_convolution_dimension_numbers(
const ConvolutionDimensionNumbers& dnums) {
if (auto convolution = DynCast<HloConvolutionInstruction>(this)) {
convolution->set_convolution_dimension_numbers(dnums);
} else if (auto custom_call = DynCast<HloCustomCallInstruction>(this)) {
custom_call->set_convolution_dimension_numbers(dnums);
} else {
LOG(FATAL) << "Unimplemented method.";
}
}
int64 HloInstruction::feature_group_count() const {
if (auto convolution = DynCast<HloConvolutionInstruction>(this)) {
return convolution->feature_group_count();
}
return Cast<HloCustomCallInstruction>(this)->feature_group_count();
}
void HloInstruction::set_feature_group_count(int64 feature_group_count) {
Cast<HloCustomCallInstruction>(this)->set_feature_group_count(
feature_group_count);
}
int64 HloInstruction::batch_group_count() const {
if (auto convolution = DynCast<HloConvolutionInstruction>(this)) {
return convolution->batch_group_count();
}
return Cast<HloCustomCallInstruction>(this)->batch_group_count();
}
void HloInstruction::set_batch_group_count(int64 batch_group_count) {
Cast<HloCustomCallInstruction>(this)->set_batch_group_count(
batch_group_count);
}
HloComputation* HloInstruction::select() const {
return Cast<HloSelectAndScatterInstruction>(this)->select();
}
HloComputation* HloInstruction::scatter() const {
return Cast<HloSelectAndScatterInstruction>(this)->scatter();
}
void HloInstruction::set_select(HloComputation* computation) {
return Cast<HloSelectAndScatterInstruction>(this)->set_select(computation);
}
void HloInstruction::set_scatter(HloComputation* computation) {
return Cast<HloSelectAndScatterInstruction>(this)->set_scatter(computation);
}
const string& HloInstruction::custom_call_target() const {
return Cast<HloCustomCallInstruction>(this)->custom_call_target();
}
const PaddingConfig& HloInstruction::padding_config() const {
return Cast<HloPadInstruction>(this)->padding_config();
}
int64 HloInstruction::slice_sizes(int64 dimension) const {
return Cast<HloDynamicSliceInstruction>(this)->slice_sizes(dimension);
}
const std::vector<int64>& HloInstruction::dynamic_slice_sizes() const {
return Cast<HloDynamicSliceInstruction>(this)->dynamic_slice_sizes();
}
const GatherDimensionNumbers& HloInstruction::gather_dimension_numbers() const {
return Cast<HloGatherInstruction>(this)->gather_dimension_numbers();
}
absl::Span<const int64> HloInstruction::gather_slice_sizes() const {
return Cast<HloGatherInstruction>(this)->gather_slice_sizes();
}
const ScatterDimensionNumbers& HloInstruction::scatter_dimension_numbers()
const {
return Cast<HloScatterInstruction>(this)->scatter_dimension_numbers();
}
const DotDimensionNumbers& HloInstruction::dot_dimension_numbers() const {
return Cast<HloDotInstruction>(this)->dot_dimension_numbers();
}
const DomainMetadata& HloInstruction::operand_side_metadata() const {
return Cast<HloDomainInstruction>(this)->operand_side_metadata();
}
const DomainMetadata& HloInstruction::user_side_metadata() const {
return Cast<HloDomainInstruction>(this)->user_side_metadata();
}
ComparisonDirection HloInstruction::comparison_direction() const {
return Cast<HloCompareInstruction>(this)->direction();
}
const TriangularSolveOptions& HloInstruction::triangular_solve_options() const {
return Cast<HloTriangularSolveInstruction>(this)->triangular_solve_options();
}
const CholeskyOptions& HloInstruction::cholesky_options() const {
return Cast<HloCholeskyInstruction>(this)->cholesky_options();
}
} // namespace xla
| [
"v-grniki@microsoft.com"
] | v-grniki@microsoft.com |
3f61433dd1f3eac10d91e1e2b8afb324d5684fe2 | 0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd | /ash/app_launch_unittest.cc | 88deea07253f42a9ae7497d445e8e14a2ab67260 | [
"BSD-3-Clause"
] | permissive | yachtcaptain23/browser-android-tabs | e5144cee9141890590d6d6faeb1bdc5d58a6cbf1 | a016aade8f8333c822d00d62738a922671a52b85 | refs/heads/master | 2021-04-28T17:07:06.955483 | 2018-09-26T06:22:11 | 2018-09-26T06:22:11 | 122,005,560 | 0 | 0 | NOASSERTION | 2019-05-17T19:37:59 | 2018-02-19T01:00:10 | null | UTF-8 | C++ | false | false | 1,781 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/components/quick_launch/public/mojom/constants.mojom.h"
#include "ash/public/interfaces/constants.mojom.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/run_loop.h"
#include "services/service_manager/public/cpp/service_test.h"
#include "services/ui/public/interfaces/constants.mojom.h"
#include "services/ui/public/interfaces/window_server_test.mojom.h"
#include "ui/views/layout/layout_provider.h"
namespace ash {
void RunCallback(bool* success, base::RepeatingClosure callback, bool result) {
*success = result;
std::move(callback).Run();
}
class AppLaunchTest : public service_manager::test::ServiceTest {
public:
AppLaunchTest() : ServiceTest("ash_unittests") {}
~AppLaunchTest() override = default;
private:
void SetUp() override {
base::CommandLine::ForCurrentProcess()->AppendSwitch("use-test-config");
ServiceTest::SetUp();
}
views::LayoutProvider layout_provider_;
DISALLOW_COPY_AND_ASSIGN(AppLaunchTest);
};
// TODO(sky): reenable this once it is actually uses ash with ws2.
TEST_F(AppLaunchTest, DISABLED_TestQuickLaunch) {
connector()->StartService(mojom::kServiceName);
connector()->StartService(quick_launch::mojom::kServiceName);
ui::mojom::WindowServerTestPtr test_interface;
connector()->BindInterface(ui::mojom::kServiceName, &test_interface);
base::RunLoop run_loop;
bool success = false;
test_interface->EnsureClientHasDrawnWindow(
quick_launch::mojom::kServiceName,
base::BindOnce(&RunCallback, &success, run_loop.QuitClosure()));
run_loop.Run();
EXPECT_TRUE(success);
}
} // namespace ash
| [
"artem@brave.com"
] | artem@brave.com |
a3e1325f206592e6fdd3f04b15c9c85940370042 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /net/proxy/proxy_config.cc | 87e17d8eb487d39f66c2c51a8dd1588bc493114c | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 9,150 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/proxy/proxy_config.h"
#include <memory>
#include <utility>
#include "base/logging.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "net/proxy/proxy_info.h"
namespace net {
namespace {
// If |proxies| is non-empty, sets it in |dict| under the key |name|.
void AddProxyListToValue(const char* name,
const ProxyList& proxies,
base::DictionaryValue* dict) {
if (!proxies.IsEmpty())
dict->Set(name, proxies.ToValue());
}
// Split the |uri_list| on commas and add each entry to |proxy_list| in turn.
void AddProxyURIListToProxyList(std::string uri_list,
ProxyList* proxy_list,
ProxyServer::Scheme default_scheme) {
base::StringTokenizer proxy_uri_list(uri_list, ",");
while (proxy_uri_list.GetNext()) {
proxy_list->AddProxyServer(
ProxyServer::FromURI(proxy_uri_list.token(), default_scheme));
}
}
} // namespace
ProxyConfig::ProxyRules::ProxyRules()
: reverse_bypass(false),
type(TYPE_NO_RULES) {
}
ProxyConfig::ProxyRules::ProxyRules(const ProxyRules& other) = default;
ProxyConfig::ProxyRules::~ProxyRules() {
}
void ProxyConfig::ProxyRules::Apply(const GURL& url, ProxyInfo* result) const {
if (empty()) {
result->UseDirect();
return;
}
bool bypass_proxy = bypass_rules.Matches(url);
if (reverse_bypass)
bypass_proxy = !bypass_proxy;
if (bypass_proxy) {
result->UseDirectWithBypassedProxy();
return;
}
switch (type) {
case ProxyRules::TYPE_SINGLE_PROXY: {
result->UseProxyList(single_proxies);
return;
}
case ProxyRules::TYPE_PROXY_PER_SCHEME: {
const ProxyList* entry = MapUrlSchemeToProxyList(url.scheme());
if (entry) {
result->UseProxyList(*entry);
} else {
// We failed to find a matching proxy server for the current URL
// scheme. Default to direct.
result->UseDirect();
}
return;
}
default: {
result->UseDirect();
NOTREACHED();
return;
}
}
}
void ProxyConfig::ProxyRules::ParseFromString(const std::string& proxy_rules) {
// Reset.
type = TYPE_NO_RULES;
single_proxies = ProxyList();
proxies_for_http = ProxyList();
proxies_for_https = ProxyList();
proxies_for_ftp = ProxyList();
fallback_proxies = ProxyList();
base::StringTokenizer proxy_server_list(proxy_rules, ";");
while (proxy_server_list.GetNext()) {
base::StringTokenizer proxy_server_for_scheme(
proxy_server_list.token_begin(), proxy_server_list.token_end(), "=");
while (proxy_server_for_scheme.GetNext()) {
std::string url_scheme = proxy_server_for_scheme.token();
// If we fail to get the proxy server here, it means that
// this is a regular proxy server configuration, i.e. proxies
// are not configured per protocol.
if (!proxy_server_for_scheme.GetNext()) {
if (type == TYPE_PROXY_PER_SCHEME)
continue; // Unexpected.
AddProxyURIListToProxyList(url_scheme,
&single_proxies,
ProxyServer::SCHEME_HTTP);
type = TYPE_SINGLE_PROXY;
return;
}
// Trim whitespace off the url scheme.
base::TrimWhitespaceASCII(url_scheme, base::TRIM_ALL, &url_scheme);
// Add it to the per-scheme mappings (if supported scheme).
type = TYPE_PROXY_PER_SCHEME;
ProxyList* entry = MapUrlSchemeToProxyListNoFallback(url_scheme);
ProxyServer::Scheme default_scheme = ProxyServer::SCHEME_HTTP;
// socks=XXX is inconsistent with the other formats, since "socks"
// is not a URL scheme. Rather this means "for everything else, send
// it to the SOCKS proxy server XXX".
if (url_scheme == "socks") {
DCHECK(!entry);
entry = &fallback_proxies;
// Note that here 'socks' is understood to be SOCKS4, even though
// 'socks' maps to SOCKS5 in ProxyServer::GetSchemeFromURIInternal.
default_scheme = ProxyServer::SCHEME_SOCKS4;
}
if (entry) {
AddProxyURIListToProxyList(proxy_server_for_scheme.token(),
entry,
default_scheme);
}
}
}
}
const ProxyList* ProxyConfig::ProxyRules::MapUrlSchemeToProxyList(
const std::string& url_scheme) const {
const ProxyList* proxy_server_list = const_cast<ProxyRules*>(this)->
MapUrlSchemeToProxyListNoFallback(url_scheme);
if (proxy_server_list && !proxy_server_list->IsEmpty())
return proxy_server_list;
if (url_scheme == "ws" || url_scheme == "wss")
return GetProxyListForWebSocketScheme();
if (!fallback_proxies.IsEmpty())
return &fallback_proxies;
return NULL; // No mapping for this scheme. Use direct.
}
bool ProxyConfig::ProxyRules::Equals(const ProxyRules& other) const {
return type == other.type &&
single_proxies.Equals(other.single_proxies) &&
proxies_for_http.Equals(other.proxies_for_http) &&
proxies_for_https.Equals(other.proxies_for_https) &&
proxies_for_ftp.Equals(other.proxies_for_ftp) &&
fallback_proxies.Equals(other.fallback_proxies) &&
bypass_rules.Equals(other.bypass_rules) &&
reverse_bypass == other.reverse_bypass;
}
ProxyList* ProxyConfig::ProxyRules::MapUrlSchemeToProxyListNoFallback(
const std::string& scheme) {
DCHECK_EQ(TYPE_PROXY_PER_SCHEME, type);
if (scheme == "http")
return &proxies_for_http;
if (scheme == "https")
return &proxies_for_https;
if (scheme == "ftp")
return &proxies_for_ftp;
return NULL; // No mapping for this scheme.
}
const ProxyList* ProxyConfig::ProxyRules::GetProxyListForWebSocketScheme()
const {
if (!fallback_proxies.IsEmpty())
return &fallback_proxies;
if (!proxies_for_https.IsEmpty())
return &proxies_for_https;
if (!proxies_for_http.IsEmpty())
return &proxies_for_http;
return NULL;
}
ProxyConfig::ProxyConfig()
: auto_detect_(false), pac_mandatory_(false),
source_(PROXY_CONFIG_SOURCE_UNKNOWN), id_(kInvalidConfigID) {
}
ProxyConfig::ProxyConfig(const ProxyConfig& config) = default;
ProxyConfig::~ProxyConfig() {
}
ProxyConfig& ProxyConfig::operator=(const ProxyConfig& config) = default;
bool ProxyConfig::Equals(const ProxyConfig& other) const {
// The two configs can have different IDs and sources. We are just interested
// in if they have the same settings.
return auto_detect_ == other.auto_detect_ &&
pac_url_ == other.pac_url_ &&
pac_mandatory_ == other.pac_mandatory_ &&
proxy_rules_.Equals(other.proxy_rules());
}
bool ProxyConfig::HasAutomaticSettings() const {
return auto_detect_ || has_pac_url();
}
void ProxyConfig::ClearAutomaticSettings() {
auto_detect_ = false;
pac_url_ = GURL();
}
std::unique_ptr<base::DictionaryValue> ProxyConfig::ToValue() const {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
// Output the automatic settings.
if (auto_detect_)
dict->SetBoolean("auto_detect", auto_detect_);
if (has_pac_url()) {
dict->SetString("pac_url", pac_url_.possibly_invalid_spec());
if (pac_mandatory_)
dict->SetBoolean("pac_mandatory", pac_mandatory_);
}
// Output the manual settings.
if (proxy_rules_.type != ProxyRules::TYPE_NO_RULES) {
switch (proxy_rules_.type) {
case ProxyRules::TYPE_SINGLE_PROXY:
AddProxyListToValue("single_proxy", proxy_rules_.single_proxies,
dict.get());
break;
case ProxyRules::TYPE_PROXY_PER_SCHEME: {
std::unique_ptr<base::DictionaryValue> dict2(
new base::DictionaryValue());
AddProxyListToValue("http", proxy_rules_.proxies_for_http, dict2.get());
AddProxyListToValue("https", proxy_rules_.proxies_for_https,
dict2.get());
AddProxyListToValue("ftp", proxy_rules_.proxies_for_ftp, dict2.get());
AddProxyListToValue("fallback", proxy_rules_.fallback_proxies,
dict2.get());
dict->Set("proxy_per_scheme", std::move(dict2));
break;
}
default:
NOTREACHED();
}
// Output the bypass rules.
const ProxyBypassRules& bypass = proxy_rules_.bypass_rules;
if (!bypass.rules().empty()) {
if (proxy_rules_.reverse_bypass)
dict->SetBoolean("reverse_bypass", true);
auto list = std::make_unique<base::ListValue>();
for (ProxyBypassRules::RuleList::const_iterator it =
bypass.rules().begin();
it != bypass.rules().end(); ++it) {
list->AppendString((*it)->ToString());
}
dict->Set("bypass_list", std::move(list));
}
}
// Output the source.
dict->SetString("source", ProxyConfigSourceToString(source_));
return dict;
}
} // namespace net
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
43121abe4cc63532158f72d199d613cdaa271d06 | a1eab6f939f8e1622cf2d6a5bc344762a660a3cf | /algorithm/code/minimal_number.cpp | 9028f9dc13373213b3e7ba722a0fdfc335b8305d | [] | no_license | T-tssxuan/data_structure_algorithm | 02b21f20adae864ac55857d58c68d6fb806719a4 | 3a19ac19bd4b56c6971b95fa1adb9d7c857f94fe | refs/heads/master | 2021-01-12T16:26:14.980768 | 2017-08-16T14:06:43 | 2017-08-16T14:06:43 | 69,272,305 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,764 | cpp | #include <string>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/**
* Describe: Give a series of number, find the minimal number they can find.
*/
// The order decide compare
bool compare(const string &str1, const string &str2){
size_t idx1 = 0;
size_t idx2 = 0;
while (idx1 < str1.length() && idx2 < str2.length()) {
if (str1[idx1] > str2[idx2]) {
return true;
} else if (str1[idx1] < str2[idx2]) {
return false;
}
++idx1;
++idx2;
}
if (idx1 < str1.length()) {
string tmp = str1.substr(idx1);
return compare(tmp, str2);
}
if (idx2 < str2.length()) {
string tmp = str2.substr(idx2);
return compare(str1, tmp);
}
return false;
};
class Solution {
public:
using PQ = priority_queue<string, vector<string>, function<bool(const string &, const string &)>>;
string minNumber(vector<int>& nums) {
vector<string> strs(nums.size());
auto trans = [](int a){ return to_string(a); };
transform(nums.begin(), nums.end(), strs.begin(), trans);
PQ pq(strs.begin(), strs.end(), compare);
string rst;
while (!pq.empty()) {
rst += pq.top();
pq.pop();
}
size_t idx = 0;
while (idx < rst.length() && rst[idx] == '0') {
++idx;
}
rst = rst.substr(idx);
return rst == ""? "0" : rst;
}
};
int main() {
Solution so;
int n;
vector<int> test;
while (cin >> n) {
test = vector<int>(n);
for (auto& ele : test) {
cin >> ele;
}
auto re = so.minNumber(test);
cout << "result: " << re << endl;
}
return 0;
}
| [
"2270360114@qq.com"
] | 2270360114@qq.com |
31f23e1166d0dee42f32ad83d4107e2b362cdfca | 260e5dec446d12a7dd3f32e331c1fde8157e5cea | /Indi/SDK/Indi_Food_Rizzo_KnockYouOutBar_functions.cpp | eb07ee8753f1aeb92b104eabcf410c76e6c342a4 | [] | no_license | jfmherokiller/TheOuterWorldsSdkDump | 6e140fde4fcd1cade94ce0d7ea69f8a3f769e1c0 | 18a8c6b1f5d87bb1ad4334be4a9f22c52897f640 | refs/heads/main | 2023-08-30T09:27:17.723265 | 2021-09-17T00:24:52 | 2021-09-17T00:24:52 | 407,437,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | cpp | // TheOuterWorlds SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "Indi_Food_Rizzo_KnockYouOutBar_parameters.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"peterpan0413@live.com"
] | peterpan0413@live.com |
ac36cdc32d03e8e2cb0828aa040afa92fec280c5 | 92adab7f98dc2e694739558e925dc4a408aa7da8 | /cpp/CSC2104/labtest5/binary_search_tree.cpp | fbf5ea308559eb4f4bdc8af6a3571bc6a9ebaff2 | [] | no_license | wzulfikar/lab | a5c29d54baa111526032741a7850ebf9457148a3 | 2ef21c16150a88a15bfb7bf4ef0014fbee262ed3 | refs/heads/master | 2023-07-23T21:37:46.047237 | 2022-10-14T20:31:15 | 2022-10-14T20:31:15 | 83,702,755 | 3 | 2 | null | 2023-07-12T00:14:00 | 2017-03-02T16:56:58 | Jupyter Notebook | UTF-8 | C++ | false | false | 2,421 | cpp | #include <iostream>
#include <list>
using namespace std;
// template
template<class T>
class Node {
public:
T value;
Node<T>* left;
Node<T>* right;
Node(T value) {
this->value = value;
this->left = NULL;
this->right = NULL;
}
};
template<class F>
class BST {
private:
Node<F> *root;
void prefix (Node<F>* current) {
if (current != NULL) {
cout << current->value << ' ';
prefix(current->left);
prefix(current->right);
}
}
void infix (Node<F>* current) {
if (current != NULL) {
infix(current->left);
cout << current->value << ' ';
infix(current->right);
}
}
void reverseInfix (Node<F>* current) {
if (current != NULL) {
reverseInfix(current->right);
cout << current->value << ' ';
reverseInfix(current->left);
}
}
void postfix (Node<F>* current) {
if (current != NULL) {
postfix(current->left);
postfix(current->right);
cout << current->value << ' ';
}
}
public:
BST(){
root = NULL;
}
void insert (F value) {
if (root == NULL) {
root = new Node<F>(value);
} else {
Node<F>* temp = root;
while (temp != NULL) {
if (value > temp->value) {
if (temp->right == NULL) {
temp->right = new Node<F>(value);
break;
}
temp = temp->right;
} else {
if (temp->left == NULL) {
temp->left = new Node<F>(value);
break;
}
temp = temp->left;
}
}
}
}
bool find (F value) {
Node<F>* temp = root;
while (temp != NULL) {
if (value == temp->value) {
return true;
}
temp = value > temp->value ? temp->right : temp->left;
}
return false;
}
void display (int order = 0) {
switch (order) {
case 0:
cout << "Displaying tree in PREFIX mode:\n";
prefix(root);
break;
case 1:
cout << "Displaying tree in INFIX mode:\n";
infix(root);
break;
case 2:
cout << "Displaying tree in POSTFIX mode:\n";
postfix(root);
break;
case 3:
cout << "Displaying tree in REVERSE-INVIX mode:\n";
reverseInfix(root);
break;
default:
prefix(root);
}
}
};
int main() {
BST<int> tree;
tree.insert(5);
tree.insert(10);
tree.insert(3);
tree.insert(7);
tree.insert(10);
tree.insert(7);
tree.display(3);
string findNode = tree.find(11) ? "Found" : "Not found";
cout << "\nNode 11 is " << findNode;
string findNode2 = tree.find(10) ? "Found" : "Not found";
cout << "\nNode 10 is " << findNode2;
return 0;
}
| [
"me@wzulfikar.com"
] | me@wzulfikar.com |
c0815807a8e63c60bf6d54da7a462ba7c892dff6 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /net/http/http_proxy_client_socket_wrapper.h | 3d0c27f741f6ee1a92a12708414c79eefa9e30c2 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 7,281 | h | // Copyright 2015 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 NET_HTTP_HTTP_PROXY_CLIENT_SOCKET_WRAPPER_H_
#define NET_HTTP_HTTP_PROXY_CLIENT_SOCKET_WRAPPER_H_
#include <stdint.h>
#include <memory>
#include <string>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "net/base/completion_callback.h"
#include "net/base/host_port_pair.h"
#include "net/base/load_timing_info.h"
#include "net/http/http_auth_controller.h"
#include "net/http/proxy_client_socket.h"
#include "net/log/net_log_with_source.h"
#include "net/socket/next_proto.h"
#include "net/socket/ssl_client_socket.h"
#include "net/socket/ssl_client_socket_pool.h"
#include "net/socket/transport_client_socket_pool.h"
#include "net/spdy/chromium/spdy_session.h"
namespace net {
class ClientSocketHandle;
class IOBuffer;
class HttpAuthCache;
class HttpResponseInfo;
class HttpStream;
class IOBuffer;
class ProxyDelegate;
class SpdySessionPool;
class SSLClientSocketPool;
class TransportClientSocketPool;
// Class that establishes connections by calling into the lower layer socket
// pools, creates a HttpProxyClientSocket / SpdyProxyClientSocket, and then
// wraps the resulting socket.
//
// This class is needed to handle auth state across multiple connection. On
// auth challenge, this class retains auth state in its AuthController, and can
// either send the auth response to the old connection, or establish a new
// connection and send the response there.
//
// TODO(mmenke): Ideally, we'd have a central location store auth state across
// multiple connections to the same server instead.
class HttpProxyClientSocketWrapper : public ProxyClientSocket {
public:
HttpProxyClientSocketWrapper(
const std::string& group_name,
RequestPriority priority,
ClientSocketPool::RespectLimits respect_limits,
base::TimeDelta connect_timeout_duration,
base::TimeDelta proxy_negotiation_timeout_duration,
TransportClientSocketPool* transport_pool,
SSLClientSocketPool* ssl_pool,
const scoped_refptr<TransportSocketParams>& transport_params,
const scoped_refptr<SSLSocketParams>& ssl_params,
const std::string& user_agent,
const HostPortPair& endpoint,
HttpAuthCache* http_auth_cache,
HttpAuthHandlerFactory* http_auth_handler_factory,
SpdySessionPool* spdy_session_pool,
bool tunnel,
ProxyDelegate* proxy_delegate,
const NetLogWithSource& net_log);
// On destruction Disconnect() is called.
~HttpProxyClientSocketWrapper() override;
// Returns load state while establishing a connection. Returns
// LOAD_STATE_IDLE at other times.
LoadState GetConnectLoadState() const;
std::unique_ptr<HttpResponseInfo> GetAdditionalErrorState();
// ProxyClientSocket implementation.
const HttpResponseInfo* GetConnectResponseInfo() const override;
std::unique_ptr<HttpStream> CreateConnectResponseStream() override;
int RestartWithAuth(const CompletionCallback& callback) override;
const scoped_refptr<HttpAuthController>& GetAuthController() const override;
bool IsUsingSpdy() const override;
NextProto GetProxyNegotiatedProtocol() const override;
// StreamSocket implementation.
int Connect(const CompletionCallback& callback) override;
void Disconnect() override;
bool IsConnected() const override;
bool IsConnectedAndIdle() const override;
const NetLogWithSource& NetLog() const override;
void SetSubresourceSpeculation() override;
void SetOmniboxSpeculation() override;
bool WasEverUsed() const override;
bool WasAlpnNegotiated() const override;
NextProto GetNegotiatedProtocol() const override;
bool GetSSLInfo(SSLInfo* ssl_info) override;
void GetConnectionAttempts(ConnectionAttempts* out) const override;
void ClearConnectionAttempts() override;
void AddConnectionAttempts(const ConnectionAttempts& attempts) override;
int64_t GetTotalReceivedBytes() const override;
// Socket implementation.
int Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) override;
int SetReceiveBufferSize(int32_t size) override;
int SetSendBufferSize(int32_t size) override;
int GetPeerAddress(IPEndPoint* address) const override;
int GetLocalAddress(IPEndPoint* address) const override;
private:
enum State {
STATE_BEGIN_CONNECT,
STATE_TCP_CONNECT,
STATE_TCP_CONNECT_COMPLETE,
STATE_SSL_CONNECT,
STATE_SSL_CONNECT_COMPLETE,
STATE_HTTP_PROXY_CONNECT,
STATE_HTTP_PROXY_CONNECT_COMPLETE,
STATE_SPDY_PROXY_CREATE_STREAM,
STATE_SPDY_PROXY_CREATE_STREAM_COMPLETE,
STATE_SPDY_PROXY_CONNECT_COMPLETE,
STATE_RESTART_WITH_AUTH,
STATE_RESTART_WITH_AUTH_COMPLETE,
STATE_NONE,
};
void OnIOComplete(int result);
// Runs the state transition loop.
int DoLoop(int result);
// Determine if need to go through TCP or SSL path.
int DoBeginConnect();
// Connecting to HTTP Proxy
int DoTransportConnect();
int DoTransportConnectComplete(int result);
// Connecting to HTTPS Proxy
int DoSSLConnect();
int DoSSLConnectComplete(int result);
int DoHttpProxyConnect();
int DoHttpProxyConnectComplete(int result);
int DoSpdyProxyCreateStream();
int DoSpdyProxyCreateStreamComplete(int result);
int DoRestartWithAuth();
int DoRestartWithAuthComplete(int result);
void NotifyProxyDelegateOfCompletion(int result);
void SetConnectTimer(base::TimeDelta duration);
void ConnectTimeout();
const HostResolver::RequestInfo& GetDestination();
State next_state_;
const std::string group_name_;
RequestPriority priority_;
ClientSocketPool::RespectLimits respect_limits_;
const base::TimeDelta connect_timeout_duration_;
const base::TimeDelta proxy_negotiation_timeout_duration_;
TransportClientSocketPool* const transport_pool_;
SSLClientSocketPool* const ssl_pool_;
const scoped_refptr<TransportSocketParams> transport_params_;
const scoped_refptr<SSLSocketParams> ssl_params_;
const std::string user_agent_;
const HostPortPair endpoint_;
SpdySessionPool* const spdy_session_pool_;
bool has_restarted_;
const bool tunnel_;
ProxyDelegate* const proxy_delegate_;
bool using_spdy_;
NextProto negotiated_protocol_;
std::unique_ptr<HttpResponseInfo> error_response_info_;
std::unique_ptr<ClientSocketHandle> transport_socket_handle_;
std::unique_ptr<ProxyClientSocket> transport_socket_;
// Called when a connection is established. Also used when restarting with
// AUTH, which will invoke this when ready to restart, after reconnecting
// if necessary.
CompletionCallback connect_callback_;
SpdyStreamRequest spdy_stream_request_;
scoped_refptr<HttpAuthController> http_auth_controller_;
NetLogWithSource net_log_;
base::OneShotTimer connect_timer_;
// Time when the connection to the proxy was started.
base::TimeTicks connect_start_time_;
DISALLOW_COPY_AND_ASSIGN(HttpProxyClientSocketWrapper);
};
} // namespace net
#endif // NET_HTTP_HTTP_PROXY_CLIENT_SOCKET_WRAPPER_H_
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
2b1da003432d6141acd8b867ca04e2709974f15d | eb20d54d53268637fd3ec43575f30a06f0f02f79 | /antigos/1856.cpp | 3ab2176bc45180d1ec56d2b8fd3c7e6c631659a2 | [] | no_license | biessek/maratona | f934033d8d85eef35fd9e1b19107d850caa25191 | b4b7dcc49ed221203df24c1934ef09b26671c837 | refs/heads/master | 2021-07-04T22:50:22.870648 | 2017-09-28T03:14:29 | 2017-09-28T03:14:29 | 105,094,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,930 | cpp | #include<cstdio>
#include<cmath>
#include<algorithm>
#include<map>
#include<vector>
#include<list>
using namespace std;
typedef pair<int, list<int>::iterator> tupla;
const int MAXTAM = 318;
int N, Q;
map<int, tupla > P;
struct setor {
int q;
list<int>::iterator l,r;
setor() {
q=0;
}
} QTR[MAXTAM];
list<int> A;
void remove(int p) {
tupla q = P[p]; // setor.
QTR[q.first].q--;
int setor = q.first;
if(q.second == QTR[setor].l) {
QTR[setor].l++;
} else if(q.second == QTR[setor].r) {
QTR[setor].r--;
} else {
list<int>::iterator it = QTR[setor].l; it++;
while(it!=QTR[setor].r){
if(*it == p) break;
it++;
}
}
A.erase(q.second);
while(setor+1<MAXTAM && QTR[setor+1].q > 0) {
QTR[setor+1].q--;
QTR[setor].r = QTR[setor+1].l;
P[*QTR[setor].r].first = setor;
QTR[setor+1].l++;
QTR[setor].q++;
if(QTR[setor].q==1) {
QTR[setor].l = QTR[setor].r;
}
setor++;
}
}
void insere(int p, int e) {
int setor = e? P[e].first:0;
list<int>::iterator posicao = e? P[e].second : A.end();
posicao++;
P[p].first = setor;
P[p].second = A.insert(posicao,p);
QTR[setor].q++;
if(QTR[setor].q==1) {
QTR[setor].r = QTR[setor].l = P[p].second;
} else if(e == *QTR[setor].r) {
QTR[setor].r = P[p].second;
}
while(setor+1<MAXTAM && QTR[setor].q >MAXTAM ) {
QTR[setor+1].q++;
QTR[setor+1].l = QTR[setor].r;
P[*QTR[setor].r].first = setor+1;
QTR[setor].r--;
QTR[setor].q--;
if(QTR[setor+1].q==1) {
QTR[setor+1].r = QTR[setor+1].l;
}
setor++;
}
}
int query(int p, int e) {
if(e==p) return 0;
int set1, set2;
set1 = P[p].first;
set2 = P[e].first;
list<int>::iterator l1, l2;
if(set1==set2) {
bool contando = false;
int res=0;
for(l1 = QTR[set1].l;l1!=QTR[set1].r;l1++) {
if(*l1 == p || *l1 == e) {
if(contando) break;
else contando = true;
}
else if(contando) res++;
}
return res;
} else {
if(set2 < set1) { swap(p,e); swap(set2,set1);}
int res=0;
if(QTR[set1].r != P[p].second) {
l1=P[p].second; l1++; l2 = QTR[set1].r; l2++;
while(l1!=l2) { res++; l1++; }
}
if(QTR[set2].l != P[e].second) {
l1=QTR[set2].l; l2 = P[e].second;
while(l1!=l2) { res++; l1++; }
}
set1++; set2;
while(set1<set2) {
res+=QTR[set1++].q;
}
return res;
}
}
// void printsetores() {
// for(int q=0;q<MAXTAM;q++) {
// if(QTR[q].q > 0) {
// printf("setor %d|%d %d = %d\n", q, QTR[q].q, *QTR[q].l,*QTR[q].r);
// }
// }
// puts("ini");
// for(map<int,pair<int,list<int>::iterator> >::iterator it = P.begin();it!=P.end();it++)
// printf("p %d = %d\n", (*it).first, (*it).second.first);
// }
int main() {
int i, p, e;
char op;
fill(QTR,QTR+MAXTAM,setor());
A.clear();
P.clear();
scanf("%d", &N);
for(i=0;i<N;i++) {
scanf("%d", &p);
insere(p, !A.empty()? A.back(): 0);
}
scanf("%d", &Q);
while(Q--) {
scanf(" %c", &op);
if(op == 'I') {
scanf(" %d %d", &p, &e);
insere(p,e);
} else if(op == 'Q') {
scanf(" %d %d", &p, &e);
// printsetores(); puts("res");
printf("%d\n", query(p,e));
} else {
scanf(" %d", &p);
remove(p);
}
// printsetores();
}
// printf("%d\n", P[99999].first);
return 0;
} | [
"root@DESKTOP-V5LA2IB.localdomain"
] | root@DESKTOP-V5LA2IB.localdomain |
64a7d1305dacf856ca1d874e0c957779688299be | 3b6ee14ff27aa37882cee98f16de21daf60f48aa | /DesignWorldApp/MainFrm.h | 4f5390341dfeb93c67d1d165d18066d3208cf88f | [] | no_license | seenunit/DesignWorld | 410aa01c274d9eac04b6ef52222d0273420f960b | 40d311b2ddf4dcc5c555689b3b4bf4a0c97f2c39 | refs/heads/client | 2021-01-18T21:21:03.688005 | 2017-07-01T07:57:19 | 2017-07-01T07:57:19 | 34,983,157 | 3 | 1 | null | 2016-04-04T12:35:26 | 2015-05-03T11:09:04 | C++ | UTF-8 | C++ | false | false | 1,537 | h |
// MainFrm.h : interface of the CMainFrame class
//
#pragma once
#include "FileView.h"
#include "ClassView.h"
#include "OutputWnd.h"
#include "PropertiesWnd.h"
class CMainFrame : public CMDIFrameWndEx
{
DECLARE_DYNAMIC(CMainFrame)
public:
CMainFrame();
// Attributes
public:
// Operations
public:
// Overrides
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual BOOL LoadFrame(UINT nIDResource, DWORD dwDefaultStyle = WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, CWnd* pParentWnd = NULL, CCreateContext* pContext = NULL);
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CMFCMenuBar m_wndMenuBar;
CMFCToolBar m_wndToolBar;
CMFCStatusBar m_wndStatusBar;
CMFCToolBarImages m_UserImages;
CFileView m_wndFileView;
CClassView m_wndClassView;
COutputWnd m_wndOutput;
CPropertiesWnd m_wndProperties;
CMFCToolBar m_ViewToolBar;
// Generated message map functions
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnWindowManager();
afx_msg void OnViewCustomize();
afx_msg LRESULT OnToolbarCreateNew(WPARAM wp, LPARAM lp);
afx_msg void OnApplicationLook(UINT id);
afx_msg void OnUpdateApplicationLook(CCmdUI* pCmdUI);
afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection);
DECLARE_MESSAGE_MAP()
BOOL CreateDockingWindows();
void SetDockingWindowIcons(BOOL bHiColorIcons);
};
| [
"seenunit@gmail.com"
] | seenunit@gmail.com |
eb7c39d6b27d6a3d3e09e4f8d19be20a607a85dd | f615faafdd6120c0bcbe0bea52ad22c8ea26fa13 | /Ja2Project/AssemblyInfo.cpp | 690b29899e76edc39b54e6d8d9b62ba58878520a | [] | no_license | egorovav/Ja2Project | af35304af21c82b4c71eb466b3bdae77fd028be8 | 880bdbcf6eea9692f35a9346de71f20239c279ac | refs/heads/master | 2021-01-19T22:53:28.517555 | 2019-10-24T21:04:20 | 2019-10-24T21:04:20 | 88,882,719 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,254 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute(L"Ja2Project")];
[assembly:AssemblyDescriptionAttribute(L"")];
[assembly:AssemblyConfigurationAttribute(L"")];
[assembly:AssemblyCompanyAttribute(L"")];
[assembly:AssemblyProductAttribute(L"Ja2Project")];
[assembly:AssemblyCopyrightAttribute(L"Copyright (c) 2015")];
[assembly:AssemblyTrademarkAttribute(L"")];
[assembly:AssemblyCultureAttribute(L"")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)]; | [
"egorov_av@mail.ru"
] | egorov_av@mail.ru |
69e6b5607df8ab04cb5284e04d098cdb4a7bc1d5 | 96ab18b237681c5c01bf3d0fce187740e5038bb8 | / asdk/Source2/ATPManager/include/AlgoEngine/AbstractAlgo.h | 8a68a7580ed0028b5c604cf2bee797f9a45c30b8 | [] | no_license | radtek/asdk | 43fd7bfeb31028ef6392be4117e5de4c908af8e5 | 4f9a3bd80f6cc58db02a4ed0f67bc5ee03cedb01 | refs/heads/master | 2020-06-09T04:28:16.485493 | 2012-05-10T10:30:00 | 2012-05-10T10:30:00 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,070 | h | /**
* @copyright 深圳市创真科技有限公司
* @system 宏汇算法交易平台(ATP)
* @brief 算法执行类
* @author 李伟
* @histroy
-------------------------------------------------------------
日期 作者 修改说明
2010-6-2 李伟 创建
-------------------------------------------------------------
*/
#pragma once
#ifndef __ABSTRACTALGO_H_
#define __ABSTRACTALGO_H_
#include "..\\include\\ATSvr\\OpenTDProtocol.h"
#include "..\\include\\ATPSetting\\ATPLogger.h"
class CTradingHandler_Futures;
class CTradingHandler_Security;
#include "AlgoSession.h"
/**
算法执行的接象类
写义了两个接口
#See Begin
#See End
算法需实现上述函数,以完成实际算法的执行.
*/
class AFX_EXT_CLASS CAbstractAlgo : public CObject
{
DECLARE_DYNCREATE(CAbstractAlgo);
public:
/**
任务总数
*/
virtual UINT GetTotal(){ return m_nTotal;}
/**
己任务总数
*/
virtual UINT GetFinish(){return m_nFinish;}
/**
取状态
*/
virtual CString GetStatus(){return m_szStatus;}
/**
取标识名
*/
virtual CString GetRunningAlgoName(){return m_szName;}
public:
/**
算法名称
*/
char m_szName[64];
/**
开始时间
*/
UINT m_nBeginTime;
/**
下单次数
*/
UINT m_nMakeOrderTimes;
/**
己完成数.
*/
UINT m_nFinish;
/**
总数
*/
UINT m_nTotal;
/**
状态说明
*/
char m_szStatus[64];
public:
CAbstractAlgo();
virtual ~CAbstractAlgo();
/**
算法初始化.
@param pParamters 算法参数值首地址.
@param nParams 参数个数
@param strReason 如果初始化失败时,或者参数不正确时,返时出错原因。
@return 返回是否初始化成功,如果初始化成功,算法交易引擎将进一步调用Run函数.
*/
virtual bool Init(ATP_ALGOPARAM_VALUE* pParamters,int nParams,CString& strReason);
/**
具体执行算法,该函数返回后,表示算法退出。算法操作引擎会执行资源的回收工作。
@return 返回退出代码。
*/
virtual int Run(){return 0;}
/**
* 强行终止算法下单.
* 算法应重写此函数,以实现算法的终止运行.结束算法运算,并退出Run函数。
* @return 返回退出代码.
@See Run
*/
virtual int Kill(){return 0;}
protected:
CAlgoSession* m_pAlgoSession;
/*
交易私有日志.
*/
CATPLogger* m_pPrivateLog;
/**
框架在,算法Run之前调用,
如果是股同时将其值传递到成员变量.
*/
virtual void BeforRun(CAlgoSession* pSession,
CATPLogger* pPrivateLog,
CTradingHandler_Security* pHandlerSec,
CTradingHandler_Futures* pHandlerFut);
/**
证券交易指针.
*/
CTradingHandler_Security* m_pTradingHeandleSec;
/**
期货交易指针.
*/
CTradingHandler_Futures* m_pTradingHeandleFut;
friend class CAlgoManager;
friend class CWinThread_ExecAlgo;
};
#endif //__ABSTRACTALGO_H_ | [
"He.Reyter@gmail.com@195b811d-50ba-3ccd-8b31-a51a91d0a79c"
] | He.Reyter@gmail.com@195b811d-50ba-3ccd-8b31-a51a91d0a79c |
ab109e9dfe68883c5f8f7c36015e65a79171791d | 7b6f2cf2b00f21e148662a2d7e2992aaad570bc6 | /Planets.cpp | fbc224653ce52770d7062fd04bfc511202cb7325 | [] | no_license | ScarGarak/cg15 | 794bd92c980c0e7f13897dff8b2ca100259e979a | d57abf67e6fcc29238d5e07053d14c34f9a85154 | refs/heads/master | 2020-04-06T04:48:10.104975 | 2015-07-16T19:53:56 | 2015-07-16T19:55:23 | 37,919,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,370 | cpp | /*
* Planets.cpp
*
* Created on: 29.06.2015
* Author: Oliver Thummerer
*/
#include "Planets.hpp"
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
// constructor
Planet::Planet() {
}
// deconstructor
Planet::~Planet() {
}
// getter
float Planet::getXPos() {
return this->xPos;
}
float Planet::getYPos() {
return this->yPos;
}
float Planet::getZPos() {
return this->zPos;
}
double Planet::getSize() {
return this->size;
}
// setter
void Planet::setXPos(float xPos){
this->xPos = xPos;
}
void Planet::setYPos(float yPos){
this->yPos = yPos;
}
void Planet::setZPos(float zPos){
this->zPos = zPos;
}
// set the sphere color
void Planet::setMaterialColor(int side, double r, double g, double b) {
float amb[4], dif[4], spe[4];
int mat;
dif[0] = r;
dif[1] = g;
dif[2] = b;
for(int i = 0; i < 3; i++) {
amb[i] = .1 * dif[i];
spe[i] = .5;
}
amb[3] = dif[3] = spe[3] = 1.0;
switch(side){
case 1: mat = GL_FRONT;
break;
case 2: mat = GL_BACK;
break;
default: mat = GL_FRONT_AND_BACK;
}
glMaterialfv(mat, GL_AMBIENT, amb);
glMaterialfv(mat, GL_DIFFUSE, dif);
glMaterialfv(mat, GL_SPECULAR, spe);
glMaterialf( mat, GL_SHININESS, 20);
}
// draw a sphere composed of triangles
void Planet::draw(const Vec3& ctr, double r){
this->setMaterialColor(1,0,155,0);
int i, j,
n1 = 6, n2 = 12;
Vec3 normal, v1;
double a1, a1d = M_PI / n1,
a2, a2d = M_PI / n2,
s1, s2,
c1, c2;
glShadeModel(GL_SMOOTH);
for(i = 0; i < n1; i++){
a1 = i * a1d;
glBegin(GL_TRIANGLE_STRIP);
for(j = 0; j <= n2; j++){
a2 = (j + .5 * (i % 2)) * 2 * a2d;
s1 = sin(a1);
c1 = cos(a1);
s2 = sin(a2);
c2 = cos(a2);
normal = c1 * XVec3 + s1 * (c2 * YVec3 + s2 * ZVec3);
v1 = ctr + r * normal;
glNormal3dv(normal.p);
glVertex3dv(v1.p);
s1 = sin(a1 + a1d);
c1 = cos(a1 + a1d);
s2 = sin(a2 + a2d);
c2 = cos(a2 + a2d);
normal = c1 * XVec3 + s1 * (c2 * YVec3 + s2 * ZVec3);
v1 = ctr + r * normal;
glNormal3dv(normal.p);
glVertex3dv(v1.p);
}
glEnd();
}
}
| [
"othummerer@gmx.de"
] | othummerer@gmx.de |
576eaf24837a0be87b3fa02801bff4064e33e4a3 | 24ce63cfba8a5dd2c5ab206963a5760cc42cf4f3 | /SceneObject.hpp | 368b3c3fade5649be4e22080f9e41fd9a6277c55 | [] | no_license | dylanswiggett/raytracer | b79b3283d64f26b4086326dfb195ba45d5137dca | edbc1d76af5093a255bbda26512ab3d2e32971b7 | refs/heads/master | 2020-04-27T00:50:34.594200 | 2014-08-26T04:56:17 | 2014-08-26T04:56:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | hpp | #ifndef _SCENE_OBJECT_HPP_
#define _SCENE_OBJECT_HPP_
#include "Ray.hpp"
#include "Material.hpp"
class SceneObject {
public:
// Attempts to trace the given ray onto this object. If no collision
// occurs, the return value is false. If a collision occurs, a ray
// is returned containing the material values of the object hit, from
// the point of collision and in the direction of the surface normal.
virtual bool raytrace(Ray *ray, Ray *ret) = 0;
virtual Material *getmat() { return &material; };
virtual void setmat(Material m) { material = m; };
protected:
Material material;
};
#endif // _SCENE_OBJECT_HPP_ | [
"dylanswiggett@gmail.com"
] | dylanswiggett@gmail.com |
5011a39e3fea2204fbf6f81870612ec0269f4c72 | 59138b1b34e2a9356ad7154a9705007349209e9a | /platform/JS/V8/v8/test/cctest/test-macro-assembler-mips.cc | c00b8e65a19f7599f373fb524b2ca376929741f8 | [
"BSD-3-Clause",
"bzip2-1.0.6",
"SunPro",
"Apache-2.0"
] | permissive | gboyraz/macchina.io | 6b879fca2329e7060122adfc691b4870d4dc06ac | de79c4d2eace01e24d685ac7f7c2e8aadf6b2668 | refs/heads/master | 2020-06-29T13:18:05.975243 | 2019-08-04T22:43:08 | 2019-08-04T22:43:08 | 200,547,738 | 2 | 0 | Apache-2.0 | 2019-08-04T22:29:19 | 2019-08-04T22:29:19 | null | UTF-8 | C++ | false | false | 57,987 | cc | // Copyright 2013 the V8 project authors. 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 Google 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 <stdlib.h>
#include <iostream> // NOLINT(readability/streams)
#include "src/base/utils/random-number-generator.h"
#include "src/macro-assembler.h"
#include "src/mips/macro-assembler-mips.h"
#include "src/mips/simulator-mips.h"
#include "src/v8.h"
#include "test/cctest/cctest.h"
using namespace v8::internal;
typedef void* (*F)(int x, int y, int p2, int p3, int p4);
typedef Object* (*F1)(int x, int p1, int p2, int p3, int p4);
typedef Object* (*F3)(void* p, int p1, int p2, int p3, int p4);
typedef Object* (*F4)(void* p0, void* p1, int p2, int p3, int p4);
#define __ masm->
TEST(BYTESWAP) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope handles(isolate);
struct T {
int32_t r1;
int32_t r2;
int32_t r3;
int32_t r4;
int32_t r5;
};
T t;
MacroAssembler assembler(isolate, NULL, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assembler;
__ lw(a2, MemOperand(a0, offsetof(T, r1)));
__ nop();
__ ByteSwapSigned(a2, a2, 4);
__ sw(a2, MemOperand(a0, offsetof(T, r1)));
__ lw(a2, MemOperand(a0, offsetof(T, r2)));
__ nop();
__ ByteSwapSigned(a2, a2, 2);
__ sw(a2, MemOperand(a0, offsetof(T, r2)));
__ lw(a2, MemOperand(a0, offsetof(T, r3)));
__ nop();
__ ByteSwapSigned(a2, a2, 1);
__ sw(a2, MemOperand(a0, offsetof(T, r3)));
__ lw(a2, MemOperand(a0, offsetof(T, r4)));
__ nop();
__ ByteSwapUnsigned(a2, a2, 1);
__ sw(a2, MemOperand(a0, offsetof(T, r4)));
__ lw(a2, MemOperand(a0, offsetof(T, r5)));
__ nop();
__ ByteSwapUnsigned(a2, a2, 2);
__ sw(a2, MemOperand(a0, offsetof(T, r5)));
__ jr(ra);
__ nop();
CodeDesc desc;
masm->GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
::F3 f = FUNCTION_CAST<::F3>(code->entry());
t.r1 = 0x781A15C3;
t.r2 = 0x2CDE;
t.r3 = 0x9F;
t.r4 = 0x9F;
t.r5 = 0x2CDE;
Object* dummy = CALL_GENERATED_CODE(isolate, f, &t, 0, 0, 0, 0);
USE(dummy);
CHECK_EQ(static_cast<int32_t>(0xC3151A78), t.r1);
CHECK_EQ(static_cast<int32_t>(0xDE2C0000), t.r2);
CHECK_EQ(static_cast<int32_t>(0x9FFFFFFF), t.r3);
CHECK_EQ(static_cast<int32_t>(0x9F000000), t.r4);
CHECK_EQ(static_cast<int32_t>(0xDE2C0000), t.r5);
}
static void TestNaN(const char *code) {
// NaN value is different on MIPS and x86 architectures, and TEST(NaNx)
// tests checks the case where a x86 NaN value is serialized into the
// snapshot on the simulator during cross compilation.
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::Context> context = CcTest::NewContext(PRINT_EXTENSION);
v8::Context::Scope context_scope(context);
v8::Local<v8::Script> script =
v8::Script::Compile(context, v8_str(code)).ToLocalChecked();
v8::Local<v8::Object> result =
v8::Local<v8::Object>::Cast(script->Run(context).ToLocalChecked());
i::Handle<i::JSReceiver> o = v8::Utils::OpenHandle(*result);
i::Handle<i::JSArray> array1(reinterpret_cast<i::JSArray*>(*o));
i::FixedDoubleArray* a = i::FixedDoubleArray::cast(array1->elements());
double value = a->get_scalar(0);
CHECK(std::isnan(value) &&
bit_cast<uint64_t>(value) ==
bit_cast<uint64_t>(std::numeric_limits<double>::quiet_NaN()));
}
TEST(NaN0) {
TestNaN(
"var result;"
"for (var i = 0; i < 2; i++) {"
" result = new Array(Number.NaN, Number.POSITIVE_INFINITY);"
"}"
"result;");
}
TEST(NaN1) {
TestNaN(
"var result;"
"for (var i = 0; i < 2; i++) {"
" result = [NaN];"
"}"
"result;");
}
TEST(jump_tables4) {
// Similar to test-assembler-mips jump_tables1, with extra test for branch
// trampoline required before emission of the dd table (where trampolines are
// blocked), and proper transition to long-branch mode.
// Regression test for v8:4294.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assembler(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assembler;
const int kNumCases = 512;
int values[kNumCases];
isolate->random_number_generator()->NextBytes(values, sizeof(values));
Label labels[kNumCases];
Label near_start, end, done;
__ Push(ra);
__ mov(v0, zero_reg);
__ Branch(&end);
__ bind(&near_start);
// Generate slightly less than 32K instructions, which will soon require
// trampoline for branch distance fixup.
for (int i = 0; i < 32768 - 256; ++i) {
__ addiu(v0, v0, 1);
}
__ GenerateSwitchTable(a0, kNumCases,
[&labels](size_t i) { return labels + i; });
for (int i = 0; i < kNumCases; ++i) {
__ bind(&labels[i]);
__ li(v0, values[i]);
__ Branch(&done);
}
__ bind(&done);
__ Pop(ra);
__ jr(ra);
__ nop();
__ bind(&end);
__ Branch(&near_start);
CodeDesc desc;
masm->GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
F1 f = FUNCTION_CAST<F1>(code->entry());
for (int i = 0; i < kNumCases; ++i) {
int res =
reinterpret_cast<int>(CALL_GENERATED_CODE(isolate, f, i, 0, 0, 0, 0));
::printf("f(%d) = %d\n", i, res);
CHECK_EQ(values[i], res);
}
}
TEST(jump_tables5) {
if (!IsMipsArchVariant(kMips32r6)) return;
// Similar to test-assembler-mips jump_tables1, with extra test for emitting a
// compact branch instruction before emission of the dd table.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assembler(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assembler;
const int kNumCases = 512;
int values[kNumCases];
isolate->random_number_generator()->NextBytes(values, sizeof(values));
Label labels[kNumCases];
Label done;
__ Push(ra);
{
__ BlockTrampolinePoolFor(kNumCases + 6 + 1);
PredictableCodeSizeScope predictable(
masm, kNumCases * kPointerSize + ((6 + 1) * Assembler::kInstrSize));
__ addiupc(at, 6 + 1);
__ Lsa(at, at, a0, 2);
__ lw(at, MemOperand(at));
__ jalr(at);
__ nop(); // Branch delay slot nop.
__ bc(&done);
// A nop instruction must be generated by the forbidden slot guard
// (Assembler::dd(Label*)).
for (int i = 0; i < kNumCases; ++i) {
__ dd(&labels[i]);
}
}
for (int i = 0; i < kNumCases; ++i) {
__ bind(&labels[i]);
__ li(v0, values[i]);
__ jr(ra);
__ nop();
}
__ bind(&done);
__ Pop(ra);
__ jr(ra);
__ nop();
CodeDesc desc;
masm->GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
F1 f = FUNCTION_CAST<F1>(code->entry());
for (int i = 0; i < kNumCases; ++i) {
int32_t res = reinterpret_cast<int32_t>(
CALL_GENERATED_CODE(isolate, f, i, 0, 0, 0, 0));
::printf("f(%d) = %d\n", i, res);
CHECK_EQ(values[i], res);
}
}
TEST(jump_tables6) {
// Similar to test-assembler-mips jump_tables1, with extra test for branch
// trampoline required after emission of the dd table (where trampolines are
// blocked). This test checks if number of really generated instructions is
// greater than number of counted instructions from code, as we are expecting
// generation of trampoline in this case (when number of kFillInstr
// instructions is close to 32K)
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assembler(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assembler;
const int kSwitchTableCases = 40;
const int kInstrSize = Assembler::kInstrSize;
const int kMaxBranchOffset = Assembler::kMaxBranchOffset;
const int kTrampolineSlotsSize = Assembler::kTrampolineSlotsSize;
const int kSwitchTablePrologueSize = MacroAssembler::kSwitchTablePrologueSize;
const int kMaxOffsetForTrampolineStart =
kMaxBranchOffset - 16 * kTrampolineSlotsSize;
const int kFillInstr = (kMaxOffsetForTrampolineStart / kInstrSize) -
(kSwitchTablePrologueSize + kSwitchTableCases) - 20;
int values[kSwitchTableCases];
isolate->random_number_generator()->NextBytes(values, sizeof(values));
Label labels[kSwitchTableCases];
Label near_start, end, done;
__ Push(ra);
__ mov(v0, zero_reg);
int offs1 = masm->pc_offset();
int gen_insn = 0;
__ Branch(&end);
gen_insn += Assembler::IsCompactBranchSupported() ? 1 : 2;
__ bind(&near_start);
// Generate slightly less than 32K instructions, which will soon require
// trampoline for branch distance fixup.
for (int i = 0; i < kFillInstr; ++i) {
__ addiu(v0, v0, 1);
}
gen_insn += kFillInstr;
__ GenerateSwitchTable(a0, kSwitchTableCases,
[&labels](size_t i) { return labels + i; });
gen_insn += (kSwitchTablePrologueSize + kSwitchTableCases);
for (int i = 0; i < kSwitchTableCases; ++i) {
__ bind(&labels[i]);
__ li(v0, values[i]);
__ Branch(&done);
}
gen_insn +=
((Assembler::IsCompactBranchSupported() ? 3 : 4) * kSwitchTableCases);
// If offset from here to first branch instr is greater than max allowed
// offset for trampoline ...
CHECK_LT(kMaxOffsetForTrampolineStart, masm->pc_offset() - offs1);
// ... number of generated instructions must be greater then "gen_insn",
// as we are expecting trampoline generation
CHECK_LT(gen_insn, (masm->pc_offset() - offs1) / kInstrSize);
__ bind(&done);
__ Pop(ra);
__ jr(ra);
__ nop();
__ bind(&end);
__ Branch(&near_start);
CodeDesc desc;
masm->GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
#ifdef OBJECT_PRINT
code->Print(std::cout);
#endif
F1 f = FUNCTION_CAST<F1>(code->entry());
for (int i = 0; i < kSwitchTableCases; ++i) {
int res =
reinterpret_cast<int>(CALL_GENERATED_CODE(isolate, f, i, 0, 0, 0, 0));
::printf("f(%d) = %d\n", i, res);
CHECK_EQ(values[i], res);
}
}
static uint32_t run_lsa(uint32_t rt, uint32_t rs, int8_t sa) {
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assembler(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assembler;
__ Lsa(v0, a0, a1, sa);
__ jr(ra);
__ nop();
CodeDesc desc;
assembler.GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
F1 f = FUNCTION_CAST<F1>(code->entry());
uint32_t res = reinterpret_cast<uint32_t>(
CALL_GENERATED_CODE(isolate, f, rt, rs, 0, 0, 0));
return res;
}
TEST(Lsa) {
CcTest::InitializeVM();
struct TestCaseLsa {
int32_t rt;
int32_t rs;
uint8_t sa;
uint32_t expected_res;
};
struct TestCaseLsa tc[] = {// rt, rs, sa, expected_res
{0x4, 0x1, 1, 0x6},
{0x4, 0x1, 2, 0x8},
{0x4, 0x1, 3, 0xc},
{0x4, 0x1, 4, 0x14},
{0x4, 0x1, 5, 0x24},
{0x0, 0x1, 1, 0x2},
{0x0, 0x1, 2, 0x4},
{0x0, 0x1, 3, 0x8},
{0x0, 0x1, 4, 0x10},
{0x0, 0x1, 5, 0x20},
{0x4, 0x0, 1, 0x4},
{0x4, 0x0, 2, 0x4},
{0x4, 0x0, 3, 0x4},
{0x4, 0x0, 4, 0x4},
{0x4, 0x0, 5, 0x4},
// Shift overflow.
{0x4, INT32_MAX, 1, 0x2},
{0x4, INT32_MAX >> 1, 2, 0x0},
{0x4, INT32_MAX >> 2, 3, 0xfffffffc},
{0x4, INT32_MAX >> 3, 4, 0xfffffff4},
{0x4, INT32_MAX >> 4, 5, 0xffffffe4},
// Signed addition overflow.
{INT32_MAX - 1, 0x1, 1, 0x80000000},
{INT32_MAX - 3, 0x1, 2, 0x80000000},
{INT32_MAX - 7, 0x1, 3, 0x80000000},
{INT32_MAX - 15, 0x1, 4, 0x80000000},
{INT32_MAX - 31, 0x1, 5, 0x80000000},
// Addition overflow.
{-2, 0x1, 1, 0x0},
{-4, 0x1, 2, 0x0},
{-8, 0x1, 3, 0x0},
{-16, 0x1, 4, 0x0},
{-32, 0x1, 5, 0x0}};
size_t nr_test_cases = sizeof(tc) / sizeof(TestCaseLsa);
for (size_t i = 0; i < nr_test_cases; ++i) {
uint32_t res = run_lsa(tc[i].rt, tc[i].rs, tc[i].sa);
PrintF("0x%x =? 0x%x == lsa(v0, %x, %x, %hhu)\n", tc[i].expected_res, res,
tc[i].rt, tc[i].rs, tc[i].sa);
CHECK_EQ(tc[i].expected_res, res);
}
}
static const std::vector<uint32_t> cvt_trunc_uint32_test_values() {
static const uint32_t kValues[] = {0x00000000, 0x00000001, 0x00ffff00,
0x7fffffff, 0x80000000, 0x80000001,
0x80ffff00, 0x8fffffff, 0xffffffff};
return std::vector<uint32_t>(&kValues[0], &kValues[arraysize(kValues)]);
}
static const std::vector<int32_t> cvt_trunc_int32_test_values() {
static const int32_t kValues[] = {
static_cast<int32_t>(0x00000000), static_cast<int32_t>(0x00000001),
static_cast<int32_t>(0x00ffff00), static_cast<int32_t>(0x7fffffff),
static_cast<int32_t>(0x80000000), static_cast<int32_t>(0x80000001),
static_cast<int32_t>(0x80ffff00), static_cast<int32_t>(0x8fffffff),
static_cast<int32_t>(0xffffffff)};
return std::vector<int32_t>(&kValues[0], &kValues[arraysize(kValues)]);
}
// Helper macros that can be used in FOR_INT32_INPUTS(i) { ... *i ... }
#define FOR_INPUTS(ctype, itype, var, test_vector) \
std::vector<ctype> var##_vec = test_vector(); \
for (std::vector<ctype>::iterator var = var##_vec.begin(); \
var != var##_vec.end(); ++var)
#define FOR_INPUTS2(ctype, itype, var, var2, test_vector) \
std::vector<ctype> var##_vec = test_vector(); \
std::vector<ctype>::iterator var; \
std::vector<ctype>::reverse_iterator var2; \
for (var = var##_vec.begin(), var2 = var##_vec.rbegin(); \
var != var##_vec.end(); ++var, ++var2)
#define FOR_ENUM_INPUTS(var, type, test_vector) \
FOR_INPUTS(enum type, type, var, test_vector)
#define FOR_STRUCT_INPUTS(var, type, test_vector) \
FOR_INPUTS(struct type, type, var, test_vector)
#define FOR_UINT32_INPUTS(var, test_vector) \
FOR_INPUTS(uint32_t, uint32, var, test_vector)
#define FOR_INT32_INPUTS(var, test_vector) \
FOR_INPUTS(int32_t, int32, var, test_vector)
#define FOR_INT32_INPUTS2(var, var2, test_vector) \
FOR_INPUTS2(int32_t, int32, var, var2, test_vector)
#define FOR_UINT64_INPUTS(var, test_vector) \
FOR_INPUTS(uint64_t, uint32, var, test_vector)
template <typename RET_TYPE, typename IN_TYPE, typename Func>
RET_TYPE run_Cvt(IN_TYPE x, Func GenerateConvertInstructionFunc) {
typedef RET_TYPE (*F_CVT)(IN_TYPE x0, int x1, int x2, int x3, int x4);
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assm;
__ mtc1(a0, f4);
GenerateConvertInstructionFunc(masm);
__ mfc1(v0, f2);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
F_CVT f = FUNCTION_CAST<F_CVT>(code->entry());
return reinterpret_cast<RET_TYPE>(
CALL_GENERATED_CODE(isolate, f, x, 0, 0, 0, 0));
}
TEST(cvt_s_w_Trunc_uw_s) {
CcTest::InitializeVM();
FOR_UINT32_INPUTS(i, cvt_trunc_uint32_test_values) {
uint32_t input = *i;
auto fn = [](MacroAssembler* masm) {
__ cvt_s_w(f0, f4);
__ Trunc_uw_s(f2, f0, f6);
};
CHECK_EQ(static_cast<float>(input), run_Cvt<uint32_t>(input, fn));
}
}
TEST(cvt_d_w_Trunc_w_d) {
CcTest::InitializeVM();
FOR_INT32_INPUTS(i, cvt_trunc_int32_test_values) {
int32_t input = *i;
auto fn = [](MacroAssembler* masm) {
__ cvt_d_w(f0, f4);
__ Trunc_w_d(f2, f0);
};
CHECK_EQ(static_cast<double>(input), run_Cvt<int32_t>(input, fn));
}
}
static const std::vector<int32_t> overflow_int32_test_values() {
static const int32_t kValues[] = {
static_cast<int32_t>(0xf0000000), static_cast<int32_t>(0x00000001),
static_cast<int32_t>(0xff000000), static_cast<int32_t>(0x0000f000),
static_cast<int32_t>(0x0f000000), static_cast<int32_t>(0x991234ab),
static_cast<int32_t>(0xb0ffff01), static_cast<int32_t>(0x00006fff),
static_cast<int32_t>(0xffffffff)};
return std::vector<int32_t>(&kValues[0], &kValues[arraysize(kValues)]);
}
enum OverflowBranchType {
kAddBranchOverflow,
kSubBranchOverflow,
};
struct OverflowRegisterCombination {
Register dst;
Register left;
Register right;
Register scratch;
};
static const std::vector<enum OverflowBranchType> overflow_branch_type() {
static const enum OverflowBranchType kValues[] = {kAddBranchOverflow,
kSubBranchOverflow};
return std::vector<enum OverflowBranchType>(&kValues[0],
&kValues[arraysize(kValues)]);
}
static const std::vector<struct OverflowRegisterCombination>
overflow_register_combination() {
static const struct OverflowRegisterCombination kValues[] = {
{t0, t1, t2, t3}, {t0, t0, t2, t3}, {t0, t1, t0, t3}, {t0, t1, t1, t3}};
return std::vector<struct OverflowRegisterCombination>(
&kValues[0], &kValues[arraysize(kValues)]);
}
template <typename T>
static bool IsAddOverflow(T x, T y) {
DCHECK(std::numeric_limits<T>::is_integer);
T max = std::numeric_limits<T>::max();
T min = std::numeric_limits<T>::min();
return (x > 0 && y > (max - x)) || (x < 0 && y < (min - x));
}
template <typename T>
static bool IsSubOverflow(T x, T y) {
DCHECK(std::numeric_limits<T>::is_integer);
T max = std::numeric_limits<T>::max();
T min = std::numeric_limits<T>::min();
return (y > 0 && x < (min + y)) || (y < 0 && x > (max + y));
}
template <typename IN_TYPE, typename Func>
static bool runOverflow(IN_TYPE valLeft, IN_TYPE valRight,
Func GenerateOverflowInstructions) {
typedef int32_t (*F_CVT)(char* x0, int x1, int x2, int x3, int x4);
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assm;
GenerateOverflowInstructions(masm, valLeft, valRight);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
F_CVT f = FUNCTION_CAST<F_CVT>(code->entry());
int32_t r =
reinterpret_cast<int32_t>(CALL_GENERATED_CODE(isolate, f, 0, 0, 0, 0, 0));
DCHECK(r == 0 || r == 1);
return r;
}
TEST(BranchOverflowInt32BothLabelsTrampoline) {
if (!IsMipsArchVariant(kMips32r6)) return;
static const int kMaxBranchOffset = (1 << (18 - 1)) - 1;
FOR_INT32_INPUTS(i, overflow_int32_test_values) {
FOR_INT32_INPUTS(j, overflow_int32_test_values) {
FOR_ENUM_INPUTS(br, OverflowBranchType, overflow_branch_type) {
FOR_STRUCT_INPUTS(regComb, OverflowRegisterCombination,
overflow_register_combination) {
int32_t ii = *i;
int32_t jj = *j;
enum OverflowBranchType branchType = *br;
struct OverflowRegisterCombination rc = *regComb;
// If left and right register are same then left and right
// test values must also be same, otherwise we skip the test
if (rc.left.code() == rc.right.code()) {
if (ii != jj) {
continue;
}
}
bool res1 = runOverflow<int32_t>(
ii, jj, [branchType, rc](MacroAssembler* masm, int32_t valLeft,
int32_t valRight) {
Label overflow, no_overflow, end;
__ li(rc.left, valLeft);
__ li(rc.right, valRight);
switch (branchType) {
case kAddBranchOverflow:
__ AddBranchOvf(rc.dst, rc.left, rc.right, &overflow,
&no_overflow, rc.scratch);
break;
case kSubBranchOverflow:
__ SubBranchOvf(rc.dst, rc.left, rc.right, &overflow,
&no_overflow, rc.scratch);
break;
}
Label done;
size_t nr_calls =
kMaxBranchOffset / (2 * Instruction::kInstrSize) + 2;
for (size_t i = 0; i < nr_calls; ++i) {
__ BranchShort(&done, eq, a0, Operand(a1));
}
__ bind(&done);
__ li(v0, 2);
__ Branch(&end);
__ bind(&overflow);
__ li(v0, 1);
__ Branch(&end);
__ bind(&no_overflow);
__ li(v0, 0);
__ bind(&end);
});
switch (branchType) {
case kAddBranchOverflow:
CHECK_EQ(IsAddOverflow<int32_t>(ii, jj), res1);
break;
case kSubBranchOverflow:
CHECK_EQ(IsSubOverflow<int32_t>(ii, jj), res1);
break;
default:
UNREACHABLE();
}
}
}
}
}
}
TEST(BranchOverflowInt32BothLabels) {
FOR_INT32_INPUTS(i, overflow_int32_test_values) {
FOR_INT32_INPUTS(j, overflow_int32_test_values) {
FOR_ENUM_INPUTS(br, OverflowBranchType, overflow_branch_type) {
FOR_STRUCT_INPUTS(regComb, OverflowRegisterCombination,
overflow_register_combination) {
int32_t ii = *i;
int32_t jj = *j;
enum OverflowBranchType branchType = *br;
struct OverflowRegisterCombination rc = *regComb;
// If left and right register are same then left and right
// test values must also be same, otherwise we skip the test
if (rc.left.code() == rc.right.code()) {
if (ii != jj) {
continue;
}
}
bool res1 = runOverflow<int32_t>(
ii, jj, [branchType, rc](MacroAssembler* masm, int32_t valLeft,
int32_t valRight) {
Label overflow, no_overflow, end;
__ li(rc.left, valLeft);
__ li(rc.right, valRight);
switch (branchType) {
case kAddBranchOverflow:
__ AddBranchOvf(rc.dst, rc.left, rc.right, &overflow,
&no_overflow, rc.scratch);
break;
case kSubBranchOverflow:
__ SubBranchOvf(rc.dst, rc.left, rc.right, &overflow,
&no_overflow, rc.scratch);
break;
}
__ li(v0, 2);
__ Branch(&end);
__ bind(&overflow);
__ li(v0, 1);
__ Branch(&end);
__ bind(&no_overflow);
__ li(v0, 0);
__ bind(&end);
});
bool res2 = runOverflow<int32_t>(
ii, jj, [branchType, rc](MacroAssembler* masm, int32_t valLeft,
int32_t valRight) {
Label overflow, no_overflow, end;
__ li(rc.left, valLeft);
switch (branchType) {
case kAddBranchOverflow:
__ AddBranchOvf(rc.dst, rc.left, Operand(valRight),
&overflow, &no_overflow, rc.scratch);
break;
case kSubBranchOverflow:
__ SubBranchOvf(rc.dst, rc.left, Operand(valRight),
&overflow, &no_overflow, rc.scratch);
break;
}
__ li(v0, 2);
__ Branch(&end);
__ bind(&overflow);
__ li(v0, 1);
__ Branch(&end);
__ bind(&no_overflow);
__ li(v0, 0);
__ bind(&end);
});
switch (branchType) {
case kAddBranchOverflow:
CHECK_EQ(IsAddOverflow<int32_t>(ii, jj), res1);
CHECK_EQ(IsAddOverflow<int32_t>(ii, jj), res2);
break;
case kSubBranchOverflow:
CHECK_EQ(IsSubOverflow<int32_t>(ii, jj), res1);
CHECK_EQ(IsSubOverflow<int32_t>(ii, jj), res2);
break;
default:
UNREACHABLE();
}
}
}
}
}
}
TEST(BranchOverflowInt32LeftLabel) {
FOR_INT32_INPUTS(i, overflow_int32_test_values) {
FOR_INT32_INPUTS(j, overflow_int32_test_values) {
FOR_ENUM_INPUTS(br, OverflowBranchType, overflow_branch_type) {
FOR_STRUCT_INPUTS(regComb, OverflowRegisterCombination,
overflow_register_combination) {
int32_t ii = *i;
int32_t jj = *j;
enum OverflowBranchType branchType = *br;
struct OverflowRegisterCombination rc = *regComb;
// If left and right register are same then left and right
// test values must also be same, otherwise we skip the test
if (rc.left.code() == rc.right.code()) {
if (ii != jj) {
continue;
}
}
bool res1 = runOverflow<int32_t>(
ii, jj, [branchType, rc](MacroAssembler* masm, int32_t valLeft,
int32_t valRight) {
Label overflow, end;
__ li(rc.left, valLeft);
__ li(rc.right, valRight);
switch (branchType) {
case kAddBranchOverflow:
__ AddBranchOvf(rc.dst, rc.left, rc.right, &overflow, NULL,
rc.scratch);
break;
case kSubBranchOverflow:
__ SubBranchOvf(rc.dst, rc.left, rc.right, &overflow, NULL,
rc.scratch);
break;
}
__ li(v0, 0);
__ Branch(&end);
__ bind(&overflow);
__ li(v0, 1);
__ bind(&end);
});
bool res2 = runOverflow<int32_t>(
ii, jj, [branchType, rc](MacroAssembler* masm, int32_t valLeft,
int32_t valRight) {
Label overflow, end;
__ li(rc.left, valLeft);
switch (branchType) {
case kAddBranchOverflow:
__ AddBranchOvf(rc.dst, rc.left, Operand(valRight),
&overflow, NULL, rc.scratch);
break;
case kSubBranchOverflow:
__ SubBranchOvf(rc.dst, rc.left, Operand(valRight),
&overflow, NULL, rc.scratch);
break;
}
__ li(v0, 0);
__ Branch(&end);
__ bind(&overflow);
__ li(v0, 1);
__ bind(&end);
});
switch (branchType) {
case kAddBranchOverflow:
CHECK_EQ(IsAddOverflow<int32_t>(ii, jj), res1);
CHECK_EQ(IsAddOverflow<int32_t>(ii, jj), res2);
break;
case kSubBranchOverflow:
CHECK_EQ(IsSubOverflow<int32_t>(ii, jj), res1);
CHECK_EQ(IsSubOverflow<int32_t>(ii, jj), res2);
break;
default:
UNREACHABLE();
}
}
}
}
}
}
TEST(BranchOverflowInt32RightLabel) {
FOR_INT32_INPUTS(i, overflow_int32_test_values) {
FOR_INT32_INPUTS(j, overflow_int32_test_values) {
FOR_ENUM_INPUTS(br, OverflowBranchType, overflow_branch_type) {
FOR_STRUCT_INPUTS(regComb, OverflowRegisterCombination,
overflow_register_combination) {
int32_t ii = *i;
int32_t jj = *j;
enum OverflowBranchType branchType = *br;
struct OverflowRegisterCombination rc = *regComb;
// If left and right register are same then left and right
// test values must also be same, otherwise we skip the test
if (rc.left.code() == rc.right.code()) {
if (ii != jj) {
continue;
}
}
bool res1 = runOverflow<int32_t>(
ii, jj, [branchType, rc](MacroAssembler* masm, int32_t valLeft,
int32_t valRight) {
Label no_overflow, end;
__ li(rc.left, valLeft);
__ li(rc.right, valRight);
switch (branchType) {
case kAddBranchOverflow:
__ AddBranchOvf(rc.dst, rc.left, rc.right, NULL,
&no_overflow, rc.scratch);
break;
case kSubBranchOverflow:
__ SubBranchOvf(rc.dst, rc.left, rc.right, NULL,
&no_overflow, rc.scratch);
break;
}
__ li(v0, 1);
__ Branch(&end);
__ bind(&no_overflow);
__ li(v0, 0);
__ bind(&end);
});
bool res2 = runOverflow<int32_t>(
ii, jj, [branchType, rc](MacroAssembler* masm, int32_t valLeft,
int32_t valRight) {
Label no_overflow, end;
__ li(rc.left, valLeft);
switch (branchType) {
case kAddBranchOverflow:
__ AddBranchOvf(rc.dst, rc.left, Operand(valRight), NULL,
&no_overflow, rc.scratch);
break;
case kSubBranchOverflow:
__ SubBranchOvf(rc.dst, rc.left, Operand(valRight), NULL,
&no_overflow, rc.scratch);
break;
}
__ li(v0, 1);
__ Branch(&end);
__ bind(&no_overflow);
__ li(v0, 0);
__ bind(&end);
});
switch (branchType) {
case kAddBranchOverflow:
CHECK_EQ(IsAddOverflow<int32_t>(ii, jj), res1);
CHECK_EQ(IsAddOverflow<int32_t>(ii, jj), res2);
break;
case kSubBranchOverflow:
CHECK_EQ(IsSubOverflow<int32_t>(ii, jj), res1);
CHECK_EQ(IsSubOverflow<int32_t>(ii, jj), res2);
break;
default:
UNREACHABLE();
}
}
}
}
}
}
TEST(min_max_nan) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assembler(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assembler;
struct TestFloat {
double a;
double b;
double c;
double d;
float e;
float f;
float g;
float h;
};
TestFloat test;
const double dnan = std::numeric_limits<double>::quiet_NaN();
const double dinf = std::numeric_limits<double>::infinity();
const double dminf = -std::numeric_limits<double>::infinity();
const float fnan = std::numeric_limits<float>::quiet_NaN();
const float finf = std::numeric_limits<float>::infinity();
const float fminf = std::numeric_limits<float>::infinity();
const int kTableLength = 13;
double inputsa[kTableLength] = {2.0, 3.0, -0.0, 0.0, 42.0, dinf, dminf,
dinf, dnan, 3.0, dinf, dnan, dnan};
double inputsb[kTableLength] = {3.0, 2.0, 0.0, -0.0, dinf, 42.0, dinf,
dminf, 3.0, dnan, dnan, dinf, dnan};
double outputsdmin[kTableLength] = {2.0, 2.0, -0.0, -0.0, 42.0,
42.0, dminf, dminf, dnan, dnan,
dnan, dnan, dnan};
double outputsdmax[kTableLength] = {3.0, 3.0, 0.0, 0.0, dinf, dinf, dinf,
dinf, dnan, dnan, dnan, dnan, dnan};
float inputse[kTableLength] = {2.0, 3.0, -0.0, 0.0, 42.0, finf, fminf,
finf, fnan, 3.0, finf, fnan, fnan};
float inputsf[kTableLength] = {3.0, 2.0, 0.0, -0.0, finf, 42.0, finf,
fminf, 3.0, fnan, fnan, finf, fnan};
float outputsfmin[kTableLength] = {2.0, 2.0, -0.0, -0.0, 42.0, 42.0, fminf,
fminf, fnan, fnan, fnan, fnan, fnan};
float outputsfmax[kTableLength] = {3.0, 3.0, 0.0, 0.0, finf, finf, finf,
finf, fnan, fnan, fnan, fnan, fnan};
auto handle_dnan = [masm](FPURegister dst, Label* nan, Label* back) {
__ bind(nan);
__ LoadRoot(t8, Heap::kNanValueRootIndex);
__ Ldc1(dst, FieldMemOperand(t8, HeapNumber::kValueOffset));
__ Branch(back);
};
auto handle_snan = [masm, fnan](FPURegister dst, Label* nan, Label* back) {
__ bind(nan);
__ Move(dst, fnan);
__ Branch(back);
};
Label handle_mind_nan, handle_maxd_nan, handle_mins_nan, handle_maxs_nan;
Label back_mind_nan, back_maxd_nan, back_mins_nan, back_maxs_nan;
__ push(s6);
__ InitializeRootRegister();
__ Ldc1(f4, MemOperand(a0, offsetof(TestFloat, a)));
__ Ldc1(f8, MemOperand(a0, offsetof(TestFloat, b)));
__ lwc1(f2, MemOperand(a0, offsetof(TestFloat, e)));
__ lwc1(f6, MemOperand(a0, offsetof(TestFloat, f)));
__ Float64Min(f10, f4, f8, &handle_mind_nan);
__ bind(&back_mind_nan);
__ Float64Max(f12, f4, f8, &handle_maxd_nan);
__ bind(&back_maxd_nan);
__ Float32Min(f14, f2, f6, &handle_mins_nan);
__ bind(&back_mins_nan);
__ Float32Max(f16, f2, f6, &handle_maxs_nan);
__ bind(&back_maxs_nan);
__ Sdc1(f10, MemOperand(a0, offsetof(TestFloat, c)));
__ Sdc1(f12, MemOperand(a0, offsetof(TestFloat, d)));
__ swc1(f14, MemOperand(a0, offsetof(TestFloat, g)));
__ swc1(f16, MemOperand(a0, offsetof(TestFloat, h)));
__ pop(s6);
__ jr(ra);
__ nop();
handle_dnan(f10, &handle_mind_nan, &back_mind_nan);
handle_dnan(f12, &handle_maxd_nan, &back_maxd_nan);
handle_snan(f14, &handle_mins_nan, &back_mins_nan);
handle_snan(f16, &handle_maxs_nan, &back_maxs_nan);
CodeDesc desc;
masm->GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
::F3 f = FUNCTION_CAST<::F3>(code->entry());
for (int i = 0; i < kTableLength; i++) {
test.a = inputsa[i];
test.b = inputsb[i];
test.e = inputse[i];
test.f = inputsf[i];
CALL_GENERATED_CODE(isolate, f, &test, 0, 0, 0, 0);
CHECK_EQ(0, memcmp(&test.c, &outputsdmin[i], sizeof(test.c)));
CHECK_EQ(0, memcmp(&test.d, &outputsdmax[i], sizeof(test.d)));
CHECK_EQ(0, memcmp(&test.g, &outputsfmin[i], sizeof(test.g)));
CHECK_EQ(0, memcmp(&test.h, &outputsfmax[i], sizeof(test.h)));
}
}
template <typename IN_TYPE, typename Func>
bool run_Unaligned(char* memory_buffer, int32_t in_offset, int32_t out_offset,
IN_TYPE value, Func GenerateUnalignedInstructionFunc) {
typedef int32_t (*F_CVT)(char* x0, int x1, int x2, int x3, int x4);
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assm;
IN_TYPE res;
GenerateUnalignedInstructionFunc(masm, in_offset, out_offset);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
F_CVT f = FUNCTION_CAST<F_CVT>(code->entry());
MemCopy(memory_buffer + in_offset, &value, sizeof(IN_TYPE));
CALL_GENERATED_CODE(isolate, f, memory_buffer, 0, 0, 0, 0);
MemCopy(&res, memory_buffer + out_offset, sizeof(IN_TYPE));
return res == value;
}
static const std::vector<uint64_t> unsigned_test_values() {
static const uint64_t kValues[] = {
0x2180f18a06384414, 0x000a714532102277, 0xbc1acccf180649f0,
0x8000000080008000, 0x0000000000000001, 0xffffffffffffffff,
};
return std::vector<uint64_t>(&kValues[0], &kValues[arraysize(kValues)]);
}
static const std::vector<int32_t> unsigned_test_offset() {
static const int32_t kValues[] = {// value, offset
-132 * KB, -21 * KB, 0, 19 * KB, 135 * KB};
return std::vector<int32_t>(&kValues[0], &kValues[arraysize(kValues)]);
}
static const std::vector<int32_t> unsigned_test_offset_increment() {
static const int32_t kValues[] = {-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5};
return std::vector<int32_t>(&kValues[0], &kValues[arraysize(kValues)]);
}
TEST(Ulh) {
CcTest::InitializeVM();
static const int kBufferSize = 300 * KB;
char memory_buffer[kBufferSize];
char* buffer_middle = memory_buffer + (kBufferSize / 2);
FOR_UINT64_INPUTS(i, unsigned_test_values) {
FOR_INT32_INPUTS2(j1, j2, unsigned_test_offset) {
FOR_INT32_INPUTS2(k1, k2, unsigned_test_offset_increment) {
uint16_t value = static_cast<uint64_t>(*i & 0xFFFF);
int32_t in_offset = *j1 + *k1;
int32_t out_offset = *j2 + *k2;
auto fn_1 = [](MacroAssembler* masm, int32_t in_offset,
int32_t out_offset) {
__ Ulh(v0, MemOperand(a0, in_offset));
__ Ush(v0, MemOperand(a0, out_offset), v0);
};
CHECK_EQ(true, run_Unaligned<uint16_t>(buffer_middle, in_offset,
out_offset, value, fn_1));
auto fn_2 = [](MacroAssembler* masm, int32_t in_offset,
int32_t out_offset) {
__ mov(t0, a0);
__ Ulh(a0, MemOperand(a0, in_offset));
__ Ush(a0, MemOperand(t0, out_offset), v0);
};
CHECK_EQ(true, run_Unaligned<uint16_t>(buffer_middle, in_offset,
out_offset, value, fn_2));
auto fn_3 = [](MacroAssembler* masm, int32_t in_offset,
int32_t out_offset) {
__ mov(t0, a0);
__ Ulhu(a0, MemOperand(a0, in_offset));
__ Ush(a0, MemOperand(t0, out_offset), t1);
};
CHECK_EQ(true, run_Unaligned<uint16_t>(buffer_middle, in_offset,
out_offset, value, fn_3));
auto fn_4 = [](MacroAssembler* masm, int32_t in_offset,
int32_t out_offset) {
__ Ulhu(v0, MemOperand(a0, in_offset));
__ Ush(v0, MemOperand(a0, out_offset), t1);
};
CHECK_EQ(true, run_Unaligned<uint16_t>(buffer_middle, in_offset,
out_offset, value, fn_4));
}
}
}
}
TEST(Ulh_bitextension) {
CcTest::InitializeVM();
static const int kBufferSize = 300 * KB;
char memory_buffer[kBufferSize];
char* buffer_middle = memory_buffer + (kBufferSize / 2);
FOR_UINT64_INPUTS(i, unsigned_test_values) {
FOR_INT32_INPUTS2(j1, j2, unsigned_test_offset) {
FOR_INT32_INPUTS2(k1, k2, unsigned_test_offset_increment) {
uint16_t value = static_cast<uint64_t>(*i & 0xFFFF);
int32_t in_offset = *j1 + *k1;
int32_t out_offset = *j2 + *k2;
auto fn = [](MacroAssembler* masm, int32_t in_offset,
int32_t out_offset) {
Label success, fail, end, different;
__ Ulh(t0, MemOperand(a0, in_offset));
__ Ulhu(t1, MemOperand(a0, in_offset));
__ Branch(&different, ne, t0, Operand(t1));
// If signed and unsigned values are same, check
// the upper bits to see if they are zero
__ sra(t0, t0, 15);
__ Branch(&success, eq, t0, Operand(zero_reg));
__ Branch(&fail);
// If signed and unsigned values are different,
// check that the upper bits are complementary
__ bind(&different);
__ sra(t1, t1, 15);
__ Branch(&fail, ne, t1, Operand(1));
__ sra(t0, t0, 15);
__ addiu(t0, t0, 1);
__ Branch(&fail, ne, t0, Operand(zero_reg));
// Fall through to success
__ bind(&success);
__ Ulh(t0, MemOperand(a0, in_offset));
__ Ush(t0, MemOperand(a0, out_offset), v0);
__ Branch(&end);
__ bind(&fail);
__ Ush(zero_reg, MemOperand(a0, out_offset), v0);
__ bind(&end);
};
CHECK_EQ(true, run_Unaligned<uint16_t>(buffer_middle, in_offset,
out_offset, value, fn));
}
}
}
}
TEST(Ulw) {
CcTest::InitializeVM();
static const int kBufferSize = 300 * KB;
char memory_buffer[kBufferSize];
char* buffer_middle = memory_buffer + (kBufferSize / 2);
FOR_UINT64_INPUTS(i, unsigned_test_values) {
FOR_INT32_INPUTS2(j1, j2, unsigned_test_offset) {
FOR_INT32_INPUTS2(k1, k2, unsigned_test_offset_increment) {
uint32_t value = static_cast<uint32_t>(*i & 0xFFFFFFFF);
int32_t in_offset = *j1 + *k1;
int32_t out_offset = *j2 + *k2;
auto fn_1 = [](MacroAssembler* masm, int32_t in_offset,
int32_t out_offset) {
__ Ulw(v0, MemOperand(a0, in_offset));
__ Usw(v0, MemOperand(a0, out_offset));
};
CHECK_EQ(true, run_Unaligned<uint32_t>(buffer_middle, in_offset,
out_offset, value, fn_1));
auto fn_2 = [](MacroAssembler* masm, int32_t in_offset,
int32_t out_offset) {
__ mov(t0, a0);
__ Ulw(a0, MemOperand(a0, in_offset));
__ Usw(a0, MemOperand(t0, out_offset));
};
CHECK_EQ(true,
run_Unaligned<uint32_t>(buffer_middle, in_offset, out_offset,
(uint32_t)value, fn_2));
}
}
}
}
TEST(Ulwc1) {
CcTest::InitializeVM();
static const int kBufferSize = 300 * KB;
char memory_buffer[kBufferSize];
char* buffer_middle = memory_buffer + (kBufferSize / 2);
FOR_UINT64_INPUTS(i, unsigned_test_values) {
FOR_INT32_INPUTS2(j1, j2, unsigned_test_offset) {
FOR_INT32_INPUTS2(k1, k2, unsigned_test_offset_increment) {
float value = static_cast<float>(*i & 0xFFFFFFFF);
int32_t in_offset = *j1 + *k1;
int32_t out_offset = *j2 + *k2;
auto fn = [](MacroAssembler* masm, int32_t in_offset,
int32_t out_offset) {
__ Ulwc1(f0, MemOperand(a0, in_offset), t0);
__ Uswc1(f0, MemOperand(a0, out_offset), t0);
};
CHECK_EQ(true, run_Unaligned<float>(buffer_middle, in_offset,
out_offset, value, fn));
}
}
}
}
TEST(Uldc1) {
CcTest::InitializeVM();
static const int kBufferSize = 300 * KB;
char memory_buffer[kBufferSize];
char* buffer_middle = memory_buffer + (kBufferSize / 2);
FOR_UINT64_INPUTS(i, unsigned_test_values) {
FOR_INT32_INPUTS2(j1, j2, unsigned_test_offset) {
FOR_INT32_INPUTS2(k1, k2, unsigned_test_offset_increment) {
double value = static_cast<double>(*i);
int32_t in_offset = *j1 + *k1;
int32_t out_offset = *j2 + *k2;
auto fn = [](MacroAssembler* masm, int32_t in_offset,
int32_t out_offset) {
__ Uldc1(f0, MemOperand(a0, in_offset), t0);
__ Usdc1(f0, MemOperand(a0, out_offset), t0);
};
CHECK_EQ(true, run_Unaligned<double>(buffer_middle, in_offset,
out_offset, value, fn));
}
}
}
}
static const std::vector<uint32_t> sltu_test_values() {
static const uint32_t kValues[] = {
0, 1, 0x7ffe, 0x7fff, 0x8000,
0x8001, 0xfffe, 0xffff, 0xffff7ffe, 0xffff7fff,
0xffff8000, 0xffff8001, 0xfffffffe, 0xffffffff,
};
return std::vector<uint32_t>(&kValues[0], &kValues[arraysize(kValues)]);
}
template <typename Func>
bool run_Sltu(uint32_t rs, uint32_t rd, Func GenerateSltuInstructionFunc) {
typedef int32_t (*F_CVT)(uint32_t x0, uint32_t x1, int x2, int x3, int x4);
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assm(isolate, nullptr, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assm;
GenerateSltuInstructionFunc(masm, rd);
__ jr(ra);
__ nop();
CodeDesc desc;
assm.GetCode(isolate, &desc);
Handle<Code> code = isolate->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
F_CVT f = FUNCTION_CAST<F_CVT>(code->entry());
int32_t res = reinterpret_cast<int32_t>(
CALL_GENERATED_CODE(isolate, f, rs, rd, 0, 0, 0));
return res == 1;
}
TEST(Sltu) {
CcTest::InitializeVM();
FOR_UINT32_INPUTS(i, sltu_test_values) {
FOR_UINT32_INPUTS(j, sltu_test_values) {
uint32_t rs = *i;
uint32_t rd = *j;
auto fn_1 = [](MacroAssembler* masm, uint32_t imm) {
__ Sltu(v0, a0, Operand(imm));
};
CHECK_EQ(rs < rd, run_Sltu(rs, rd, fn_1));
auto fn_2 = [](MacroAssembler* masm, uint32_t imm) {
__ Sltu(v0, a0, a1);
};
CHECK_EQ(rs < rd, run_Sltu(rs, rd, fn_2));
}
}
}
template <typename T, typename Inputs, typename Results>
static ::F4 GenerateMacroFloat32MinMax(MacroAssembler* masm) {
T a = T::from_code(4); // f4
T b = T::from_code(6); // f6
T c = T::from_code(8); // f8
Label ool_min_abc, ool_min_aab, ool_min_aba;
Label ool_max_abc, ool_max_aab, ool_max_aba;
Label done_min_abc, done_min_aab, done_min_aba;
Label done_max_abc, done_max_aab, done_max_aba;
#define FLOAT_MIN_MAX(fminmax, res, x, y, done, ool, res_field) \
__ lwc1(x, MemOperand(a0, offsetof(Inputs, src1_))); \
__ lwc1(y, MemOperand(a0, offsetof(Inputs, src2_))); \
__ fminmax(res, x, y, &ool); \
__ bind(&done); \
__ swc1(a, MemOperand(a1, offsetof(Results, res_field)))
// a = min(b, c);
FLOAT_MIN_MAX(Float32Min, a, b, c, done_min_abc, ool_min_abc, min_abc_);
// a = min(a, b);
FLOAT_MIN_MAX(Float32Min, a, a, b, done_min_aab, ool_min_aab, min_aab_);
// a = min(b, a);
FLOAT_MIN_MAX(Float32Min, a, b, a, done_min_aba, ool_min_aba, min_aba_);
// a = max(b, c);
FLOAT_MIN_MAX(Float32Max, a, b, c, done_max_abc, ool_max_abc, max_abc_);
// a = max(a, b);
FLOAT_MIN_MAX(Float32Max, a, a, b, done_max_aab, ool_max_aab, max_aab_);
// a = max(b, a);
FLOAT_MIN_MAX(Float32Max, a, b, a, done_max_aba, ool_max_aba, max_aba_);
#undef FLOAT_MIN_MAX
__ jr(ra);
__ nop();
// Generate out-of-line cases.
__ bind(&ool_min_abc);
__ Float32MinOutOfLine(a, b, c);
__ Branch(&done_min_abc);
__ bind(&ool_min_aab);
__ Float32MinOutOfLine(a, a, b);
__ Branch(&done_min_aab);
__ bind(&ool_min_aba);
__ Float32MinOutOfLine(a, b, a);
__ Branch(&done_min_aba);
__ bind(&ool_max_abc);
__ Float32MaxOutOfLine(a, b, c);
__ Branch(&done_max_abc);
__ bind(&ool_max_aab);
__ Float32MaxOutOfLine(a, a, b);
__ Branch(&done_max_aab);
__ bind(&ool_max_aba);
__ Float32MaxOutOfLine(a, b, a);
__ Branch(&done_max_aba);
CodeDesc desc;
masm->GetCode(masm->isolate(), &desc);
Handle<Code> code = masm->isolate()->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
#ifdef DEBUG
OFStream os(stdout);
code->Print(os);
#endif
return FUNCTION_CAST<::F4>(code->entry());
}
TEST(macro_float_minmax_f32) {
// Test the Float32Min and Float32Max macros.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assembler(isolate, NULL, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assembler;
struct Inputs {
float src1_;
float src2_;
};
struct Results {
// Check all register aliasing possibilities in order to exercise all
// code-paths in the macro assembler.
float min_abc_;
float min_aab_;
float min_aba_;
float max_abc_;
float max_aab_;
float max_aba_;
};
::F4 f = GenerateMacroFloat32MinMax<FPURegister, Inputs, Results>(masm);
Object* dummy = nullptr;
USE(dummy);
#define CHECK_MINMAX(src1, src2, min, max) \
do { \
Inputs inputs = {src1, src2}; \
Results results; \
dummy = CALL_GENERATED_CODE(isolate, f, &inputs, &results, 0, 0, 0); \
CHECK_EQ(bit_cast<uint32_t>(min), bit_cast<uint32_t>(results.min_abc_)); \
CHECK_EQ(bit_cast<uint32_t>(min), bit_cast<uint32_t>(results.min_aab_)); \
CHECK_EQ(bit_cast<uint32_t>(min), bit_cast<uint32_t>(results.min_aba_)); \
CHECK_EQ(bit_cast<uint32_t>(max), bit_cast<uint32_t>(results.max_abc_)); \
CHECK_EQ(bit_cast<uint32_t>(max), bit_cast<uint32_t>(results.max_aab_)); \
CHECK_EQ(bit_cast<uint32_t>(max), bit_cast<uint32_t>(results.max_aba_)); \
/* Use a bit_cast to correctly identify -0.0 and NaNs. */ \
} while (0)
float nan_a = std::numeric_limits<float>::quiet_NaN();
float nan_b = std::numeric_limits<float>::quiet_NaN();
CHECK_MINMAX(1.0f, -1.0f, -1.0f, 1.0f);
CHECK_MINMAX(-1.0f, 1.0f, -1.0f, 1.0f);
CHECK_MINMAX(0.0f, -1.0f, -1.0f, 0.0f);
CHECK_MINMAX(-1.0f, 0.0f, -1.0f, 0.0f);
CHECK_MINMAX(-0.0f, -1.0f, -1.0f, -0.0f);
CHECK_MINMAX(-1.0f, -0.0f, -1.0f, -0.0f);
CHECK_MINMAX(0.0f, 1.0f, 0.0f, 1.0f);
CHECK_MINMAX(1.0f, 0.0f, 0.0f, 1.0f);
CHECK_MINMAX(0.0f, 0.0f, 0.0f, 0.0f);
CHECK_MINMAX(-0.0f, -0.0f, -0.0f, -0.0f);
CHECK_MINMAX(-0.0f, 0.0f, -0.0f, 0.0f);
CHECK_MINMAX(0.0f, -0.0f, -0.0f, 0.0f);
CHECK_MINMAX(0.0f, nan_a, nan_a, nan_a);
CHECK_MINMAX(nan_a, 0.0f, nan_a, nan_a);
CHECK_MINMAX(nan_a, nan_b, nan_a, nan_a);
CHECK_MINMAX(nan_b, nan_a, nan_b, nan_b);
#undef CHECK_MINMAX
}
template <typename T, typename Inputs, typename Results>
static ::F4 GenerateMacroFloat64MinMax(MacroAssembler* masm) {
T a = T::from_code(4); // f4
T b = T::from_code(6); // f6
T c = T::from_code(8); // f8
Label ool_min_abc, ool_min_aab, ool_min_aba;
Label ool_max_abc, ool_max_aab, ool_max_aba;
Label done_min_abc, done_min_aab, done_min_aba;
Label done_max_abc, done_max_aab, done_max_aba;
#define FLOAT_MIN_MAX(fminmax, res, x, y, done, ool, res_field) \
__ Ldc1(x, MemOperand(a0, offsetof(Inputs, src1_))); \
__ Ldc1(y, MemOperand(a0, offsetof(Inputs, src2_))); \
__ fminmax(res, x, y, &ool); \
__ bind(&done); \
__ Sdc1(a, MemOperand(a1, offsetof(Results, res_field)))
// a = min(b, c);
FLOAT_MIN_MAX(Float64Min, a, b, c, done_min_abc, ool_min_abc, min_abc_);
// a = min(a, b);
FLOAT_MIN_MAX(Float64Min, a, a, b, done_min_aab, ool_min_aab, min_aab_);
// a = min(b, a);
FLOAT_MIN_MAX(Float64Min, a, b, a, done_min_aba, ool_min_aba, min_aba_);
// a = max(b, c);
FLOAT_MIN_MAX(Float64Max, a, b, c, done_max_abc, ool_max_abc, max_abc_);
// a = max(a, b);
FLOAT_MIN_MAX(Float64Max, a, a, b, done_max_aab, ool_max_aab, max_aab_);
// a = max(b, a);
FLOAT_MIN_MAX(Float64Max, a, b, a, done_max_aba, ool_max_aba, max_aba_);
#undef FLOAT_MIN_MAX
__ jr(ra);
__ nop();
// Generate out-of-line cases.
__ bind(&ool_min_abc);
__ Float64MinOutOfLine(a, b, c);
__ Branch(&done_min_abc);
__ bind(&ool_min_aab);
__ Float64MinOutOfLine(a, a, b);
__ Branch(&done_min_aab);
__ bind(&ool_min_aba);
__ Float64MinOutOfLine(a, b, a);
__ Branch(&done_min_aba);
__ bind(&ool_max_abc);
__ Float64MaxOutOfLine(a, b, c);
__ Branch(&done_max_abc);
__ bind(&ool_max_aab);
__ Float64MaxOutOfLine(a, a, b);
__ Branch(&done_max_aab);
__ bind(&ool_max_aba);
__ Float64MaxOutOfLine(a, b, a);
__ Branch(&done_max_aba);
CodeDesc desc;
masm->GetCode(masm->isolate(), &desc);
Handle<Code> code = masm->isolate()->factory()->NewCode(
desc, Code::ComputeFlags(Code::STUB), Handle<Code>());
#ifdef DEBUG
OFStream os(stdout);
code->Print(os);
#endif
return FUNCTION_CAST<::F4>(code->entry());
}
TEST(macro_float_minmax_f64) {
// Test the Float64Min and Float64Max macros.
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
HandleScope scope(isolate);
MacroAssembler assembler(isolate, NULL, 0,
v8::internal::CodeObjectRequired::kYes);
MacroAssembler* masm = &assembler;
struct Inputs {
double src1_;
double src2_;
};
struct Results {
// Check all register aliasing possibilities in order to exercise all
// code-paths in the macro assembler.
double min_abc_;
double min_aab_;
double min_aba_;
double max_abc_;
double max_aab_;
double max_aba_;
};
::F4 f = GenerateMacroFloat64MinMax<DoubleRegister, Inputs, Results>(masm);
Object* dummy = nullptr;
USE(dummy);
#define CHECK_MINMAX(src1, src2, min, max) \
do { \
Inputs inputs = {src1, src2}; \
Results results; \
dummy = CALL_GENERATED_CODE(isolate, f, &inputs, &results, 0, 0, 0); \
CHECK_EQ(bit_cast<uint64_t>(min), bit_cast<uint64_t>(results.min_abc_)); \
CHECK_EQ(bit_cast<uint64_t>(min), bit_cast<uint64_t>(results.min_aab_)); \
CHECK_EQ(bit_cast<uint64_t>(min), bit_cast<uint64_t>(results.min_aba_)); \
CHECK_EQ(bit_cast<uint64_t>(max), bit_cast<uint64_t>(results.max_abc_)); \
CHECK_EQ(bit_cast<uint64_t>(max), bit_cast<uint64_t>(results.max_aab_)); \
CHECK_EQ(bit_cast<uint64_t>(max), bit_cast<uint64_t>(results.max_aba_)); \
/* Use a bit_cast to correctly identify -0.0 and NaNs. */ \
} while (0)
double nan_a = std::numeric_limits<double>::quiet_NaN();
double nan_b = std::numeric_limits<double>::quiet_NaN();
CHECK_MINMAX(1.0, -1.0, -1.0, 1.0);
CHECK_MINMAX(-1.0, 1.0, -1.0, 1.0);
CHECK_MINMAX(0.0, -1.0, -1.0, 0.0);
CHECK_MINMAX(-1.0, 0.0, -1.0, 0.0);
CHECK_MINMAX(-0.0, -1.0, -1.0, -0.0);
CHECK_MINMAX(-1.0, -0.0, -1.0, -0.0);
CHECK_MINMAX(0.0, 1.0, 0.0, 1.0);
CHECK_MINMAX(1.0, 0.0, 0.0, 1.0);
CHECK_MINMAX(0.0, 0.0, 0.0, 0.0);
CHECK_MINMAX(-0.0, -0.0, -0.0, -0.0);
CHECK_MINMAX(-0.0, 0.0, -0.0, 0.0);
CHECK_MINMAX(0.0, -0.0, -0.0, 0.0);
CHECK_MINMAX(0.0, nan_a, nan_a, nan_a);
CHECK_MINMAX(nan_a, 0.0, nan_a, nan_a);
CHECK_MINMAX(nan_a, nan_b, nan_a, nan_a);
CHECK_MINMAX(nan_b, nan_a, nan_b, nan_b);
#undef CHECK_MINMAX
}
#undef __
| [
"guenter.obiltschnig@appinf.com"
] | guenter.obiltschnig@appinf.com |
94be2c3827807df886ed80becf07e7104a58cc34 | fe81eae22f5662b6b6dca838b6972be27ca63b2d | /aorus/AORUS/inc/kb/KbCfg.cpp | 236b31773491b9980cb9a0e63a4d10927afdbd1c | [] | no_license | josephx86/Aorus | d014c1d97131cfb7201ab0352b38e2bc4adb007e | 8f9dcd4a4b55176d4575d9309e8536fbc8008b60 | refs/heads/master | 2021-05-05T19:29:47.147219 | 2017-07-25T09:36:08 | 2017-07-25T09:36:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,414 | cpp | #include "StdAfx.h"
#include "KbCfg.h"
KB_CLR_CFG::_KB_CLR_CFG()
{
nCount = 1;
ZeroMemory(clrList, sizeof(COLORREF) * 10);
clrList[0] = 255;
}
KB_CLR_CFG::_KB_CLR_CFG(int nType)
{
switch(nType)
{
case 0:
clrList[0] = s_clrKbLed[0];
nCount = 1;
break;
case 1:
clrList[0] = s_clrKbLed[0];
clrList[1] = s_clrKbLed[1];
nCount = 2;
break;
case 2:
clrList[0] = s_clrKbLed[0];
nCount = 0;
break;
case 3:
clrList[0] = s_clrKbLed[0];
clrList[1] = s_clrKbLed[1];
clrList[2] = s_clrKbLed[2];
clrList[3] = s_clrKbLed[3];
clrList[4] = s_clrKbLed[4];
clrList[5] = s_clrKbLed[5];
clrList[6] = s_clrKbLed[6];
nCount = 7;
break;
case 4:
clrList[0] = s_clrKbLed[0];
clrList[1] = s_clrKbLed[1];
clrList[2] = s_clrKbLed[2];
clrList[3] = s_clrKbLed[3];
clrList[4] = s_clrKbLed[4];
clrList[5] = s_clrKbLed[5];
clrList[6] = s_clrKbLed[7];
nCount = 7;
break;
case 5:
clrList[0] = s_clrKbLed[0];
clrList[1] = s_clrKbLed[1];
clrList[2] = s_clrKbLed[2];
clrList[3] = s_clrKbLed[3];
clrList[4] = s_clrKbLed[4];
clrList[5] = s_clrKbLed[5];
clrList[6] = s_clrKbLed[7];
nCount = 7;
break;
}
}
KB_LED_CFG::_KB_LED_CFG()
{
nType = 1;
nSpeed = 10;
nBrightness = 10;
nStartWay = START_AUTO;
nTimes = 2;
nWidth = 2;
nAngle = 0;
nClrCount = 0;
bOn = true;
}
void KB_LED_CFG::Def(int nType)
{
switch(nType)
{
case 1:
nType = LED_CONSISTENT;
nSpeed = 10;
nBrightness = 10;
nStartWay = START_AUTO;
nTimes = 2;
nWidth = 2;
nAngle = 0;
bOn = true;
nClrCount = 1;
clrCfg[0].clrList[0] = s_clrKbLed[0];
clrCfg[0].nCount = 1;
break;
case 2:
nType = LED_PULSING;
nSpeed = 10;
nBrightness = 10;
nStartWay = START_AUTO;
nTimes = 2;
nWidth = 2;
nAngle = 0;
nClrCount = 1;
bOn = true;
clrCfg[0].clrList[0] = s_clrKbLed[0];
clrCfg[0].clrList[1] = s_clrKbLed[1];
clrCfg[0].nCount = 2;
break;
case 3:
nType = LED_REACTIVE;
nSpeed = 10;
nBrightness = 10;
nStartWay = START_AUTO;
nTimes = 2;
nWidth = 1;
nAngle = 1;
nClrCount = 1;
bOn = true;
clrCfg[0].clrList[0] = s_clrKbLed[0];
clrCfg[0].nCount = 0;
break;
case 4:
nType = LED_RIPPLE;
nSpeed = 10;
nBrightness = 10;
nStartWay = START_PRESS;
nTimes = 1;
nWidth = 1;
nAngle = 0;
nClrCount = 1;
bOn = true;
clrCfg[0].clrList[0] = s_clrKbLed[0];
clrCfg[0].clrList[1] = s_clrKbLed[1];
clrCfg[0].clrList[2] = s_clrKbLed[2];
clrCfg[0].clrList[3] = s_clrKbLed[3];
clrCfg[0].clrList[4] = s_clrKbLed[4];
clrCfg[0].clrList[5] = s_clrKbLed[5];
clrCfg[0].clrList[6] = s_clrKbLed[6];
clrCfg[0].nCount = 7;
break;
case 5:
nType = LED_CYCLING;
nSpeed = 10;
nBrightness = 10;
nStartWay = START_AUTO;
nTimes = 0;
nWidth = 2;
nAngle = 0;
nClrCount = 1;
bOn = true;
clrCfg[0].clrList[0] = s_clrKbLed[0];
clrCfg[0].clrList[1] = s_clrKbLed[1];
clrCfg[0].clrList[2] = s_clrKbLed[2];
clrCfg[0].clrList[3] = s_clrKbLed[3];
clrCfg[0].clrList[4] = s_clrKbLed[4];
clrCfg[0].clrList[5] = s_clrKbLed[5];
clrCfg[0].clrList[6] = s_clrKbLed[7];
clrCfg[0].nCount = 7;
break;
case 6:
nType = LED_WAVE;
nSpeed = 10;
nBrightness = 10;
nStartWay = START_PRESS;
nTimes = 1;
nWidth = 2;
nAngle = 0;
nClrCount = 1;
bOn = true;
clrCfg[0].clrList[0] = s_clrKbLed[0];
clrCfg[0].clrList[1] = s_clrKbLed[1];
clrCfg[0].clrList[2] = s_clrKbLed[2];
clrCfg[0].clrList[3] = s_clrKbLed[3];
clrCfg[0].clrList[4] = s_clrKbLed[4];
clrCfg[0].clrList[5] = s_clrKbLed[5];
clrCfg[0].clrList[6] = s_clrKbLed[7];
clrCfg[0].nCount = 7;
break;
}
}
//////////////////////////////////////////////////////////////////////////
CKbCfg::CKbCfg(void)
{
}
CKbCfg::~CKbCfg(void)
{
}
void CKbCfg::SetClrCfg(KB_CLR_CFG cfg, int nType, int nIndex)
{
CIniFile ini;
CString sPath = CKbLedCtrl::GetCfgPath(-1) + _T("present.ini");
ini.SetIniFile(sPath);
CString sSession;
sSession.Format(_T("T%d_%d"), nType, nIndex);
for (int m = 0; m < cfg.nCount; m++)
{
CString sKey;
sKey.Format(_T("C%d"), m);
ini.SetIniInfo(sSession, sKey, cfg.clrList[m]);
}
ini.SetIniInfo(sSession, _T("Count"), cfg.nCount);
}
void CKbCfg::SetClrCfgs(KB_CLR_CFG cfg[], int nType, int nCount)
{
CIniFile ini;
CString sPath = CKbLedCtrl::GetCfgPath(-1) + _T("present.ini");
ini.SetIniFile(sPath);
CString sSession;
for (int n = 0; n < nCount; n++)
{
sSession.Format(_T("T%d_%d"), nType, n);
for (int m = 0; m < cfg[n].nCount; m++)
{
CString sKey;
sKey.Format(_T("C%d"), m);
ini.SetIniInfo(sSession, sKey, cfg[n].clrList[m]);
}
ini.SetIniInfo(sSession, _T("Count"), cfg[n].nCount);
}
sSession.Format(_T("T%d"), nType);
ini.SetIniInfo(sSession, _T("Count"), nCount);
}
void CKbCfg::GetClrCfgs(KB_CLR_CFG cfg[], int nType, int& nCount)
{
CIniFile ini;
CString sPath = CKbLedCtrl::GetCfgPath(-1) + _T("present.ini");
ini.SetIniFile(sPath);
CString sSession;
sSession.Format(_T("T%d"), nType);
BOOL bGet = ini.GetIniInfo(sSession, _T("Count"), nCount);
if (!bGet)
{
KB_CLR_CFG cfgDefault(nType);
cfg[0] = cfgDefault;
nCount = 1;
SetClrCfgs(cfg, nType, nCount);
return;
}
for (int n = 0; n < nCount; n++)
{
sSession.Format(_T("T%d_%d"), nType, n);
ini.GetIniInfo(sSession, _T("Count"), cfg[n].nCount);
for (int m = 0; m < cfg[n].nCount; m++)
{
CString sKey;
sKey.Format(_T("C%d"), m);
ini.GetIniInfo(sSession, sKey, cfg[n].clrList[m]);
}
}
}
| [
"925350731@qq.com"
] | 925350731@qq.com |
6155bf956ac9c31035b9ac8053e3bcb579b4da01 | 62ec94314f194157f62c49c206dd777a159e0817 | /src/console/gengetopt/cl_arguments.cpp | d3b1c5f8d7203caea7327edcac7cb0b7c14f1204 | [] | no_license | telishev/sneakPic | e6c3a9ceee97caf5c46808225e0e3e68a1ca2bf0 | 25cac33adfec70f161cc526123df5376ece9b950 | refs/heads/master | 2020-04-14T19:04:56.660200 | 2014-07-19T20:37:38 | 2014-07-19T20:37:38 | 10,853,376 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 35,197 | cpp | /*
File autogenerated by gengetopt version 2.22.6
generated with the following command:
e:\MinGW\msys\1.0\local\bin\gengetopt.exe -i cl_arguments.ggo --unamed-opt=SVG_FILES --show-required -G -F cl_arguments -c cpp
The developers of gengetopt consider the fixed text that goes in all
gengetopt output files to be in the public domain:
we make no copyright claims on it.
*/
/* If we use autoconf. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef FIX_UNUSED
#define FIX_UNUSED(X) (void) (X) /* avoid warnings for unused params */
#endif
#include "cl_arguments.h"
const char *gengetopt_args_info_purpose = "";
const char *gengetopt_args_info_usage = "Usage: " CMDLINE_PARSER_PACKAGE " [OPTIONS]... [SVG_FILES]...";
const char *gengetopt_args_info_versiontext = "";
const char *gengetopt_args_info_description = "";
const char *gengetopt_args_info_full_help[] = {
" -h, --help Print help and exit",
" --full-help Print help, including hidden options, and exit",
" -V, --version Print version and exit",
"\nExport:",
" -r, --render-png=FileName.png Renders target svg file to FileName.png",
" --save=FileName.svg Saves file to FileName.svg in svg format (for\n testing purposes)",
0
};
static void
init_help_array(void)
{
gengetopt_args_info_help[0] = gengetopt_args_info_full_help[0];
gengetopt_args_info_help[1] = gengetopt_args_info_full_help[1];
gengetopt_args_info_help[2] = gengetopt_args_info_full_help[2];
gengetopt_args_info_help[3] = gengetopt_args_info_full_help[3];
gengetopt_args_info_help[4] = gengetopt_args_info_full_help[4];
gengetopt_args_info_help[5] = 0;
}
const char *gengetopt_args_info_help[6];
typedef enum {ARG_NO
, ARG_STRING
} cmdline_parser_arg_type;
static
void clear_given (struct gengetopt_args_info *args_info);
static
void clear_args (struct gengetopt_args_info *args_info);
static int
cmdline_parser_internal (int argc, char **argv, struct gengetopt_args_info *args_info,
struct cmdline_parser_params *params, const char *additional_error);
static char *
gengetopt_strdup (const char *s);
static
void clear_given (struct gengetopt_args_info *args_info)
{
args_info->help_given = 0 ;
args_info->full_help_given = 0 ;
args_info->version_given = 0 ;
args_info->render_png_given = 0 ;
args_info->save_given = 0 ;
}
static
void clear_args (struct gengetopt_args_info *args_info)
{
FIX_UNUSED (args_info);
args_info->render_png_arg = NULL;
args_info->render_png_orig = NULL;
args_info->save_arg = NULL;
args_info->save_orig = NULL;
}
static
void init_args_info(struct gengetopt_args_info *args_info)
{
init_help_array();
args_info->help_help = gengetopt_args_info_full_help[0] ;
args_info->full_help_help = gengetopt_args_info_full_help[1] ;
args_info->version_help = gengetopt_args_info_full_help[2] ;
args_info->render_png_help = gengetopt_args_info_full_help[4] ;
args_info->save_help = gengetopt_args_info_full_help[5] ;
}
void
cmdline_parser_print_version (void)
{
printf ("%s %s\n",
(strlen(CMDLINE_PARSER_PACKAGE_NAME) ? CMDLINE_PARSER_PACKAGE_NAME : CMDLINE_PARSER_PACKAGE),
CMDLINE_PARSER_VERSION);
if (strlen(gengetopt_args_info_versiontext) > 0)
printf("\n%s\n", gengetopt_args_info_versiontext);
}
static void print_help_common(void) {
cmdline_parser_print_version ();
if (strlen(gengetopt_args_info_purpose) > 0)
printf("\n%s\n", gengetopt_args_info_purpose);
if (strlen(gengetopt_args_info_usage) > 0)
printf("\n%s\n", gengetopt_args_info_usage);
printf("\n");
if (strlen(gengetopt_args_info_description) > 0)
printf("%s\n\n", gengetopt_args_info_description);
}
void
cmdline_parser_print_help (void)
{
int i = 0;
print_help_common();
while (gengetopt_args_info_help[i])
printf("%s\n", gengetopt_args_info_help[i++]);
}
void
cmdline_parser_print_full_help (void)
{
int i = 0;
print_help_common();
while (gengetopt_args_info_full_help[i])
printf("%s\n", gengetopt_args_info_full_help[i++]);
}
void
cmdline_parser_init (struct gengetopt_args_info *args_info)
{
clear_given (args_info);
clear_args (args_info);
init_args_info (args_info);
args_info->inputs = 0;
args_info->inputs_num = 0;
}
void
cmdline_parser_params_init(struct cmdline_parser_params *params)
{
if (params)
{
params->override = 0;
params->initialize = 1;
params->check_required = 1;
params->check_ambiguity = 0;
params->print_errors = 1;
}
}
struct cmdline_parser_params *
cmdline_parser_params_create(void)
{
struct cmdline_parser_params *params =
(struct cmdline_parser_params *)malloc(sizeof(struct cmdline_parser_params));
cmdline_parser_params_init(params);
return params;
}
static void
free_string_field (char **s)
{
if (*s)
{
free (*s);
*s = 0;
}
}
static void
cmdline_parser_release (struct gengetopt_args_info *args_info)
{
unsigned int i;
free_string_field (&(args_info->render_png_arg));
free_string_field (&(args_info->render_png_orig));
free_string_field (&(args_info->save_arg));
free_string_field (&(args_info->save_orig));
for (i = 0; i < args_info->inputs_num; ++i)
free (args_info->inputs [i]);
if (args_info->inputs_num)
free (args_info->inputs);
clear_given (args_info);
}
static void
write_into_file(FILE *outfile, const char *opt, const char *arg, const char *values[])
{
FIX_UNUSED (values);
if (arg) {
fprintf(outfile, "%s=\"%s\"\n", opt, arg);
} else {
fprintf(outfile, "%s\n", opt);
}
}
int
cmdline_parser_dump(FILE *outfile, struct gengetopt_args_info *args_info)
{
int i = 0;
if (!outfile)
{
fprintf (stderr, "%s: cannot dump options to stream\n", CMDLINE_PARSER_PACKAGE);
return EXIT_FAILURE;
}
if (args_info->help_given)
write_into_file(outfile, "help", 0, 0 );
if (args_info->full_help_given)
write_into_file(outfile, "full-help", 0, 0 );
if (args_info->version_given)
write_into_file(outfile, "version", 0, 0 );
if (args_info->render_png_given)
write_into_file(outfile, "render-png", args_info->render_png_orig, 0);
if (args_info->save_given)
write_into_file(outfile, "save", args_info->save_orig, 0);
i = EXIT_SUCCESS;
return i;
}
int
cmdline_parser_file_save(const char *filename, struct gengetopt_args_info *args_info)
{
FILE *outfile;
int i = 0;
outfile = fopen(filename, "w");
if (!outfile)
{
fprintf (stderr, "%s: cannot open file for writing: %s\n", CMDLINE_PARSER_PACKAGE, filename);
return EXIT_FAILURE;
}
i = cmdline_parser_dump(outfile, args_info);
fclose (outfile);
return i;
}
void
cmdline_parser_free (struct gengetopt_args_info *args_info)
{
cmdline_parser_release (args_info);
}
/** @brief replacement of strdup, which is not standard */
char *
gengetopt_strdup (const char *s)
{
char *result = 0;
if (!s)
return result;
result = (char*)malloc(strlen(s) + 1);
if (result == (char*)0)
return (char*)0;
strcpy(result, s);
return result;
}
int
cmdline_parser (int argc, char **argv, struct gengetopt_args_info *args_info)
{
return cmdline_parser2 (argc, argv, args_info, 0, 1, 1);
}
int
cmdline_parser_ext (int argc, char **argv, struct gengetopt_args_info *args_info,
struct cmdline_parser_params *params)
{
int result;
result = cmdline_parser_internal (argc, argv, args_info, params, 0);
if (result == EXIT_FAILURE)
{
cmdline_parser_free (args_info);
exit (EXIT_FAILURE);
}
return result;
}
int
cmdline_parser2 (int argc, char **argv, struct gengetopt_args_info *args_info, int override, int initialize, int check_required)
{
int result;
struct cmdline_parser_params params;
params.override = override;
params.initialize = initialize;
params.check_required = check_required;
params.check_ambiguity = 0;
params.print_errors = 1;
result = cmdline_parser_internal (argc, argv, args_info, ¶ms, 0);
if (result == EXIT_FAILURE)
{
cmdline_parser_free (args_info);
exit (EXIT_FAILURE);
}
return result;
}
int
cmdline_parser_required (struct gengetopt_args_info *args_info, const char *prog_name)
{
FIX_UNUSED (args_info);
FIX_UNUSED (prog_name);
return EXIT_SUCCESS;
}
/*
* Extracted from the glibc source tree, version 2.3.6
*
* Licensed under the GPL as per the whole glibc source tree.
*
* This file was modified so that getopt_long can be called
* many times without risking previous memory to be spoiled.
*
* Modified by Andre Noll and Lorenzo Bettini for use in
* GNU gengetopt generated files.
*
*/
/*
* we must include anything we need since this file is not thought to be
* inserted in a file already using getopt.h
*
* Lorenzo
*/
struct option
{
const char *name;
/* has_arg can't be an enum because some compilers complain about
type mismatches in all the code that assumes it is an int. */
int has_arg;
int *flag;
int val;
};
/* This version of `getopt' appears to the caller like standard Unix `getopt'
but it behaves differently for the user, since it allows the user
to intersperse the options with the other arguments.
As `getopt' works, it permutes the elements of ARGV so that,
when it is done, all the options precede everything else. Thus
all application programs are extended to handle flexible argument order.
*/
/*
If the field `flag' is not NULL, it points to a variable that is set
to the value given in the field `val' when the option is found, but
left unchanged if the option is not found.
To have a long-named option do something other than set an `int' to
a compiled-in constant, such as set a value from `custom_optarg', set the
option's `flag' field to zero and its `val' field to a nonzero
value (the equivalent single-letter option character, if there is
one). For long options that have a zero `flag' field, `getopt'
returns the contents of the `val' field. */
/* Names for the values of the `has_arg' field of `struct option'. */
#ifndef no_argument
#define no_argument 0
#endif
#ifndef required_argument
#define required_argument 1
#endif
#ifndef optional_argument
#define optional_argument 2
#endif
struct custom_getopt_data {
/*
* These have exactly the same meaning as the corresponding global variables,
* except that they are used for the reentrant versions of getopt.
*/
int custom_optind;
int custom_opterr;
int custom_optopt;
char *custom_optarg;
/* True if the internal members have been initialized. */
int initialized;
/*
* The next char to be scanned in the option-element in which the last option
* character we returned was found. This allows us to pick up the scan where
* we left off. If this is zero, or a null string, it means resume the scan by
* advancing to the next ARGV-element.
*/
char *nextchar;
/*
* Describe the part of ARGV that contains non-options that have been skipped.
* `first_nonopt' is the index in ARGV of the first of them; `last_nonopt' is
* the index after the last of them.
*/
int first_nonopt;
int last_nonopt;
};
/*
* the variables optarg, optind, opterr and optopt are renamed with
* the custom_ prefix so that they don't interfere with getopt ones.
*
* Moreover they're static so they are visible only from within the
* file where this very file will be included.
*/
/*
* For communication from `custom_getopt' to the caller. When `custom_getopt' finds an
* option that takes an argument, the argument value is returned here.
*/
static char *custom_optarg;
/*
* Index in ARGV of the next element to be scanned. This is used for
* communication to and from the caller and for communication between
* successive calls to `custom_getopt'.
*
* On entry to `custom_getopt', 1 means this is the first call; initialize.
*
* When `custom_getopt' returns -1, this is the index of the first of the non-option
* elements that the caller should itself scan.
*
* Otherwise, `custom_optind' communicates from one call to the next how much of ARGV
* has been scanned so far.
*
* 1003.2 says this must be 1 before any call.
*/
static int custom_optind = 1;
/*
* Callers store zero here to inhibit the error message for unrecognized
* options.
*/
static int custom_opterr = 1;
/*
* Set to an option character which was unrecognized. This must be initialized
* on some systems to avoid linking in the system's own getopt implementation.
*/
static int custom_optopt = '?';
/*
* Exchange two adjacent subsequences of ARGV. One subsequence is elements
* [first_nonopt,last_nonopt) which contains all the non-options that have been
* skipped so far. The other is elements [last_nonopt,custom_optind), which contains
* all the options processed since those non-options were skipped.
* `first_nonopt' and `last_nonopt' are relocated so that they describe the new
* indices of the non-options in ARGV after they are moved.
*/
static void exchange(char **argv, struct custom_getopt_data *d)
{
int bottom = d->first_nonopt;
int middle = d->last_nonopt;
int top = d->custom_optind;
char *tem;
/*
* Exchange the shorter segment with the far end of the longer segment.
* That puts the shorter segment into the right place. It leaves the
* longer segment in the right place overall, but it consists of two
* parts that need to be swapped next.
*/
while (top > middle && middle > bottom) {
if (top - middle > middle - bottom) {
/* Bottom segment is the short one. */
int len = middle - bottom;
int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] =
argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
} else {
/* Top segment is the short one. */
int len = top - middle;
int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
d->first_nonopt += (d->custom_optind - d->last_nonopt);
d->last_nonopt = d->custom_optind;
}
/* Initialize the internal data when the first call is made. */
static void custom_getopt_initialize(struct custom_getopt_data *d)
{
/*
* Start processing options with ARGV-element 1 (since ARGV-element 0
* is the program name); the sequence of previously skipped non-option
* ARGV-elements is empty.
*/
d->first_nonopt = d->last_nonopt = d->custom_optind;
d->nextchar = NULL;
d->initialized = 1;
}
#define NONOPTION_P (argv[d->custom_optind][0] != '-' || argv[d->custom_optind][1] == '\0')
/* return: zero: continue, nonzero: return given value to user */
static int shuffle_argv(int argc, char *const *argv,const struct option *longopts,
struct custom_getopt_data *d)
{
/*
* Give FIRST_NONOPT & LAST_NONOPT rational values if CUSTOM_OPTIND has been
* moved back by the user (who may also have changed the arguments).
*/
if (d->last_nonopt > d->custom_optind)
d->last_nonopt = d->custom_optind;
if (d->first_nonopt > d->custom_optind)
d->first_nonopt = d->custom_optind;
/*
* If we have just processed some options following some
* non-options, exchange them so that the options come first.
*/
if (d->first_nonopt != d->last_nonopt &&
d->last_nonopt != d->custom_optind)
exchange((char **) argv, d);
else if (d->last_nonopt != d->custom_optind)
d->first_nonopt = d->custom_optind;
/*
* Skip any additional non-options and extend the range of
* non-options previously skipped.
*/
while (d->custom_optind < argc && NONOPTION_P)
d->custom_optind++;
d->last_nonopt = d->custom_optind;
/*
* The special ARGV-element `--' means premature end of options. Skip
* it like a null option, then exchange with previous non-options as if
* it were an option, then skip everything else like a non-option.
*/
if (d->custom_optind != argc && !strcmp(argv[d->custom_optind], "--")) {
d->custom_optind++;
if (d->first_nonopt != d->last_nonopt
&& d->last_nonopt != d->custom_optind)
exchange((char **) argv, d);
else if (d->first_nonopt == d->last_nonopt)
d->first_nonopt = d->custom_optind;
d->last_nonopt = argc;
d->custom_optind = argc;
}
/*
* If we have done all the ARGV-elements, stop the scan and back over
* any non-options that we skipped and permuted.
*/
if (d->custom_optind == argc) {
/*
* Set the next-arg-index to point at the non-options that we
* previously skipped, so the caller will digest them.
*/
if (d->first_nonopt != d->last_nonopt)
d->custom_optind = d->first_nonopt;
return -1;
}
/*
* If we have come to a non-option and did not permute it, either stop
* the scan or describe it to the caller and pass it by.
*/
if (NONOPTION_P) {
d->custom_optarg = argv[d->custom_optind++];
return 1;
}
/*
* We have found another option-ARGV-element. Skip the initial
* punctuation.
*/
d->nextchar = (argv[d->custom_optind] + 1 + (longopts != NULL && argv[d->custom_optind][1] == '-'));
return 0;
}
/*
* Check whether the ARGV-element is a long option.
*
* If there's a long option "fubar" and the ARGV-element is "-fu", consider
* that an abbreviation of the long option, just like "--fu", and not "-f" with
* arg "u".
*
* This distinction seems to be the most useful approach.
*
*/
static int check_long_opt(int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longind,
int print_errors, struct custom_getopt_data *d)
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = d->nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match or abbreviated matches */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp(p->name, d->nextchar, nameend - d->nextchar)) {
if ((unsigned int) (nameend - d->nextchar)
== (unsigned int) strlen(p->name)) {
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
} else if (pfound == NULL) {
/* First nonexact match found. */
pfound = p;
indfound = option_index;
} else if (pfound->has_arg != p->has_arg
|| pfound->flag != p->flag
|| pfound->val != p->val)
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact) {
if (print_errors) {
fprintf(stderr,
"%s: option `%s' is ambiguous\n",
argv[0], argv[d->custom_optind]);
}
d->nextchar += strlen(d->nextchar);
d->custom_optind++;
d->custom_optopt = 0;
return '?';
}
if (pfound) {
option_index = indfound;
d->custom_optind++;
if (*nameend) {
if (pfound->has_arg != no_argument)
d->custom_optarg = nameend + 1;
else {
if (print_errors) {
if (argv[d->custom_optind - 1][1] == '-') {
/* --option */
fprintf(stderr, "%s: option `--%s' doesn't allow an argument\n",
argv[0], pfound->name);
} else {
/* +option or -option */
fprintf(stderr, "%s: option `%c%s' doesn't allow an argument\n",
argv[0], argv[d->custom_optind - 1][0], pfound->name);
}
}
d->nextchar += strlen(d->nextchar);
d->custom_optopt = pfound->val;
return '?';
}
} else if (pfound->has_arg == required_argument) {
if (d->custom_optind < argc)
d->custom_optarg = argv[d->custom_optind++];
else {
if (print_errors) {
fprintf(stderr,
"%s: option `%s' requires an argument\n",
argv[0],
argv[d->custom_optind - 1]);
}
d->nextchar += strlen(d->nextchar);
d->custom_optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
d->nextchar += strlen(d->nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag) {
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/*
* Can't find it as a long option. If this is not getopt_long_only, or
* the option starts with '--' or is not a valid short option, then
* it's an error. Otherwise interpret it as a short option.
*/
if (print_errors) {
if (argv[d->custom_optind][1] == '-') {
/* --option */
fprintf(stderr,
"%s: unrecognized option `--%s'\n",
argv[0], d->nextchar);
} else {
/* +option or -option */
fprintf(stderr,
"%s: unrecognized option `%c%s'\n",
argv[0], argv[d->custom_optind][0],
d->nextchar);
}
}
d->nextchar = (char *) "";
d->custom_optind++;
d->custom_optopt = 0;
return '?';
}
static int check_short_opt(int argc, char *const *argv, const char *optstring,
int print_errors, struct custom_getopt_data *d)
{
char c = *d->nextchar++;
const char *temp = strchr(optstring, c);
/* Increment `custom_optind' when we start to process its last character. */
if (*d->nextchar == '\0')
++d->custom_optind;
if (!temp || c == ':') {
if (print_errors)
fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
d->custom_optopt = c;
return '?';
}
if (temp[1] == ':') {
if (temp[2] == ':') {
/* This is an option that accepts an argument optionally. */
if (*d->nextchar != '\0') {
d->custom_optarg = d->nextchar;
d->custom_optind++;
} else
d->custom_optarg = NULL;
d->nextchar = NULL;
} else {
/* This is an option that requires an argument. */
if (*d->nextchar != '\0') {
d->custom_optarg = d->nextchar;
/*
* If we end this ARGV-element by taking the
* rest as an arg, we must advance to the next
* element now.
*/
d->custom_optind++;
} else if (d->custom_optind == argc) {
if (print_errors) {
fprintf(stderr,
"%s: option requires an argument -- %c\n",
argv[0], c);
}
d->custom_optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
} else
/*
* We already incremented `custom_optind' once;
* increment it again when taking next ARGV-elt
* as argument.
*/
d->custom_optarg = argv[d->custom_optind++];
d->nextchar = NULL;
}
}
return c;
}
/*
* Scan elements of ARGV for option characters given in OPTSTRING.
*
* If an element of ARGV starts with '-', and is not exactly "-" or "--",
* then it is an option element. The characters of this element
* (aside from the initial '-') are option characters. If `getopt'
* is called repeatedly, it returns successively each of the option characters
* from each of the option elements.
*
* If `getopt' finds another option character, it returns that character,
* updating `custom_optind' and `nextchar' so that the next call to `getopt' can
* resume the scan with the following option character or ARGV-element.
*
* If there are no more option characters, `getopt' returns -1.
* Then `custom_optind' is the index in ARGV of the first ARGV-element
* that is not an option. (The ARGV-elements have been permuted
* so that those that are not options now come last.)
*
* OPTSTRING is a string containing the legitimate option characters.
* If an option character is seen that is not listed in OPTSTRING,
* return '?' after printing an error message. If you set `custom_opterr' to
* zero, the error message is suppressed but we still return '?'.
*
* If a char in OPTSTRING is followed by a colon, that means it wants an arg,
* so the following text in the same ARGV-element, or the text of the following
* ARGV-element, is returned in `custom_optarg'. Two colons mean an option that
* wants an optional arg; if there is text in the current ARGV-element,
* it is returned in `custom_optarg', otherwise `custom_optarg' is set to zero.
*
* If OPTSTRING starts with `-' or `+', it requests different methods of
* handling the non-option ARGV-elements.
* See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
*
* Long-named options begin with `--' instead of `-'.
* Their names may be abbreviated as long as the abbreviation is unique
* or is an exact match for some defined option. If they have an
* argument, it follows the option name in the same ARGV-element, separated
* from the option name by a `=', or else the in next ARGV-element.
* When `getopt' finds a long-named option, it returns 0 if that option's
* `flag' field is nonzero, the value of the option's `val' field
* if the `flag' field is zero.
*
* The elements of ARGV aren't really const, because we permute them.
* But we pretend they're const in the prototype to be compatible
* with other systems.
*
* LONGOPTS is a vector of `struct option' terminated by an
* element containing a name which is zero.
*
* LONGIND returns the index in LONGOPT of the long-named option found.
* It is only valid when a long-named option has been found by the most
* recent call.
*
* Return the option character from OPTS just read. Return -1 when there are
* no more options. For unrecognized options, or options missing arguments,
* `custom_optopt' is set to the option letter, and '?' is returned.
*
* The OPTS string is a list of characters which are recognized option letters,
* optionally followed by colons, specifying that that letter takes an
* argument, to be placed in `custom_optarg'.
*
* If a letter in OPTS is followed by two colons, its argument is optional.
* This behavior is specific to the GNU `getopt'.
*
* The argument `--' causes premature termination of argument scanning,
* explicitly telling `getopt' that there are no more options. If OPTS begins
* with `--', then non-option arguments are treated as arguments to the option
* '\0'. This behavior is specific to the GNU `getopt'.
*/
static int getopt_internal_r(int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longind,
struct custom_getopt_data *d)
{
int ret, print_errors = d->custom_opterr;
if (optstring[0] == ':')
print_errors = 0;
if (argc < 1)
return -1;
d->custom_optarg = NULL;
/*
* This is a big difference with GNU getopt, since optind == 0
* means initialization while here 1 means first call.
*/
if (d->custom_optind == 0 || !d->initialized) {
if (d->custom_optind == 0)
d->custom_optind = 1; /* Don't scan ARGV[0], the program name. */
custom_getopt_initialize(d);
}
if (d->nextchar == NULL || *d->nextchar == '\0') {
ret = shuffle_argv(argc, argv, longopts, d);
if (ret)
return ret;
}
if (longopts && (argv[d->custom_optind][1] == '-' ))
return check_long_opt(argc, argv, optstring, longopts,
longind, print_errors, d);
return check_short_opt(argc, argv, optstring, print_errors, d);
}
static int custom_getopt_internal(int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longind)
{
int result;
/* Keep a global copy of all internal members of d */
static struct custom_getopt_data d;
d.custom_optind = custom_optind;
d.custom_opterr = custom_opterr;
result = getopt_internal_r(argc, argv, optstring, longopts,
longind, &d);
custom_optind = d.custom_optind;
custom_optarg = d.custom_optarg;
custom_optopt = d.custom_optopt;
return result;
}
static int custom_getopt_long (int argc, char *const *argv, const char *options,
const struct option *long_options, int *opt_index)
{
return custom_getopt_internal(argc, argv, options, long_options,
opt_index);
}
static char *package_name = 0;
/**
* @brief updates an option
* @param field the generic pointer to the field to update
* @param orig_field the pointer to the orig field
* @param field_given the pointer to the number of occurrence of this option
* @param prev_given the pointer to the number of occurrence already seen
* @param value the argument for this option (if null no arg was specified)
* @param possible_values the possible values for this option (if specified)
* @param default_value the default value (in case the option only accepts fixed values)
* @param arg_type the type of this option
* @param check_ambiguity @see cmdline_parser_params.check_ambiguity
* @param override @see cmdline_parser_params.override
* @param no_free whether to free a possible previous value
* @param multiple_option whether this is a multiple option
* @param long_opt the corresponding long option
* @param short_opt the corresponding short option (or '-' if none)
* @param additional_error possible further error specification
*/
static
int update_arg(void *field, char **orig_field,
unsigned int *field_given, unsigned int *prev_given,
char *value, const char *possible_values[],
const char *default_value,
cmdline_parser_arg_type arg_type,
int check_ambiguity, int override,
int no_free, int multiple_option,
const char *long_opt, char short_opt,
const char *additional_error)
{
char *stop_char = 0;
const char *val = value;
int found;
char **string_field;
FIX_UNUSED (field);
stop_char = 0;
found = 0;
if (!multiple_option && prev_given && (*prev_given || (check_ambiguity && *field_given)))
{
if (short_opt != '-')
fprintf (stderr, "%s: `--%s' (`-%c') option given more than once%s\n",
package_name, long_opt, short_opt,
(additional_error ? additional_error : ""));
else
fprintf (stderr, "%s: `--%s' option given more than once%s\n",
package_name, long_opt,
(additional_error ? additional_error : ""));
return 1; /* failure */
}
FIX_UNUSED (default_value);
if (field_given && *field_given && ! override)
return 0;
if (prev_given)
(*prev_given)++;
if (field_given)
(*field_given)++;
if (possible_values)
val = possible_values[found];
switch(arg_type) {
case ARG_STRING:
if (val) {
string_field = (char **)field;
if (!no_free && *string_field)
free (*string_field); /* free previous string */
*string_field = gengetopt_strdup (val);
}
break;
default:
break;
};
/* store the original value */
switch(arg_type) {
case ARG_NO:
break;
default:
if (value && orig_field) {
if (no_free) {
*orig_field = value;
} else {
if (*orig_field)
free (*orig_field); /* free previous string */
*orig_field = gengetopt_strdup (value);
}
}
};
return 0; /* OK */
}
int
cmdline_parser_internal (
int argc, char **argv, struct gengetopt_args_info *args_info,
struct cmdline_parser_params *params, const char *additional_error)
{
int c; /* Character of the parsed option. */
int error_occurred = 0;
struct gengetopt_args_info local_args_info;
int override;
int initialize;
int check_required;
int check_ambiguity;
char *optarg;
int optind;
int opterr;
int optopt;
package_name = argv[0];
override = params->override;
initialize = params->initialize;
check_required = params->check_required;
check_ambiguity = params->check_ambiguity;
if (initialize)
cmdline_parser_init (args_info);
cmdline_parser_init (&local_args_info);
optarg = 0;
optind = 0;
opterr = params->print_errors;
optopt = '?';
while (1)
{
int option_index = 0;
static struct option long_options[] = {
{ "help", 0, NULL, 'h' },
{ "full-help", 0, NULL, 0 },
{ "version", 0, NULL, 'V' },
{ "render-png", 1, NULL, 'r' },
{ "save", 1, NULL, 0 },
{ 0, 0, 0, 0 }
};
custom_optarg = optarg;
custom_optind = optind;
custom_opterr = opterr;
custom_optopt = optopt;
c = custom_getopt_long (argc, argv, "hVr:", long_options, &option_index);
optarg = custom_optarg;
optind = custom_optind;
opterr = custom_opterr;
optopt = custom_optopt;
if (c == -1) break; /* Exit from `while (1)' loop. */
switch (c)
{
case 'h': /* Print help and exit. */
cmdline_parser_print_help ();
cmdline_parser_free (&local_args_info);
exit (EXIT_SUCCESS);
case 'V': /* Print version and exit. */
cmdline_parser_print_version ();
cmdline_parser_free (&local_args_info);
exit (EXIT_SUCCESS);
case 'r': /* Renders target svg file to FileName.png. */
if (update_arg( (void *)&(args_info->render_png_arg),
&(args_info->render_png_orig), &(args_info->render_png_given),
&(local_args_info.render_png_given), optarg, 0, 0, ARG_STRING,
check_ambiguity, override, 0, 0,
"render-png", 'r',
additional_error))
goto failure;
break;
case 0: /* Long option with no short option */
if (strcmp (long_options[option_index].name, "full-help") == 0) {
cmdline_parser_print_full_help ();
cmdline_parser_free (&local_args_info);
exit (EXIT_SUCCESS);
}
/* Saves file to FileName.svg in svg format (for testing purposes). */
if (strcmp (long_options[option_index].name, "save") == 0)
{
if (update_arg( (void *)&(args_info->save_arg),
&(args_info->save_orig), &(args_info->save_given),
&(local_args_info.save_given), optarg, 0, 0, ARG_STRING,
check_ambiguity, override, 0, 0,
"save", '-',
additional_error))
goto failure;
}
break;
case '?': /* Invalid option. */
/* `getopt_long' already printed an error message. */
goto failure;
default: /* bug: option not considered. */
fprintf (stderr, "%s: option unknown: %c%s\n", CMDLINE_PARSER_PACKAGE, c, (additional_error ? additional_error : ""));
abort ();
} /* switch */
} /* while */
cmdline_parser_release (&local_args_info);
if ( error_occurred )
return (EXIT_FAILURE);
if (optind < argc)
{
int i = 0 ;
int found_prog_name = 0;
/* whether program name, i.e., argv[0], is in the remaining args
(this may happen with some implementations of getopt,
but surely not with the one included by gengetopt) */
args_info->inputs_num = argc - optind - found_prog_name;
args_info->inputs =
(char **)(malloc ((args_info->inputs_num)*sizeof(char *))) ;
while (optind < argc)
args_info->inputs[ i++ ] = gengetopt_strdup (argv[optind++]) ;
}
return 0;
failure:
cmdline_parser_release (&local_args_info);
return (EXIT_FAILURE);
}
| [
"predelnik@gmail.com"
] | predelnik@gmail.com |
a365cf2a2b1e41307d17a7af9ba25a6b009e5872 | 793c8848753f530aab28076a4077deac815af5ac | /src/dskphone/ui/t48/settingui/src/cdlgcustomforward.cpp | 6f654232844ca7141c334538bd497becd25f54f6 | [] | no_license | Parantido/sipphone | 4c1b9b18a7a6e478514fe0aadb79335e734bc016 | f402efb088bb42900867608cc9ccf15d9b946d7d | refs/heads/master | 2021-09-10T20:12:36.553640 | 2018-03-30T12:44:13 | 2018-03-30T12:44:13 | 263,628,242 | 1 | 0 | null | 2020-05-13T12:49:19 | 2020-05-13T12:49:18 | null | UTF-8 | C++ | false | false | 5,533 | cpp | #include "cdlgcustomforward.h"
#include "account/include/modaccount.h"
#include "settingui/include/modsettingui.h"
#include "qtcommon/qmisc.h"
#include "uikernel/languagehelper.h"
#include "uimanager/moduimanager.h"
#include "keymap.h"
#include "baseui/fontcolor.h"
#include "setting/src/callforwardcontroller.h"
CDlgCustomForward::CDlgCustomForward(QWidget * parent)
: CDlgBaseSubPage(parent)
, m_bEnableAccount(false)
{
m_strTitle = LANG_TRANSLATE(TRID_CUSTOM_FORWARD).toUtf8().data();
m_listForwardData.clear();
InitData();
}
CDlgCustomForward::~CDlgCustomForward()
{
}
void CDlgCustomForward::InitData()
{
if (NULL != m_pGeneralFrame)
{
m_pGeneralFrame->SetNote(LANG_TRANSLATE(TRID_NONE));
}
QWidgetPair qPair;
QString strLab;
//获取可用账号数据
ListAccounts listValidAccount = acc_GetAvailableAccountList();
int nIndex = 0;
ListAccounts::iterator itAccount = listValidAccount.begin();
for (/* */; itAccount != listValidAccount.end(); ++itAccount)
{
QLabel * pLabel = new QLabel(this);
if (NULL != pLabel)
{
// 设置字体颜色
SetWgtFontColor(pLabel, FONT_TYPE_TEXT);
//http://10.2.1.199/Bug.php?BugID=92700 改为和黑白屏一样统一通过acc_GetAccountShowText接口获取
yl::string strAccountDisplayName = acc_GetAccountShowText(*itAccount);
//设置Activation标签
strLab = toQString(strAccountDisplayName.c_str());
qPair.first = strLab;
qPair.second = pLabel;
qPair.third = "enter";
qPair.bWithStatus = true;
qPair.eType = SETTING_ITEM_MENU;
// 加入映射中
CustomForwardData ItemData;
ItemData.iAccountID = *itAccount;
ItemData.pLabel = pLabel;
ItemData.nIndex = nIndex;
m_listForwardData.push_back(ItemData);
m_vecWidgetPair.push_back(qPair);
nIndex++;
}
}
#ifdef IF_FEATURE_FORWARD_OPT
if (listValidAccount.size() > 1)
{
QLabel * pLabel = new QLabel(this);
if (NULL != pLabel)
{
// 设置字体颜色
SetWgtFontColor(pLabel, FONT_TYPE_TEXT);
//设置Activation标签
strLab = LANG_TRANSLATE(TRID_ALL_LINES);
qPair.first = strLab;
qPair.second = pLabel;
qPair.third = "enter";
qPair.bWithStatus = true;
qPair.eType = SETTING_ITEM_MENU;
CustomForwardData ItemData;
ItemData.iAccountID = -1;
ItemData.pLabel = pLabel;
ItemData.nIndex = nIndex++;
m_listForwardData.push_back(ItemData);
m_vecWidgetPair.push_back(qPair);
}
}
#endif
//设置为None的提示必须在AddWidget之后
AddWidget(m_vecWidgetPair, true, false, true, false);
// 无账号可用
m_bEnableAccount = (listValidAccount.size() != 0);
//为界面自己安装事件过滤器
this->installEventFilter(this);
}
// 设置子页面的SoftKey
bool CDlgCustomForward::GetSoftkeyData(CArraySoftKeyBarData & objWndData)
{
objWndData[3].m_strSoftkeyAction = "";
objWndData[3].m_strSoftkeyTitle = "";
return true;
}
// 对输入框的数据进行验证
bool CDlgCustomForward::IsInputDataValid(InputDataErrorInfo & objErrorContent)
{
return true;
}
//从V层读取当前界面的配置,通过C层保存
bool CDlgCustomForward::SavePageData()
{
return false;
}
//通过C层获取已有配置数据,通过V层在界面上显示出来
bool CDlgCustomForward::LoadPageData()
{
int nAccountID;
for (nAccountID = 0; nAccountID < acc_AccountNum(); nAccountID++)
{
IterForwardData itrBegin = m_listForwardData.begin();
for (; itrBegin != m_listForwardData.end(); ++itrBegin)
{
CustomForwardData & ItemData = *itrBegin;
if (ItemData.iAccountID == nAccountID)
{
// 从配置中读值
QString strText = g_pCallForwardController->IsForwardEnable(FWD_TYPE_ALL, ItemData.iAccountID)
? LANG_TRANSLATE(TRID_ON) : LANG_TRANSLATE(TRID_OFF);
ItemData.pLabel->setText(strText);
}
}
}
//给自己安装过滤器
this->installEventFilter(this);
return true;
}
//通过C层获取配置数据,与GetPageData值比较,有改动时返回true
bool CDlgCustomForward::IsStatusChanged()
{
return false;
}
bool CDlgCustomForward::OnAction(const QString & strAction)
{
bool bResult = false;
if (strAction == "enter")
{
//根据账号进入,显示
IterForwardData itrBegin = m_listForwardData.begin();
for (; itrBegin != m_listForwardData.end(); ++itrBegin)
{
if (itrBegin->nIndex == m_pGeneralFrame->GetFocusItemDataIndex())
{
SubMenuData subMenuData;
subMenuData.iFirstSelectItem = 0;
subMenuData.pBeforeSetSubpageData = (void *) & (itrBegin->iAccountID);
subMenuData.strMenuAction = "OpenSubPage(call_forward_option)";
emit openpage(subMenuData);
break;
}
}
bResult = true;
}
return bResult;
}
void CDlgCustomForward::showEvent(QShowEvent * e)
{
//从CDlgCustomForwardOption子界面返回,需重新下载数据
LoadPageData();
}
| [
"rongxx@yealink.com"
] | rongxx@yealink.com |
8bb3dfade91d35731dc58e39ace895c2cb94d16c | 77f8410a1b13402b33806ac45263a61d0c3aba90 | /v8/src/builtins/builtins-collections-gen.cc | 476c4833f71d0542cf506cb0d1ac65b26e982e23 | [] | no_license | ngot/libv8 | 93d5a874cffce7373bb13f4cba343d7e906524a5 | 34abbc81c745a896221918e75dc8658337c7a1f1 | refs/heads/master | 2021-06-26T07:31:23.672284 | 2017-09-15T16:22:01 | 2017-09-15T16:22:01 | 103,535,365 | 17 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 72,012 | cc | // Copyright 2017 the V8 project 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 "src/builtins/builtins-constructor-gen.h"
#include "src/builtins/builtins-iterator-gen.h"
#include "src/builtins/builtins-utils-gen.h"
#include "src/code-stub-assembler.h"
#include "src/factory-inl.h"
#include "src/objects/hash-table.h"
namespace v8 {
namespace internal {
using compiler::Node;
class CollectionsBuiltinsAssembler : public CodeStubAssembler {
public:
explicit CollectionsBuiltinsAssembler(compiler::CodeAssemblerState* state)
: CodeStubAssembler(state) {}
protected:
Node* AllocateJSMap(Node* js_map_function);
template <typename CollectionType>
Node* AllocateOrderedHashTable();
Node* AllocateJSCollection(Node* js_map_function);
template <typename IteratorType>
Node* AllocateJSCollectionIterator(Node* context, int map_index,
Node* collection);
Node* GetHash(Node* const key);
Node* CallGetHashRaw(Node* const key);
Node* CallGetOrCreateHashRaw(Node* const key);
// Transitions the iterator to the non obsolete backing store.
// This is a NOP if the [table] is not obsolete.
typedef std::function<void(Node* const table, Node* const index)>
UpdateInTransition;
template <typename TableType>
std::tuple<Node*, Node*> Transition(
Node* const table, Node* const index,
UpdateInTransition const& update_in_transition);
template <typename IteratorType, typename TableType>
std::tuple<Node*, Node*> TransitionAndUpdate(Node* const iterator);
template <typename TableType>
std::tuple<Node*, Node*, Node*> NextSkipHoles(Node* table, Node* index,
Label* if_end);
// Builds code that finds OrderedHashTable entry for a key with hash code
// {hash} with using the comparison code generated by {key_compare}. The code
// jumps to {entry_found} if the key is found, or to {not_found} if the key
// was not found. In the {entry_found} branch, the variable
// entry_start_position will be bound to the index of the entry (relative to
// OrderedHashTable::kHashTableStartIndex).
//
// The {CollectionType} template parameter stands for the particular instance
// of OrderedHashTable, it should be OrderedHashMap or OrderedHashSet.
template <typename CollectionType>
void FindOrderedHashTableEntry(
Node* table, Node* hash,
std::function<void(Node* other, Label* if_same, Label* if_not_same)>
key_compare,
Variable* entry_start_position, Label* entry_found, Label* not_found);
// Specialization for Smi.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise.
template <typename CollectionType>
void FindOrderedHashTableEntryForSmiKey(Node* table, Node* key_tagged,
Variable* result, Label* entry_found,
Label* not_found);
void SameValueZeroSmi(Node* key_smi, Node* candidate_key, Label* if_same,
Label* if_not_same);
// Specialization for heap numbers.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise.
void SameValueZeroHeapNumber(Node* key_string, Node* candidate_key,
Label* if_same, Label* if_not_same);
template <typename CollectionType>
void FindOrderedHashTableEntryForHeapNumberKey(Node* context, Node* table,
Node* key_heap_number,
Variable* result,
Label* entry_found,
Label* not_found);
// Specialization for bigints.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise.
void SameValueZeroBigInt(Node* key, Node* candidate_key, Label* if_same,
Label* if_not_same);
template <typename CollectionType>
void FindOrderedHashTableEntryForBigIntKey(Node* context, Node* table,
Node* key, Variable* result,
Label* entry_found,
Label* not_found);
// Specialization for string.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise.
template <typename CollectionType>
void FindOrderedHashTableEntryForStringKey(Node* context, Node* table,
Node* key_tagged, Variable* result,
Label* entry_found,
Label* not_found);
Node* ComputeIntegerHashForString(Node* context, Node* string_key);
void SameValueZeroString(Node* context, Node* key_string, Node* candidate_key,
Label* if_same, Label* if_not_same);
// Specialization for non-strings, non-numbers. For those we only need
// reference equality to compare the keys.
// The {result} variable will contain the entry index if the key was found,
// or the hash code otherwise. If the hash-code has not been computed, it
// should be Smi -1.
template <typename CollectionType>
void FindOrderedHashTableEntryForOtherKey(Node* context, Node* table,
Node* key, Variable* result,
Label* entry_found,
Label* not_found);
template <typename CollectionType>
void TryLookupOrderedHashTableIndex(Node* const table, Node* const key,
Node* const context, Variable* result,
Label* if_entry_found,
Label* if_not_found);
Node* NormalizeNumberKey(Node* key);
void StoreOrderedHashMapNewEntry(Node* const table, Node* const key,
Node* const value, Node* const hash,
Node* const number_of_buckets,
Node* const occupancy);
void StoreOrderedHashSetNewEntry(Node* const table, Node* const key,
Node* const hash,
Node* const number_of_buckets,
Node* const occupancy);
};
template <typename CollectionType>
Node* CollectionsBuiltinsAssembler::AllocateOrderedHashTable() {
static const int kCapacity = CollectionType::kMinCapacity;
static const int kBucketCount = kCapacity / CollectionType::kLoadFactor;
static const int kDataTableLength = kCapacity * CollectionType::kEntrySize;
static const int kFixedArrayLength =
CollectionType::kHashTableStartIndex + kBucketCount + kDataTableLength;
static const int kDataTableStartIndex =
CollectionType::kHashTableStartIndex + kBucketCount;
STATIC_ASSERT(base::bits::IsPowerOfTwo(kCapacity));
STATIC_ASSERT(kCapacity <= CollectionType::kMaxCapacity);
// Allocate the table and add the proper map.
const ElementsKind elements_kind = HOLEY_ELEMENTS;
Node* const length_intptr = IntPtrConstant(kFixedArrayLength);
Node* const table = AllocateFixedArray(elements_kind, length_intptr);
CSA_ASSERT(this,
IntPtrLessThanOrEqual(
length_intptr, IntPtrConstant(FixedArray::kMaxRegularLength)));
Heap::RootListIndex map_index = Heap::kOrderedHashTableMapRootIndex;
// TODO(gsathya): Directly store correct in AllocateFixedArray,
// instead of overwriting here.
StoreMapNoWriteBarrier(table, map_index);
// Initialize the OrderedHashTable fields.
const WriteBarrierMode barrier_mode = SKIP_WRITE_BARRIER;
StoreFixedArrayElement(table, CollectionType::kNumberOfElementsIndex,
SmiConstant(0), barrier_mode);
StoreFixedArrayElement(table, CollectionType::kNumberOfDeletedElementsIndex,
SmiConstant(0), barrier_mode);
StoreFixedArrayElement(table, CollectionType::kNumberOfBucketsIndex,
SmiConstant(kBucketCount), barrier_mode);
// Fill the buckets with kNotFound.
Node* const not_found = SmiConstant(CollectionType::kNotFound);
STATIC_ASSERT(CollectionType::kHashTableStartIndex ==
CollectionType::kNumberOfBucketsIndex + 1);
STATIC_ASSERT((CollectionType::kHashTableStartIndex + kBucketCount) ==
kDataTableStartIndex);
for (int i = 0; i < kBucketCount; i++) {
StoreFixedArrayElement(table, CollectionType::kHashTableStartIndex + i,
not_found, barrier_mode);
}
// Fill the data table with undefined.
STATIC_ASSERT(kDataTableStartIndex + kDataTableLength == kFixedArrayLength);
for (int i = 0; i < kDataTableLength; i++) {
StoreFixedArrayElement(table, kDataTableStartIndex + i, UndefinedConstant(),
barrier_mode);
}
return table;
}
Node* CollectionsBuiltinsAssembler::AllocateJSCollection(
Node* js_map_function) {
CSA_ASSERT(this, IsConstructorMap(LoadMap(js_map_function)));
Node* const initial_map = LoadObjectField(
js_map_function, JSFunction::kPrototypeOrInitialMapOffset);
Node* const instance = AllocateJSObjectFromMap(initial_map);
StoreObjectFieldRoot(instance, JSMap::kTableOffset,
Heap::kUndefinedValueRootIndex);
return instance;
}
template <typename IteratorType>
Node* CollectionsBuiltinsAssembler::AllocateJSCollectionIterator(
Node* context, int map_index, Node* collection) {
Node* const table = LoadObjectField(collection, JSCollection::kTableOffset);
Node* const native_context = LoadNativeContext(context);
Node* const iterator_map = LoadContextElement(native_context, map_index);
Node* const iterator = AllocateInNewSpace(IteratorType::kSize);
StoreMapNoWriteBarrier(iterator, iterator_map);
StoreObjectFieldRoot(iterator, IteratorType::kPropertiesOrHashOffset,
Heap::kEmptyFixedArrayRootIndex);
StoreObjectFieldRoot(iterator, IteratorType::kElementsOffset,
Heap::kEmptyFixedArrayRootIndex);
StoreObjectFieldNoWriteBarrier(iterator, IteratorType::kTableOffset, table);
StoreObjectFieldNoWriteBarrier(iterator, IteratorType::kIndexOffset,
SmiConstant(0));
return iterator;
}
TF_BUILTIN(MapConstructor, CollectionsBuiltinsAssembler) {
const int kIterableArg = 0;
Node* argc =
ChangeInt32ToIntPtr(Parameter(BuiltinDescriptor::kArgumentsCount));
CodeStubArguments args(this, argc);
Node* const iterable = args.GetOptionalArgumentValue(kIterableArg);
Node* const new_target = Parameter(BuiltinDescriptor::kNewTarget);
Node* const context = Parameter(BuiltinDescriptor::kContext);
Label if_target_is_undefined(this, Label::kDeferred);
GotoIf(IsUndefined(new_target), &if_target_is_undefined);
Node* const native_context = LoadNativeContext(context);
Node* const js_map_fun =
LoadContextElement(native_context, Context::JS_MAP_FUN_INDEX);
VARIABLE(var_result, MachineRepresentation::kTagged);
Label init(this), exit(this), if_targetisnotmodified(this),
if_targetismodified(this);
Branch(WordEqual(js_map_fun, new_target), &if_targetisnotmodified,
&if_targetismodified);
BIND(&if_targetisnotmodified);
{
Node* const instance = AllocateJSCollection(js_map_fun);
var_result.Bind(instance);
Goto(&init);
}
BIND(&if_targetismodified);
{
ConstructorBuiltinsAssembler constructor_assembler(this->state());
Node* const instance = constructor_assembler.EmitFastNewObject(
context, js_map_fun, new_target);
var_result.Bind(instance);
Goto(&init);
}
BIND(&init);
Node* table = AllocateOrderedHashTable<OrderedHashMap>();
StoreObjectField(var_result.value(), JSMap::kTableOffset, table);
GotoIf(Word32Or(IsUndefined(iterable), IsNull(iterable)), &exit);
Label if_notcallable(this);
// TODO(gsathya): Add fast path for unmodified maps.
Node* const adder = GetProperty(context, var_result.value(),
isolate()->factory()->set_string());
GotoIf(TaggedIsSmi(adder), &if_notcallable);
GotoIfNot(IsCallable(adder), &if_notcallable);
IteratorBuiltinsAssembler iterator_assembler(this->state());
Node* const iterator = iterator_assembler.GetIterator(context, iterable);
GotoIf(IsUndefined(iterator), &exit);
Node* const fast_iterator_result_map =
LoadContextElement(native_context, Context::ITERATOR_RESULT_MAP_INDEX);
VARIABLE(var_exception, MachineRepresentation::kTagged, TheHoleConstant());
Label loop(this), if_notobject(this), if_exception(this);
Goto(&loop);
BIND(&loop);
{
Node* const next = iterator_assembler.IteratorStep(
context, iterator, &exit, fast_iterator_result_map);
Node* const next_value = iterator_assembler.IteratorValue(
context, next, fast_iterator_result_map);
GotoIf(TaggedIsSmi(next_value), &if_notobject);
GotoIfNot(IsJSReceiver(next_value), &if_notobject);
Node* const k =
GetProperty(context, next_value, isolate()->factory()->zero_string());
GotoIfException(k, &if_exception, &var_exception);
Node* const v =
GetProperty(context, next_value, isolate()->factory()->one_string());
GotoIfException(v, &if_exception, &var_exception);
Node* add_call = CallJS(CodeFactory::Call(isolate()), context, adder,
var_result.value(), k, v);
GotoIfException(add_call, &if_exception, &var_exception);
Goto(&loop);
BIND(&if_notobject);
{
Node* const exception = MakeTypeError(
MessageTemplate::kIteratorValueNotAnObject, context, next_value);
var_exception.Bind(exception);
Goto(&if_exception);
}
}
BIND(&if_exception);
{
iterator_assembler.IteratorCloseOnException(context, iterator,
&var_exception);
}
BIND(&if_notcallable);
{
Node* const receiver_str = HeapConstant(isolate()->factory()->add_string());
ThrowTypeError(context, MessageTemplate::kPropertyNotFunction, adder,
receiver_str, var_result.value());
}
BIND(&if_target_is_undefined);
ThrowTypeError(context, MessageTemplate::kConstructorNotFunction,
HeapConstant(isolate()->factory()->Map_string()));
BIND(&exit);
args.PopAndReturn(var_result.value());
}
TF_BUILTIN(SetConstructor, CollectionsBuiltinsAssembler) {
const int kIterableArg = 0;
Node* argc =
ChangeInt32ToIntPtr(Parameter(BuiltinDescriptor::kArgumentsCount));
CodeStubArguments args(this, argc);
Node* const iterable = args.GetOptionalArgumentValue(kIterableArg);
Node* const new_target = Parameter(BuiltinDescriptor::kNewTarget);
Node* const context = Parameter(BuiltinDescriptor::kContext);
Label if_target_is_undefined(this, Label::kDeferred);
GotoIf(IsUndefined(new_target), &if_target_is_undefined);
Node* const native_context = LoadNativeContext(context);
Node* const js_set_fun =
LoadContextElement(native_context, Context::JS_SET_FUN_INDEX);
VARIABLE(var_result, MachineRepresentation::kTagged);
Label init(this), exit(this), if_targetisnotmodified(this),
if_targetismodified(this);
Branch(WordEqual(js_set_fun, new_target), &if_targetisnotmodified,
&if_targetismodified);
BIND(&if_targetisnotmodified);
{
Node* const instance = AllocateJSCollection(js_set_fun);
var_result.Bind(instance);
Goto(&init);
}
BIND(&if_targetismodified);
{
ConstructorBuiltinsAssembler constructor_assembler(this->state());
Node* const instance = constructor_assembler.EmitFastNewObject(
context, js_set_fun, new_target);
var_result.Bind(instance);
Goto(&init);
}
BIND(&init);
Node* table = AllocateOrderedHashTable<OrderedHashSet>();
StoreObjectField(var_result.value(), JSSet::kTableOffset, table);
GotoIf(Word32Or(IsUndefined(iterable), IsNull(iterable)), &exit);
Label if_notcallable(this);
// TODO(gsathya): Add fast path for unmodified maps.
Node* const adder = GetProperty(context, var_result.value(),
isolate()->factory()->add_string());
GotoIf(TaggedIsSmi(adder), &if_notcallable);
GotoIfNot(IsCallable(adder), &if_notcallable);
IteratorBuiltinsAssembler iterator_assembler(this->state());
Node* const iterator = iterator_assembler.GetIterator(context, iterable);
GotoIf(IsUndefined(iterator), &exit);
Node* const fast_iterator_result_map =
LoadContextElement(native_context, Context::ITERATOR_RESULT_MAP_INDEX);
VARIABLE(var_exception, MachineRepresentation::kTagged, TheHoleConstant());
Label loop(this), if_notobject(this), if_exception(this);
Goto(&loop);
BIND(&loop);
{
Node* const next = iterator_assembler.IteratorStep(
context, iterator, &exit, fast_iterator_result_map);
Node* const next_value = iterator_assembler.IteratorValue(
context, next, fast_iterator_result_map);
Node* add_call = CallJS(CodeFactory::Call(isolate()), context, adder,
var_result.value(), next_value);
GotoIfException(add_call, &if_exception, &var_exception);
Goto(&loop);
}
BIND(&if_exception);
{
iterator_assembler.IteratorCloseOnException(context, iterator,
&var_exception);
}
BIND(&if_notcallable);
ThrowTypeError(context, MessageTemplate::kPropertyNotFunction, adder,
HeapConstant(isolate()->factory()->add_string()),
var_result.value());
BIND(&if_target_is_undefined);
ThrowTypeError(context, MessageTemplate::kConstructorNotFunction,
HeapConstant(isolate()->factory()->Set_string()));
BIND(&exit);
args.PopAndReturn(var_result.value());
}
Node* CollectionsBuiltinsAssembler::CallGetOrCreateHashRaw(Node* const key) {
Node* const function_addr =
ExternalConstant(ExternalReference::get_or_create_hash_raw(isolate()));
Node* const isolate_ptr =
ExternalConstant(ExternalReference::isolate_address(isolate()));
MachineType type_ptr = MachineType::Pointer();
MachineType type_tagged = MachineType::AnyTagged();
Node* const result = CallCFunction2(type_tagged, type_ptr, type_tagged,
function_addr, isolate_ptr, key);
return result;
}
Node* CollectionsBuiltinsAssembler::CallGetHashRaw(Node* const key) {
Node* const function_addr = ExternalConstant(
ExternalReference::orderedhashmap_gethash_raw(isolate()));
Node* const isolate_ptr =
ExternalConstant(ExternalReference::isolate_address(isolate()));
MachineType type_ptr = MachineType::Pointer();
MachineType type_tagged = MachineType::AnyTagged();
Node* const result = CallCFunction2(type_tagged, type_ptr, type_tagged,
function_addr, isolate_ptr, key);
return SmiUntag(result);
}
Node* CollectionsBuiltinsAssembler::GetHash(Node* const key) {
VARIABLE(var_result, MachineType::PointerRepresentation());
Label if_jsobject(this), other(this), done(this);
Node* instance_type = LoadMapInstanceType(LoadMap(key));
Branch(IsJSObjectInstanceType(instance_type), &if_jsobject, &other);
BIND(&if_jsobject);
{
Node* hash = LoadHashForJSObject(key, instance_type);
// TODO(gsathya): Change all uses of -1 to PropertyArray::kNoHashSentinel.
var_result.Bind(SelectConstant(
Word32Equal(hash, Int32Constant(PropertyArray::kNoHashSentinel)),
IntPtrConstant(-1), ChangeInt32ToIntPtr(hash),
MachineType::PointerRepresentation()));
Goto(&done);
}
BIND(&other);
{
var_result.Bind(CallGetHashRaw(key));
Goto(&done);
}
BIND(&done);
return var_result.value();
}
void CollectionsBuiltinsAssembler::SameValueZeroSmi(Node* key_smi,
Node* candidate_key,
Label* if_same,
Label* if_not_same) {
// If the key is the same, we are done.
GotoIf(WordEqual(candidate_key, key_smi), if_same);
// If the candidate key is smi, then it must be different (because
// we already checked for equality above).
GotoIf(TaggedIsSmi(candidate_key), if_not_same);
// If the candidate key is not smi, we still have to check if it is a
// heap number with the same value.
GotoIfNot(IsHeapNumber(candidate_key), if_not_same);
Node* const candidate_key_number = LoadHeapNumberValue(candidate_key);
Node* const key_number = SmiToFloat64(key_smi);
GotoIf(Float64Equal(candidate_key_number, key_number), if_same);
Goto(if_not_same);
}
template <typename CollectionType>
void CollectionsBuiltinsAssembler::FindOrderedHashTableEntryForSmiKey(
Node* table, Node* smi_key, Variable* result, Label* entry_found,
Label* not_found) {
Node* const key_untagged = SmiUntag(smi_key);
Node* const hash =
ChangeInt32ToIntPtr(ComputeIntegerHash(key_untagged, Int32Constant(0)));
CSA_ASSERT(this, IntPtrGreaterThanOrEqual(hash, IntPtrConstant(0)));
result->Bind(hash);
FindOrderedHashTableEntry<CollectionType>(
table, hash,
[&](Node* other_key, Label* if_same, Label* if_not_same) {
SameValueZeroSmi(smi_key, other_key, if_same, if_not_same);
},
result, entry_found, not_found);
}
template <typename CollectionType>
void CollectionsBuiltinsAssembler::FindOrderedHashTableEntryForStringKey(
Node* context, Node* table, Node* key_tagged, Variable* result,
Label* entry_found, Label* not_found) {
Node* const hash = ComputeIntegerHashForString(context, key_tagged);
CSA_ASSERT(this, IntPtrGreaterThanOrEqual(hash, IntPtrConstant(0)));
result->Bind(hash);
FindOrderedHashTableEntry<CollectionType>(
table, hash,
[&](Node* other_key, Label* if_same, Label* if_not_same) {
SameValueZeroString(context, key_tagged, other_key, if_same,
if_not_same);
},
result, entry_found, not_found);
}
template <typename CollectionType>
void CollectionsBuiltinsAssembler::FindOrderedHashTableEntryForHeapNumberKey(
Node* context, Node* table, Node* key_heap_number, Variable* result,
Label* entry_found, Label* not_found) {
Node* hash = CallGetHashRaw(key_heap_number);
CSA_ASSERT(this, IntPtrGreaterThanOrEqual(hash, IntPtrConstant(0)));
result->Bind(hash);
Node* const key_float = LoadHeapNumberValue(key_heap_number);
FindOrderedHashTableEntry<CollectionType>(
table, hash,
[&](Node* other_key, Label* if_same, Label* if_not_same) {
SameValueZeroHeapNumber(key_float, other_key, if_same, if_not_same);
},
result, entry_found, not_found);
}
template <typename CollectionType>
void CollectionsBuiltinsAssembler::FindOrderedHashTableEntryForBigIntKey(
Node* context, Node* table, Node* key, Variable* result, Label* entry_found,
Label* not_found) {
Node* hash = CallGetHashRaw(key);
CSA_ASSERT(this, IntPtrGreaterThanOrEqual(hash, IntPtrConstant(0)));
result->Bind(hash);
FindOrderedHashTableEntry<CollectionType>(
table, hash,
[&](Node* other_key, Label* if_same, Label* if_not_same) {
SameValueZeroBigInt(key, other_key, if_same, if_not_same);
},
result, entry_found, not_found);
}
template <typename CollectionType>
void CollectionsBuiltinsAssembler::FindOrderedHashTableEntryForOtherKey(
Node* context, Node* table, Node* key, Variable* result, Label* entry_found,
Label* not_found) {
Node* hash = GetHash(key);
result->Bind(hash);
FindOrderedHashTableEntry<CollectionType>(
table, hash,
[&](Node* other_key, Label* if_same, Label* if_not_same) {
Branch(WordEqual(key, other_key), if_same, if_not_same);
},
result, entry_found, not_found);
}
Node* CollectionsBuiltinsAssembler::ComputeIntegerHashForString(
Node* context, Node* string_key) {
VARIABLE(var_result, MachineType::PointerRepresentation());
Label hash_not_computed(this), done(this, &var_result);
Node* hash =
ChangeInt32ToIntPtr(LoadNameHash(string_key, &hash_not_computed));
var_result.Bind(hash);
Goto(&done);
BIND(&hash_not_computed);
var_result.Bind(CallGetHashRaw(string_key));
Goto(&done);
BIND(&done);
return var_result.value();
}
void CollectionsBuiltinsAssembler::SameValueZeroString(Node* context,
Node* key_string,
Node* candidate_key,
Label* if_same,
Label* if_not_same) {
// If the candidate is not a string, the keys are not equal.
GotoIf(TaggedIsSmi(candidate_key), if_not_same);
GotoIfNot(IsString(candidate_key), if_not_same);
Branch(WordEqual(CallBuiltin(Builtins::kStringEqual, context, key_string,
candidate_key),
TrueConstant()),
if_same, if_not_same);
}
void CollectionsBuiltinsAssembler::SameValueZeroBigInt(Node* key,
Node* candidate_key,
Label* if_same,
Label* if_not_same) {
CSA_ASSERT(this, IsBigInt(key));
GotoIf(TaggedIsSmi(candidate_key), if_not_same);
GotoIfNot(IsBigInt(candidate_key), if_not_same);
Branch(WordEqual(CallRuntime(Runtime::kBigIntEqual, NoContextConstant(), key,
candidate_key),
TrueConstant()),
if_same, if_not_same);
}
void CollectionsBuiltinsAssembler::SameValueZeroHeapNumber(Node* key_float,
Node* candidate_key,
Label* if_same,
Label* if_not_same) {
Label if_smi(this), if_keyisnan(this);
GotoIf(TaggedIsSmi(candidate_key), &if_smi);
GotoIfNot(IsHeapNumber(candidate_key), if_not_same);
{
// {candidate_key} is a heap number.
Node* const candidate_float = LoadHeapNumberValue(candidate_key);
GotoIf(Float64Equal(key_float, candidate_float), if_same);
// SameValueZero needs to treat NaNs as equal. First check if {key_float}
// is NaN.
BranchIfFloat64IsNaN(key_float, &if_keyisnan, if_not_same);
BIND(&if_keyisnan);
{
// Return true iff {candidate_key} is NaN.
Branch(Float64Equal(candidate_float, candidate_float), if_not_same,
if_same);
}
}
BIND(&if_smi);
{
Node* const candidate_float = SmiToFloat64(candidate_key);
Branch(Float64Equal(key_float, candidate_float), if_same, if_not_same);
}
}
template <typename CollectionType>
void CollectionsBuiltinsAssembler::FindOrderedHashTableEntry(
Node* table, Node* hash,
std::function<void(Node*, Label*, Label*)> key_compare,
Variable* entry_start_position, Label* entry_found, Label* not_found) {
// Get the index of the bucket.
Node* const number_of_buckets = SmiUntag(
LoadFixedArrayElement(table, CollectionType::kNumberOfBucketsIndex));
Node* const bucket =
WordAnd(hash, IntPtrSub(number_of_buckets, IntPtrConstant(1)));
Node* const first_entry = SmiUntag(LoadFixedArrayElement(
table, bucket, CollectionType::kHashTableStartIndex * kPointerSize));
// Walk the bucket chain.
Node* entry_start;
Label if_key_found(this);
{
VARIABLE(var_entry, MachineType::PointerRepresentation(), first_entry);
Label loop(this, {&var_entry, entry_start_position}),
continue_next_entry(this);
Goto(&loop);
BIND(&loop);
// If the entry index is the not-found sentinel, we are done.
GotoIf(
WordEqual(var_entry.value(), IntPtrConstant(CollectionType::kNotFound)),
not_found);
// Make sure the entry index is within range.
CSA_ASSERT(
this,
UintPtrLessThan(
var_entry.value(),
SmiUntag(SmiAdd(
LoadFixedArrayElement(table,
CollectionType::kNumberOfElementsIndex),
LoadFixedArrayElement(
table, CollectionType::kNumberOfDeletedElementsIndex)))));
// Compute the index of the entry relative to kHashTableStartIndex.
entry_start =
IntPtrAdd(IntPtrMul(var_entry.value(),
IntPtrConstant(CollectionType::kEntrySize)),
number_of_buckets);
// Load the key from the entry.
Node* const candidate_key = LoadFixedArrayElement(
table, entry_start,
CollectionType::kHashTableStartIndex * kPointerSize);
key_compare(candidate_key, &if_key_found, &continue_next_entry);
BIND(&continue_next_entry);
// Load the index of the next entry in the bucket chain.
var_entry.Bind(SmiUntag(LoadFixedArrayElement(
table, entry_start,
(CollectionType::kHashTableStartIndex + CollectionType::kChainOffset) *
kPointerSize)));
Goto(&loop);
}
BIND(&if_key_found);
entry_start_position->Bind(entry_start);
Goto(entry_found);
}
TF_BUILTIN(OrderedHashTableHealIndex, CollectionsBuiltinsAssembler) {
Node* table = Parameter(Descriptor::kTable);
Node* index = Parameter(Descriptor::kIndex);
CSA_ASSERT(this, TaggedIsNotSmi(table));
CSA_ASSERT(this, TaggedIsSmi(index));
Label return_index(this), return_zero(this);
// Check if we need to update the {index}.
GotoIfNot(SmiLessThan(SmiConstant(Smi::kZero), index), &return_zero);
// Check if the {table} was cleared.
Node* number_of_deleted_elements = LoadAndUntagObjectField(
table, OrderedHashTableBase::kNumberOfDeletedElementsOffset);
GotoIf(WordEqual(number_of_deleted_elements,
IntPtrConstant(OrderedHashTableBase::kClearedTableSentinel)),
&return_zero);
VARIABLE(var_i, MachineType::PointerRepresentation(), IntPtrConstant(0));
VARIABLE(var_index, MachineRepresentation::kTagged, index);
Label loop(this, {&var_i, &var_index});
Goto(&loop);
BIND(&loop);
{
Node* i = var_i.value();
GotoIfNot(IntPtrLessThan(i, number_of_deleted_elements), &return_index);
Node* removed_index = LoadFixedArrayElement(
table, i, OrderedHashTableBase::kRemovedHolesIndex * kPointerSize);
GotoIf(SmiGreaterThanOrEqual(removed_index, index), &return_index);
Decrement(&var_index, 1, SMI_PARAMETERS);
Increment(&var_i);
Goto(&loop);
}
BIND(&return_index);
Return(var_index.value());
BIND(&return_zero);
Return(SmiConstant(Smi::kZero));
}
template <typename TableType>
std::tuple<Node*, Node*> CollectionsBuiltinsAssembler::Transition(
Node* const table, Node* const index,
UpdateInTransition const& update_in_transition) {
VARIABLE(var_index, MachineType::PointerRepresentation(), index);
VARIABLE(var_table, MachineRepresentation::kTagged, table);
Label if_done(this), if_transition(this, Label::kDeferred);
Branch(TaggedIsSmi(
LoadObjectField(var_table.value(), TableType::kNextTableOffset)),
&if_done, &if_transition);
BIND(&if_transition);
{
Label loop(this, {&var_table, &var_index}), done_loop(this);
Goto(&loop);
BIND(&loop);
{
Node* table = var_table.value();
Node* index = var_index.value();
Node* next_table = LoadObjectField(table, TableType::kNextTableOffset);
GotoIf(TaggedIsSmi(next_table), &done_loop);
var_table.Bind(next_table);
var_index.Bind(
SmiUntag(CallBuiltin(Builtins::kOrderedHashTableHealIndex,
NoContextConstant(), table, SmiTag(index))));
Goto(&loop);
}
BIND(&done_loop);
// Update with the new {table} and {index}.
update_in_transition(var_table.value(), var_index.value());
Goto(&if_done);
}
BIND(&if_done);
return std::tuple<Node*, Node*>(var_table.value(), var_index.value());
}
template <typename IteratorType, typename TableType>
std::tuple<Node*, Node*> CollectionsBuiltinsAssembler::TransitionAndUpdate(
Node* const iterator) {
return Transition<TableType>(
LoadObjectField(iterator, IteratorType::kTableOffset),
LoadAndUntagObjectField(iterator, IteratorType::kIndexOffset),
[this, iterator](Node* const table, Node* const index) {
// Update the {iterator} with the new state.
StoreObjectField(iterator, IteratorType::kTableOffset, table);
StoreObjectFieldNoWriteBarrier(iterator, IteratorType::kIndexOffset,
SmiTag(index));
});
}
template <typename TableType>
std::tuple<Node*, Node*, Node*> CollectionsBuiltinsAssembler::NextSkipHoles(
Node* table, Node* index, Label* if_end) {
// Compute the used capacity for the {table}.
Node* number_of_buckets =
LoadAndUntagObjectField(table, TableType::kNumberOfBucketsOffset);
Node* number_of_elements =
LoadAndUntagObjectField(table, TableType::kNumberOfElementsOffset);
Node* number_of_deleted_elements =
LoadAndUntagObjectField(table, TableType::kNumberOfDeletedElementsOffset);
Node* used_capacity =
IntPtrAdd(number_of_elements, number_of_deleted_elements);
Node* entry_key;
Node* entry_start_position;
VARIABLE(var_index, MachineType::PointerRepresentation(), index);
Label loop(this, &var_index), done_loop(this);
Goto(&loop);
BIND(&loop);
{
GotoIfNot(IntPtrLessThan(var_index.value(), used_capacity), if_end);
entry_start_position = IntPtrAdd(
IntPtrMul(var_index.value(), IntPtrConstant(TableType::kEntrySize)),
number_of_buckets);
entry_key =
LoadFixedArrayElement(table, entry_start_position,
TableType::kHashTableStartIndex * kPointerSize);
Increment(&var_index);
Branch(IsTheHole(entry_key), &loop, &done_loop);
}
BIND(&done_loop);
return std::tuple<Node*, Node*, Node*>(entry_key, entry_start_position,
var_index.value());
}
TF_BUILTIN(MapGet, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_MAP_TYPE, "Map.prototype.get");
Node* const table = LoadObjectField(receiver, JSMap::kTableOffset);
Node* index = CallBuiltin(Builtins::kMapLookupHashIndex, context, table, key);
Label if_found(this), if_not_found(this);
Branch(SmiGreaterThanOrEqual(index, SmiConstant(0)), &if_found,
&if_not_found);
BIND(&if_found);
Return(LoadFixedArrayElement(table, SmiUntag(index)));
BIND(&if_not_found);
Return(UndefinedConstant());
}
TF_BUILTIN(MapHas, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_MAP_TYPE, "Map.prototype.has");
Node* const table = LoadObjectField(receiver, JSMap::kTableOffset);
Node* index = CallBuiltin(Builtins::kMapLookupHashIndex, context, table, key);
Label if_found(this), if_not_found(this);
Branch(SmiGreaterThanOrEqual(index, SmiConstant(0)), &if_found,
&if_not_found);
BIND(&if_found);
Return(TrueConstant());
BIND(&if_not_found);
Return(FalseConstant());
}
Node* CollectionsBuiltinsAssembler::NormalizeNumberKey(Node* const key) {
VARIABLE(result, MachineRepresentation::kTagged, key);
Label done(this);
GotoIf(TaggedIsSmi(key), &done);
GotoIfNot(IsHeapNumber(key), &done);
Node* const number = LoadHeapNumberValue(key);
GotoIfNot(Float64Equal(number, Float64Constant(0.0)), &done);
// We know the value is zero, so we take the key to be Smi 0.
// Another option would be to normalize to Smi here.
result.Bind(SmiConstant(0));
Goto(&done);
BIND(&done);
return result.value();
}
TF_BUILTIN(MapSet, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* key = Parameter(Descriptor::kKey);
Node* const value = Parameter(Descriptor::kValue);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_MAP_TYPE, "Map.prototype.set");
key = NormalizeNumberKey(key);
Node* const table = LoadObjectField(receiver, JSMap::kTableOffset);
VARIABLE(entry_start_position_or_hash, MachineType::PointerRepresentation(),
IntPtrConstant(0));
Label entry_found(this), not_found(this);
TryLookupOrderedHashTableIndex<OrderedHashMap>(table, key, context,
&entry_start_position_or_hash,
&entry_found, ¬_found);
BIND(&entry_found);
// If we found the entry, we just store the value there.
StoreFixedArrayElement(table, entry_start_position_or_hash.value(), value,
UPDATE_WRITE_BARRIER,
kPointerSize * (OrderedHashMap::kHashTableStartIndex +
OrderedHashMap::kValueOffset));
Return(receiver);
Label no_hash(this), add_entry(this), store_new_entry(this);
BIND(¬_found);
{
// If we have a hash code, we can start adding the new entry.
GotoIf(IntPtrGreaterThanOrEqual(entry_start_position_or_hash.value(),
IntPtrConstant(0)),
&add_entry);
// Otherwise, go to runtime to compute the hash code.
entry_start_position_or_hash.Bind(SmiUntag(CallGetOrCreateHashRaw(key)));
Goto(&add_entry);
}
BIND(&add_entry);
VARIABLE(number_of_buckets, MachineType::PointerRepresentation());
VARIABLE(occupancy, MachineType::PointerRepresentation());
VARIABLE(table_var, MachineRepresentation::kTaggedPointer, table);
{
// Check we have enough space for the entry.
number_of_buckets.Bind(SmiUntag(
LoadFixedArrayElement(table, OrderedHashMap::kNumberOfBucketsIndex)));
STATIC_ASSERT(OrderedHashMap::kLoadFactor == 2);
Node* const capacity = WordShl(number_of_buckets.value(), 1);
Node* const number_of_elements = SmiUntag(
CAST(LoadObjectField(table, OrderedHashMap::kNumberOfElementsOffset)));
Node* const number_of_deleted = SmiUntag(CAST(LoadObjectField(
table, OrderedHashMap::kNumberOfDeletedElementsOffset)));
occupancy.Bind(IntPtrAdd(number_of_elements, number_of_deleted));
GotoIf(IntPtrLessThan(occupancy.value(), capacity), &store_new_entry);
// We do not have enough space, grow the table and reload the relevant
// fields.
CallRuntime(Runtime::kMapGrow, context, receiver);
table_var.Bind(LoadObjectField(receiver, JSMap::kTableOffset));
number_of_buckets.Bind(SmiUntag(LoadFixedArrayElement(
table_var.value(), OrderedHashMap::kNumberOfBucketsIndex)));
Node* const new_number_of_elements = SmiUntag(CAST(LoadObjectField(
table_var.value(), OrderedHashMap::kNumberOfElementsOffset)));
Node* const new_number_of_deleted = SmiUntag(CAST(LoadObjectField(
table_var.value(), OrderedHashMap::kNumberOfDeletedElementsOffset)));
occupancy.Bind(IntPtrAdd(new_number_of_elements, new_number_of_deleted));
Goto(&store_new_entry);
}
BIND(&store_new_entry);
// Store the key, value and connect the element to the bucket chain.
StoreOrderedHashMapNewEntry(table_var.value(), key, value,
entry_start_position_or_hash.value(),
number_of_buckets.value(), occupancy.value());
Return(receiver);
}
void CollectionsBuiltinsAssembler::StoreOrderedHashMapNewEntry(
Node* const table, Node* const key, Node* const value, Node* const hash,
Node* const number_of_buckets, Node* const occupancy) {
Node* const bucket =
WordAnd(hash, IntPtrSub(number_of_buckets, IntPtrConstant(1)));
Node* const bucket_entry = LoadFixedArrayElement(
table, bucket, OrderedHashMap::kHashTableStartIndex * kPointerSize);
// Store the entry elements.
Node* const entry_start = IntPtrAdd(
IntPtrMul(occupancy, IntPtrConstant(OrderedHashMap::kEntrySize)),
number_of_buckets);
StoreFixedArrayElement(table, entry_start, key, UPDATE_WRITE_BARRIER,
kPointerSize * OrderedHashMap::kHashTableStartIndex);
StoreFixedArrayElement(table, entry_start, value, UPDATE_WRITE_BARRIER,
kPointerSize * (OrderedHashMap::kHashTableStartIndex +
OrderedHashMap::kValueOffset));
StoreFixedArrayElement(table, entry_start, bucket_entry, SKIP_WRITE_BARRIER,
kPointerSize * (OrderedHashMap::kHashTableStartIndex +
OrderedHashMap::kChainOffset));
// Update the bucket head.
StoreFixedArrayElement(table, bucket, SmiTag(occupancy), SKIP_WRITE_BARRIER,
OrderedHashMap::kHashTableStartIndex * kPointerSize);
// Bump the elements count.
Node* const number_of_elements =
LoadObjectField(table, OrderedHashMap::kNumberOfElementsOffset);
StoreObjectFieldNoWriteBarrier(table, OrderedHashMap::kNumberOfElementsOffset,
SmiAdd(number_of_elements, SmiConstant(1)));
}
TF_BUILTIN(MapDelete, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_MAP_TYPE,
"Map.prototype.delete");
Node* const table = LoadObjectField(receiver, JSMap::kTableOffset);
VARIABLE(entry_start_position_or_hash, MachineType::PointerRepresentation(),
IntPtrConstant(0));
Label entry_found(this), not_found(this);
TryLookupOrderedHashTableIndex<OrderedHashMap>(table, key, context,
&entry_start_position_or_hash,
&entry_found, ¬_found);
BIND(¬_found);
Return(FalseConstant());
BIND(&entry_found);
// If we found the entry, mark the entry as deleted.
StoreFixedArrayElement(table, entry_start_position_or_hash.value(),
TheHoleConstant(), UPDATE_WRITE_BARRIER,
kPointerSize * OrderedHashMap::kHashTableStartIndex);
StoreFixedArrayElement(table, entry_start_position_or_hash.value(),
TheHoleConstant(), UPDATE_WRITE_BARRIER,
kPointerSize * (OrderedHashMap::kHashTableStartIndex +
OrderedHashMap::kValueOffset));
// Decrement the number of elements, increment the number of deleted elements.
Node* const number_of_elements = SmiSub(
CAST(LoadObjectField(table, OrderedHashMap::kNumberOfElementsOffset)),
SmiConstant(1));
StoreObjectFieldNoWriteBarrier(table, OrderedHashMap::kNumberOfElementsOffset,
number_of_elements);
Node* const number_of_deleted =
SmiAdd(CAST(LoadObjectField(
table, OrderedHashMap::kNumberOfDeletedElementsOffset)),
SmiConstant(1));
StoreObjectFieldNoWriteBarrier(
table, OrderedHashMap::kNumberOfDeletedElementsOffset, number_of_deleted);
Node* const number_of_buckets =
LoadFixedArrayElement(table, OrderedHashMap::kNumberOfBucketsIndex);
// If there fewer elements than #buckets / 2, shrink the table.
Label shrink(this);
GotoIf(SmiLessThan(SmiAdd(number_of_elements, number_of_elements),
number_of_buckets),
&shrink);
Return(TrueConstant());
BIND(&shrink);
CallRuntime(Runtime::kMapShrink, context, receiver);
Return(TrueConstant());
}
TF_BUILTIN(SetAdd, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_SET_TYPE, "Set.prototype.add");
key = NormalizeNumberKey(key);
Node* const table = LoadObjectField(receiver, JSMap::kTableOffset);
VARIABLE(entry_start_position_or_hash, MachineType::PointerRepresentation(),
IntPtrConstant(0));
Label entry_found(this), not_found(this);
TryLookupOrderedHashTableIndex<OrderedHashSet>(table, key, context,
&entry_start_position_or_hash,
&entry_found, ¬_found);
BIND(&entry_found);
// The entry was found, there is nothing to do.
Return(receiver);
Label no_hash(this), add_entry(this), store_new_entry(this);
BIND(¬_found);
{
// If we have a hash code, we can start adding the new entry.
GotoIf(IntPtrGreaterThanOrEqual(entry_start_position_or_hash.value(),
IntPtrConstant(0)),
&add_entry);
// Otherwise, go to runtime to compute the hash code.
entry_start_position_or_hash.Bind(SmiUntag((CallGetOrCreateHashRaw(key))));
Goto(&add_entry);
}
BIND(&add_entry);
VARIABLE(number_of_buckets, MachineType::PointerRepresentation());
VARIABLE(occupancy, MachineType::PointerRepresentation());
VARIABLE(table_var, MachineRepresentation::kTaggedPointer, table);
{
// Check we have enough space for the entry.
number_of_buckets.Bind(SmiUntag(
LoadFixedArrayElement(table, OrderedHashSet::kNumberOfBucketsIndex)));
STATIC_ASSERT(OrderedHashSet::kLoadFactor == 2);
Node* const capacity = WordShl(number_of_buckets.value(), 1);
Node* const number_of_elements = SmiUntag(
CAST(LoadObjectField(table, OrderedHashSet::kNumberOfElementsOffset)));
Node* const number_of_deleted = SmiUntag(CAST(LoadObjectField(
table, OrderedHashSet::kNumberOfDeletedElementsOffset)));
occupancy.Bind(IntPtrAdd(number_of_elements, number_of_deleted));
GotoIf(IntPtrLessThan(occupancy.value(), capacity), &store_new_entry);
// We do not have enough space, grow the table and reload the relevant
// fields.
CallRuntime(Runtime::kSetGrow, context, receiver);
table_var.Bind(LoadObjectField(receiver, JSMap::kTableOffset));
number_of_buckets.Bind(SmiUntag(LoadFixedArrayElement(
table_var.value(), OrderedHashSet::kNumberOfBucketsIndex)));
Node* const new_number_of_elements = SmiUntag(CAST(LoadObjectField(
table_var.value(), OrderedHashSet::kNumberOfElementsOffset)));
Node* const new_number_of_deleted = SmiUntag(CAST(LoadObjectField(
table_var.value(), OrderedHashSet::kNumberOfDeletedElementsOffset)));
occupancy.Bind(IntPtrAdd(new_number_of_elements, new_number_of_deleted));
Goto(&store_new_entry);
}
BIND(&store_new_entry);
// Store the key, value and connect the element to the bucket chain.
StoreOrderedHashSetNewEntry(table_var.value(), key,
entry_start_position_or_hash.value(),
number_of_buckets.value(), occupancy.value());
Return(receiver);
}
void CollectionsBuiltinsAssembler::StoreOrderedHashSetNewEntry(
Node* const table, Node* const key, Node* const hash,
Node* const number_of_buckets, Node* const occupancy) {
Node* const bucket =
WordAnd(hash, IntPtrSub(number_of_buckets, IntPtrConstant(1)));
Node* const bucket_entry = LoadFixedArrayElement(
table, bucket, OrderedHashSet::kHashTableStartIndex * kPointerSize);
// Store the entry elements.
Node* const entry_start = IntPtrAdd(
IntPtrMul(occupancy, IntPtrConstant(OrderedHashSet::kEntrySize)),
number_of_buckets);
StoreFixedArrayElement(table, entry_start, key, UPDATE_WRITE_BARRIER,
kPointerSize * OrderedHashSet::kHashTableStartIndex);
StoreFixedArrayElement(table, entry_start, bucket_entry, SKIP_WRITE_BARRIER,
kPointerSize * (OrderedHashSet::kHashTableStartIndex +
OrderedHashSet::kChainOffset));
// Update the bucket head.
StoreFixedArrayElement(table, bucket, SmiTag(occupancy), SKIP_WRITE_BARRIER,
OrderedHashSet::kHashTableStartIndex * kPointerSize);
// Bump the elements count.
Node* const number_of_elements =
LoadObjectField(table, OrderedHashSet::kNumberOfElementsOffset);
StoreObjectFieldNoWriteBarrier(table, OrderedHashSet::kNumberOfElementsOffset,
SmiAdd(number_of_elements, SmiConstant(1)));
}
TF_BUILTIN(SetDelete, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_SET_TYPE,
"Set.prototype.delete");
Node* const table = LoadObjectField(receiver, JSMap::kTableOffset);
VARIABLE(entry_start_position_or_hash, MachineType::PointerRepresentation(),
IntPtrConstant(0));
Label entry_found(this), not_found(this);
TryLookupOrderedHashTableIndex<OrderedHashSet>(table, key, context,
&entry_start_position_or_hash,
&entry_found, ¬_found);
BIND(¬_found);
Return(FalseConstant());
BIND(&entry_found);
// If we found the entry, mark the entry as deleted.
StoreFixedArrayElement(table, entry_start_position_or_hash.value(),
TheHoleConstant(), UPDATE_WRITE_BARRIER,
kPointerSize * OrderedHashSet::kHashTableStartIndex);
// Decrement the number of elements, increment the number of deleted elements.
Node* const number_of_elements = SmiSub(
CAST(LoadObjectField(table, OrderedHashSet::kNumberOfElementsOffset)),
SmiConstant(1));
StoreObjectFieldNoWriteBarrier(table, OrderedHashSet::kNumberOfElementsOffset,
number_of_elements);
Node* const number_of_deleted =
SmiAdd(CAST(LoadObjectField(
table, OrderedHashSet::kNumberOfDeletedElementsOffset)),
SmiConstant(1));
StoreObjectFieldNoWriteBarrier(
table, OrderedHashSet::kNumberOfDeletedElementsOffset, number_of_deleted);
Node* const number_of_buckets =
LoadFixedArrayElement(table, OrderedHashSet::kNumberOfBucketsIndex);
// If there fewer elements than #buckets / 2, shrink the table.
Label shrink(this);
GotoIf(SmiLessThan(SmiAdd(number_of_elements, number_of_elements),
number_of_buckets),
&shrink);
Return(TrueConstant());
BIND(&shrink);
CallRuntime(Runtime::kSetShrink, context, receiver);
Return(TrueConstant());
}
TF_BUILTIN(MapPrototypeEntries, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_MAP_TYPE,
"Map.prototype.entries");
Return(AllocateJSCollectionIterator<JSMapIterator>(
context, Context::MAP_KEY_VALUE_ITERATOR_MAP_INDEX, receiver));
}
TF_BUILTIN(MapPrototypeGetSize, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_MAP_TYPE,
"get Map.prototype.size");
Node* const table = LoadObjectField(receiver, JSMap::kTableOffset);
Return(LoadObjectField(table, OrderedHashMap::kNumberOfElementsOffset));
}
TF_BUILTIN(MapPrototypeForEach, CollectionsBuiltinsAssembler) {
const char* const kMethodName = "Map.prototype.forEach";
Node* const argc = Parameter(BuiltinDescriptor::kArgumentsCount);
Node* const context = Parameter(BuiltinDescriptor::kContext);
CodeStubArguments args(this, ChangeInt32ToIntPtr(argc));
Node* const receiver = args.GetReceiver();
Node* const callback = args.GetOptionalArgumentValue(0);
Node* const this_arg = args.GetOptionalArgumentValue(1);
ThrowIfNotInstanceType(context, receiver, JS_MAP_TYPE, kMethodName);
// Ensure that {callback} is actually callable.
Label callback_not_callable(this, Label::kDeferred);
GotoIf(TaggedIsSmi(callback), &callback_not_callable);
GotoIfNot(IsCallable(callback), &callback_not_callable);
VARIABLE(var_index, MachineType::PointerRepresentation(), IntPtrConstant(0));
VARIABLE(var_table, MachineRepresentation::kTagged,
LoadObjectField(receiver, JSMap::kTableOffset));
Label loop(this, {&var_index, &var_table}), done_loop(this);
Goto(&loop);
BIND(&loop);
{
// Transition {table} and {index} if there was any modification to
// the {receiver} while we're iterating.
Node* index = var_index.value();
Node* table = var_table.value();
std::tie(table, index) =
Transition<OrderedHashMap>(table, index, [](Node*, Node*) {});
// Read the next entry from the {table}, skipping holes.
Node* entry_key;
Node* entry_start_position;
std::tie(entry_key, entry_start_position, index) =
NextSkipHoles<OrderedHashMap>(table, index, &done_loop);
// Load the entry value as well.
Node* entry_value = LoadFixedArrayElement(
table, entry_start_position,
(OrderedHashMap::kHashTableStartIndex + OrderedHashMap::kValueOffset) *
kPointerSize);
// Invoke the {callback} passing the {entry_key}, {entry_value} and the
// {receiver}.
CallJS(CodeFactory::Call(isolate()), context, callback, this_arg,
entry_value, entry_key, receiver);
// Continue with the next entry.
var_index.Bind(index);
var_table.Bind(table);
Goto(&loop);
}
BIND(&done_loop);
args.PopAndReturn(UndefinedConstant());
BIND(&callback_not_callable);
{
CallRuntime(Runtime::kThrowCalledNonCallable, context, callback);
Unreachable();
}
}
TF_BUILTIN(MapPrototypeKeys, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_MAP_TYPE, "Map.prototype.keys");
Return(AllocateJSCollectionIterator<JSMapIterator>(
context, Context::MAP_KEY_ITERATOR_MAP_INDEX, receiver));
}
TF_BUILTIN(MapPrototypeValues, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_MAP_TYPE,
"Map.prototype.values");
Return(AllocateJSCollectionIterator<JSMapIterator>(
context, Context::MAP_VALUE_ITERATOR_MAP_INDEX, receiver));
}
TF_BUILTIN(MapIteratorPrototypeNext, CollectionsBuiltinsAssembler) {
const char* const kMethodName = "Map Iterator.prototype.next";
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const context = Parameter(Descriptor::kContext);
// Ensure that the {receiver} is actually a JSMapIterator.
Label if_receiver_valid(this), if_receiver_invalid(this, Label::kDeferred);
GotoIf(TaggedIsSmi(receiver), &if_receiver_invalid);
Node* const receiver_instance_type = LoadInstanceType(receiver);
GotoIf(
InstanceTypeEqual(receiver_instance_type, JS_MAP_KEY_VALUE_ITERATOR_TYPE),
&if_receiver_valid);
GotoIf(InstanceTypeEqual(receiver_instance_type, JS_MAP_KEY_ITERATOR_TYPE),
&if_receiver_valid);
Branch(InstanceTypeEqual(receiver_instance_type, JS_MAP_VALUE_ITERATOR_TYPE),
&if_receiver_valid, &if_receiver_invalid);
BIND(&if_receiver_invalid);
ThrowIncompatibleMethodReceiver(context, kMethodName, receiver);
BIND(&if_receiver_valid);
// Check if the {receiver} is exhausted.
VARIABLE(var_done, MachineRepresentation::kTagged, TrueConstant());
VARIABLE(var_value, MachineRepresentation::kTagged, UndefinedConstant());
Label return_value(this, {&var_done, &var_value}), return_entry(this),
return_end(this, Label::kDeferred);
// Transition the {receiver} table if necessary.
Node* table;
Node* index;
std::tie(table, index) =
TransitionAndUpdate<JSMapIterator, OrderedHashMap>(receiver);
// Read the next entry from the {table}, skipping holes.
Node* entry_key;
Node* entry_start_position;
std::tie(entry_key, entry_start_position, index) =
NextSkipHoles<OrderedHashMap>(table, index, &return_end);
StoreObjectFieldNoWriteBarrier(receiver, JSMapIterator::kIndexOffset,
SmiTag(index));
var_value.Bind(entry_key);
var_done.Bind(FalseConstant());
// Check how to return the {key} (depending on {receiver} type).
GotoIf(InstanceTypeEqual(receiver_instance_type, JS_MAP_KEY_ITERATOR_TYPE),
&return_value);
var_value.Bind(LoadFixedArrayElement(
table, entry_start_position,
(OrderedHashMap::kHashTableStartIndex + OrderedHashMap::kValueOffset) *
kPointerSize));
Branch(InstanceTypeEqual(receiver_instance_type, JS_MAP_VALUE_ITERATOR_TYPE),
&return_value, &return_entry);
BIND(&return_entry);
{
Node* result =
AllocateJSIteratorResultForEntry(context, entry_key, var_value.value());
Return(result);
}
BIND(&return_value);
{
Node* result =
AllocateJSIteratorResult(context, var_value.value(), var_done.value());
Return(result);
}
BIND(&return_end);
{
StoreObjectFieldRoot(receiver, JSMapIterator::kTableOffset,
Heap::kEmptyOrderedHashTableRootIndex);
Goto(&return_value);
}
}
TF_BUILTIN(SetHas, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_SET_TYPE, "Set.prototype.has");
Node* const table = LoadObjectField(receiver, JSMap::kTableOffset);
VARIABLE(entry_start_position, MachineType::PointerRepresentation(),
IntPtrConstant(0));
VARIABLE(result, MachineRepresentation::kTaggedSigned, IntPtrConstant(0));
Label if_key_smi(this), if_key_string(this), if_key_heap_number(this),
if_key_bigint(this), entry_found(this), not_found(this), done(this);
GotoIf(TaggedIsSmi(key), &if_key_smi);
Node* key_map = LoadMap(key);
Node* key_instance_type = LoadMapInstanceType(key_map);
GotoIf(IsStringInstanceType(key_instance_type), &if_key_string);
GotoIf(IsHeapNumberMap(key_map), &if_key_heap_number);
GotoIf(IsBigIntInstanceType(key_instance_type), &if_key_bigint);
FindOrderedHashTableEntryForOtherKey<OrderedHashSet>(
context, table, key, &entry_start_position, &entry_found, ¬_found);
BIND(&if_key_smi);
{
FindOrderedHashTableEntryForSmiKey<OrderedHashSet>(
table, key, &entry_start_position, &entry_found, ¬_found);
}
BIND(&if_key_string);
{
FindOrderedHashTableEntryForStringKey<OrderedHashSet>(
context, table, key, &entry_start_position, &entry_found, ¬_found);
}
BIND(&if_key_heap_number);
{
FindOrderedHashTableEntryForHeapNumberKey<OrderedHashSet>(
context, table, key, &entry_start_position, &entry_found, ¬_found);
}
BIND(&if_key_bigint);
{
FindOrderedHashTableEntryForBigIntKey<OrderedHashSet>(
context, table, key, &entry_start_position, &entry_found, ¬_found);
}
BIND(&entry_found);
Return(TrueConstant());
BIND(¬_found);
Return(FalseConstant());
}
TF_BUILTIN(SetPrototypeEntries, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_SET_TYPE,
"Set.prototype.entries");
Return(AllocateJSCollectionIterator<JSSetIterator>(
context, Context::SET_KEY_VALUE_ITERATOR_MAP_INDEX, receiver));
}
TF_BUILTIN(SetPrototypeGetSize, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_SET_TYPE,
"get Set.prototype.size");
Node* const table = LoadObjectField(receiver, JSSet::kTableOffset);
Return(LoadObjectField(table, OrderedHashSet::kNumberOfElementsOffset));
}
TF_BUILTIN(SetPrototypeForEach, CollectionsBuiltinsAssembler) {
const char* const kMethodName = "Set.prototype.forEach";
Node* const argc = Parameter(BuiltinDescriptor::kArgumentsCount);
Node* const context = Parameter(BuiltinDescriptor::kContext);
CodeStubArguments args(this, ChangeInt32ToIntPtr(argc));
Node* const receiver = args.GetReceiver();
Node* const callback = args.GetOptionalArgumentValue(0);
Node* const this_arg = args.GetOptionalArgumentValue(1);
ThrowIfNotInstanceType(context, receiver, JS_SET_TYPE, kMethodName);
// Ensure that {callback} is actually callable.
Label callback_not_callable(this, Label::kDeferred);
GotoIf(TaggedIsSmi(callback), &callback_not_callable);
GotoIfNot(IsCallable(callback), &callback_not_callable);
VARIABLE(var_index, MachineType::PointerRepresentation(), IntPtrConstant(0));
VARIABLE(var_table, MachineRepresentation::kTagged,
LoadObjectField(receiver, JSSet::kTableOffset));
Label loop(this, {&var_index, &var_table}), done_loop(this);
Goto(&loop);
BIND(&loop);
{
// Transition {table} and {index} if there was any modification to
// the {receiver} while we're iterating.
Node* index = var_index.value();
Node* table = var_table.value();
std::tie(table, index) =
Transition<OrderedHashSet>(table, index, [](Node*, Node*) {});
// Read the next entry from the {table}, skipping holes.
Node* entry_key;
Node* entry_start_position;
std::tie(entry_key, entry_start_position, index) =
NextSkipHoles<OrderedHashSet>(table, index, &done_loop);
// Invoke the {callback} passing the {entry_key} (twice) and the {receiver}.
CallJS(CodeFactory::Call(isolate()), context, callback, this_arg, entry_key,
entry_key, receiver);
// Continue with the next entry.
var_index.Bind(index);
var_table.Bind(table);
Goto(&loop);
}
BIND(&done_loop);
args.PopAndReturn(UndefinedConstant());
BIND(&callback_not_callable);
{
CallRuntime(Runtime::kThrowCalledNonCallable, context, callback);
Unreachable();
}
}
TF_BUILTIN(SetPrototypeValues, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const context = Parameter(Descriptor::kContext);
ThrowIfNotInstanceType(context, receiver, JS_SET_TYPE,
"Set.prototype.values");
Return(AllocateJSCollectionIterator<JSSetIterator>(
context, Context::SET_VALUE_ITERATOR_MAP_INDEX, receiver));
}
TF_BUILTIN(SetIteratorPrototypeNext, CollectionsBuiltinsAssembler) {
const char* const kMethodName = "Set Iterator.prototype.next";
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const context = Parameter(Descriptor::kContext);
// Ensure that the {receiver} is actually a JSSetIterator.
Label if_receiver_valid(this), if_receiver_invalid(this, Label::kDeferred);
GotoIf(TaggedIsSmi(receiver), &if_receiver_invalid);
Node* const receiver_instance_type = LoadInstanceType(receiver);
GotoIf(InstanceTypeEqual(receiver_instance_type, JS_SET_VALUE_ITERATOR_TYPE),
&if_receiver_valid);
Branch(
InstanceTypeEqual(receiver_instance_type, JS_SET_KEY_VALUE_ITERATOR_TYPE),
&if_receiver_valid, &if_receiver_invalid);
BIND(&if_receiver_invalid);
ThrowIncompatibleMethodReceiver(context, kMethodName, receiver);
BIND(&if_receiver_valid);
// Check if the {receiver} is exhausted.
VARIABLE(var_done, MachineRepresentation::kTagged, TrueConstant());
VARIABLE(var_value, MachineRepresentation::kTagged, UndefinedConstant());
Label return_value(this, {&var_done, &var_value}), return_entry(this),
return_end(this, Label::kDeferred);
// Transition the {receiver} table if necessary.
Node* table;
Node* index;
std::tie(table, index) =
TransitionAndUpdate<JSSetIterator, OrderedHashSet>(receiver);
// Read the next entry from the {table}, skipping holes.
Node* entry_key;
Node* entry_start_position;
std::tie(entry_key, entry_start_position, index) =
NextSkipHoles<OrderedHashSet>(table, index, &return_end);
StoreObjectFieldNoWriteBarrier(receiver, JSSetIterator::kIndexOffset,
SmiTag(index));
var_value.Bind(entry_key);
var_done.Bind(FalseConstant());
// Check how to return the {key} (depending on {receiver} type).
Branch(InstanceTypeEqual(receiver_instance_type, JS_SET_VALUE_ITERATOR_TYPE),
&return_value, &return_entry);
BIND(&return_entry);
{
Node* result = AllocateJSIteratorResultForEntry(context, var_value.value(),
var_value.value());
Return(result);
}
BIND(&return_value);
{
Node* result =
AllocateJSIteratorResult(context, var_value.value(), var_done.value());
Return(result);
}
BIND(&return_end);
{
StoreObjectFieldRoot(receiver, JSSetIterator::kTableOffset,
Heap::kEmptyOrderedHashTableRootIndex);
Goto(&return_value);
}
}
template <typename CollectionType>
void CollectionsBuiltinsAssembler::TryLookupOrderedHashTableIndex(
Node* const table, Node* const key, Node* const context, Variable* result,
Label* if_entry_found, Label* if_not_found) {
Label if_key_smi(this), if_key_string(this), if_key_heap_number(this),
if_key_bigint(this);
GotoIf(TaggedIsSmi(key), &if_key_smi);
Node* key_map = LoadMap(key);
Node* key_instance_type = LoadMapInstanceType(key_map);
GotoIf(IsStringInstanceType(key_instance_type), &if_key_string);
GotoIf(IsHeapNumberMap(key_map), &if_key_heap_number);
GotoIf(IsBigIntInstanceType(key_instance_type), &if_key_bigint);
FindOrderedHashTableEntryForOtherKey<CollectionType>(
context, table, key, result, if_entry_found, if_not_found);
BIND(&if_key_smi);
{
FindOrderedHashTableEntryForSmiKey<CollectionType>(
table, key, result, if_entry_found, if_not_found);
}
BIND(&if_key_string);
{
FindOrderedHashTableEntryForStringKey<CollectionType>(
context, table, key, result, if_entry_found, if_not_found);
}
BIND(&if_key_heap_number);
{
FindOrderedHashTableEntryForHeapNumberKey<CollectionType>(
context, table, key, result, if_entry_found, if_not_found);
}
BIND(&if_key_bigint);
{
FindOrderedHashTableEntryForBigIntKey<CollectionType>(
context, table, key, result, if_entry_found, if_not_found);
}
}
TF_BUILTIN(MapLookupHashIndex, CollectionsBuiltinsAssembler) {
Node* const table = Parameter(Descriptor::kTable);
Node* const key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
VARIABLE(entry_start_position, MachineType::PointerRepresentation(),
IntPtrConstant(0));
Label entry_found(this), not_found(this);
TryLookupOrderedHashTableIndex<OrderedHashMap>(
table, key, context, &entry_start_position, &entry_found, ¬_found);
BIND(&entry_found);
Node* index = IntPtrAdd(entry_start_position.value(),
IntPtrConstant(OrderedHashMap::kHashTableStartIndex +
OrderedHashMap::kValueOffset));
Return(SmiTag(index));
BIND(¬_found);
Return(SmiConstant(-1));
}
TF_BUILTIN(WeakMapLookupHashIndex, CollectionsBuiltinsAssembler) {
Node* const table = Parameter(Descriptor::kTable);
Node* const key = Parameter(Descriptor::kKey);
Label if_found(this), if_not_found(this);
Node* const capacity =
SmiUntag(LoadFixedArrayElement(table, WeakHashTable::kCapacityIndex));
Node* const mask = IntPtrSub(capacity, IntPtrConstant(1));
Node* const hash = GetHash(key);
GotoIf(IntPtrLessThan(hash, IntPtrConstant(0)), &if_not_found);
// See HashTable::FirstProbe().
Node* entry = WordAnd(hash, mask);
VARIABLE(var_count, MachineType::PointerRepresentation(), IntPtrConstant(0));
VARIABLE(var_entry, MachineType::PointerRepresentation(), entry);
Variable* loop_vars[] = {&var_count, &var_entry};
Label loop(this, arraysize(loop_vars), loop_vars);
Goto(&loop);
BIND(&loop);
Node* index;
{
Node* entry = var_entry.value();
index = IntPtrMul(entry, IntPtrConstant(WeakHashTable::kEntrySize));
index =
IntPtrAdd(index, IntPtrConstant(WeakHashTable::kElementsStartIndex));
Node* current = LoadFixedArrayElement(table, index);
GotoIf(WordEqual(current, UndefinedConstant()), &if_not_found);
GotoIf(WordEqual(current, key), &if_found);
// See HashTable::NextProbe().
Increment(&var_count);
entry = WordAnd(IntPtrAdd(entry, var_count.value()), mask);
var_entry.Bind(entry);
Goto(&loop);
}
BIND(&if_not_found);
Return(SmiConstant(-1));
BIND(&if_found);
Return(SmiTag(Signed(IntPtrAdd(index, IntPtrConstant(1)))));
}
TF_BUILTIN(WeakMapGet, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
Label return_undefined(this);
ThrowIfNotInstanceType(context, receiver, JS_WEAK_MAP_TYPE,
"WeakMap.prototype.get");
GotoIf(TaggedIsSmi(key), &return_undefined);
GotoIfNot(IsJSReceiver(key), &return_undefined);
Node* const table = LoadObjectField(receiver, JSWeakCollection::kTableOffset);
Node* const index =
CallBuiltin(Builtins::kWeakMapLookupHashIndex, context, table, key);
GotoIf(WordEqual(index, SmiConstant(-1)), &return_undefined);
Return(LoadFixedArrayElement(table, SmiUntag(index)));
BIND(&return_undefined);
Return(UndefinedConstant());
}
TF_BUILTIN(WeakMapHas, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
Label return_false(this);
ThrowIfNotInstanceType(context, receiver, JS_WEAK_MAP_TYPE,
"WeakMap.prototype.get");
GotoIf(TaggedIsSmi(key), &return_false);
GotoIfNot(IsJSReceiver(key), &return_false);
Node* const table = LoadObjectField(receiver, JSWeakCollection::kTableOffset);
Node* const index =
CallBuiltin(Builtins::kWeakMapLookupHashIndex, context, table, key);
GotoIf(WordEqual(index, SmiConstant(-1)), &return_false);
Return(TrueConstant());
BIND(&return_false);
Return(FalseConstant());
}
TF_BUILTIN(WeakSetHas, CollectionsBuiltinsAssembler) {
Node* const receiver = Parameter(Descriptor::kReceiver);
Node* const key = Parameter(Descriptor::kKey);
Node* const context = Parameter(Descriptor::kContext);
Label return_false(this);
ThrowIfNotInstanceType(context, receiver, JS_WEAK_SET_TYPE,
"WeakSet.prototype.get");
GotoIf(TaggedIsSmi(key), &return_false);
GotoIfNot(IsJSReceiver(key), &return_false);
Node* const table = LoadObjectField(receiver, JSWeakCollection::kTableOffset);
Node* const index =
CallBuiltin(Builtins::kWeakMapLookupHashIndex, context, table, key);
GotoIf(WordEqual(index, SmiConstant(-1)), &return_false);
Return(TrueConstant());
BIND(&return_false);
Return(FalseConstant());
}
} // namespace internal
} // namespace v8
| [
"zhuanghengfei@gmail.com"
] | zhuanghengfei@gmail.com |
020cb123aec4fe9bfc85b9417875f190b85df0e6 | c2239a4e2f88d072021113fe355c02eedefe9110 | /private/ToolZ/PositionService.cxx | 4afe8e6d912776abc11c28db9efa68a5d2856974 | [] | no_license | mzoll/ToolZ | d581258655c61a5958ed25004ee1d4b15cabd28c | 6f8dcaf439db172ad8c5248f71d644ffbe9566c7 | refs/heads/master | 2020-03-29T16:18:13.566897 | 2018-09-24T13:41:50 | 2018-09-24T13:41:50 | 150,108,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,056 | cxx | /**
* \file PositionService.cxx
*
* copyright (c) 2011
* the IceCube Collaboration
* $Id: IceHiveHelpers.cxx 144968 2016-04-20 22:52:24Z mzoll $
* @date $Date: 2013-10-22$
* @author mzoll <marcel.zoll@fysik.su.se>
*/
#include "ToolZ/PositionService.h"
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
#include <algorithm>
#include <vector>
//=================== CLASS PositionService ===========
PositionService::PositionService(
const I3OMGeoMap& omgeo,
CompactOMKeyHashServiceConstPtr& hasher)
: hasher_(hasher ? hasher : boost::make_shared<const CompactOMKeyHashService>(ExtractOMKeys(omgeo))),
hashedPosition_(ConstructHashedPositions(omgeo))
{
if (!hasher)
hasher = hasher_;
};
PositionService::PositionService(
const I3OMGeoMap& omgeo,
const CompactOMKeyHashServiceConstPtr& hasher)
: hasher_(hasher),
hashedPosition_(ConstructHashedPositions(omgeo))
{};
#if SERIALIZATION_ENABLED
PositionService::PositionService(
const CompactOMKeyHashServiceConstPtr& hasher,
const std::vector<I3Position>& hashedPosition)
: hasher_(hasher),
hashedPosition_(hashedPosition)
{};
#endif //SERIALIZATION_ENABLED
std::vector<I3Position> PositionService::ConstructHashedPositions (
const I3OMGeoMap& omgeo) const
{
std::vector<I3Position> hashedPosition;
BOOST_FOREACH(const OMKey& omkey, hasher_->GetOMKeys()) {
hashedPosition.push_back(omgeo.at(omkey).position);
}
return hashedPosition;
};
bool PositionService::VerifyAgainst(
const I3OMGeoMap& omgeo) const
{
for (uint64_t i=0; i<hashedPosition_.size(); i++) {
const OMKey omkey = hasher_->OMKeyFromHash(i);
const I3OMGeoMap::const_iterator geo_entry = omgeo.find(omkey);
if (geo_entry == omgeo.end()) {
log_error("Do not verify against each other");
return false;
}
if (hashedPosition_.at(i) != omgeo.at(omkey).position) {
log_error("Do not verify against each other");
return false;
}
}
return true;
}
#if SERIALIZATION_ENABLED
I3_SERIALIZABLE(PositionService);
#endif
| [
"marcel.zoll.physics@gmail.com"
] | marcel.zoll.physics@gmail.com |
0dbe5447ac2492031d8bb18cc2ad6ebd48bac8cc | fbd1bd8238aa7af82fa68f0fbc3e5e2b4bebb9c0 | /clock.cpp | f97da1a9984a5ce8c0873e6e6be5261469edf103 | [
"MIT"
] | permissive | Oscar-Rod/Thermostat | 785a42b4c7f76329dc78860aa3f75f0f473812ba | 83dfb4f89b03f37a64da784a1df80973174f4425 | refs/heads/main | 2023-03-01T22:57:57.184350 | 2021-02-03T18:24:55 | 2021-02-03T18:24:55 | 332,833,599 | 0 | 0 | MIT | 2021-02-03T18:24:55 | 2021-01-25T17:50:45 | C++ | UTF-8 | C++ | false | false | 828 | cpp | #include "clock.h"
Clock::Clock() {
}
void Clock::init() {
Wire.begin();
clockModule.setClockMode(false);
}
void Clock::setTime(int hour, int minute, int second) {
clockModule.setHour(hour);
clockModule.setMinute(minute);
clockModule.setSecond(second);
}
int Clock::getTime(int *hour, int *minute, int *second) {
currentMilis = millis();
if (currentMilis - previousMilis >= 1000){
previousMilis = currentMilis;
*hour = clockModule.getHour(h12Flag, pmFlag);
*minute = clockModule.getMinute();
*second = clockModule.getSecond();
}
}
bool Clock::isWeekend() {
int dayOfWeek = getDayOfWeek();
if (dayOfWeek > 5) return true;
else return false;
}
void Clock::setDayOfWeek(byte DayOfWeek) {
clockModule.setDoW(DayOfWeek);
}
byte Clock::getDayOfWeek() {
return clockModule.getDoW();
}
| [
"rguez.r.os@gmail.com"
] | rguez.r.os@gmail.com |
96cc75bb4e878114dc87de4300e61070f537ce61 | 3ded37602d6d303e61bff401b2682f5c2b52928c | /ml/013/Classes/View/MachineView.h | 808f5ec4562c4acea8e15bca3b723637f0ce20bd | [] | no_license | CristinaBaby/Demo_CC | 8ce532dcf016f21b442d8b05173a7d20c03d337e | 6f6a7ff132e93271b8952b8da6884c3634f5cb59 | refs/heads/master | 2021-05-02T14:58:52.900119 | 2018-02-09T11:48:02 | 2018-02-09T11:48:02 | 120,727,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,145 | h | //
// MachineView.h
// Make
//
// Created by liji on 15/5/28.
//
//
#ifndef __Make__MachineView__
#define __Make__MachineView__
#include <stdio.h>
#include "cocos2d.h"
USING_NS_CC;
class MachineViewDelegate
{
public:
virtual void allStepFinished(){};
};
class MachineView : public Layer
{
public:
CREATE_FUNC(MachineView);
bool init();
void setDelegate(MachineViewDelegate* delegate){delegate_ = delegate;};
private:
void initMachine();
void showIceBag();
void iceBagClicked();
void machineCoverClosed();
void showMachineBtn();
void runMachine();
void iceEffect(float dt);
void snowconeFall(float dt);
void showIcePile();
void stepFinish();
private:
Sprite* lid_;
Sprite* boxBottom_;
Sprite* boxCover_;
Sprite* hint_;
Sprite* iceBag_;
Sprite* pile_;
Sprite* btn_;
MachineViewDelegate* delegate_;
Vector<Sprite*> vec_ice;
int iceCount_ = 0;
EventListenerTouchOneByOne* listener_;
float _rectPosY = 0.f;
const float _totalTime = 3.f;
float _speed = 0.f;
};
#endif /* defined(__Make__MachineView__) */
| [
"wuguiling@smalltreemedia.com"
] | wuguiling@smalltreemedia.com |
175bbb66a0cda3a1f10859f6af0b90874134652f | cd9c4670683df414f814928ec69778c13095f862 | /SpotVMFrame/SpotVMFrame/mutation.cpp | 801c32f0e0995fd1a6a0c34f4cfa20178faca145 | [] | no_license | amelieczhou/hybrid-dynamic-workflow-scheduling | a1d82d0ec110cf099c0eab37984622fb2c5dbf2b | c13d8d1aaaee95a9262a530d91746309b081c25c | refs/heads/master | 2020-12-25T18:20:30.888574 | 2015-01-13T03:37:29 | 2015-01-13T03:37:29 | 32,119,838 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,278 | cpp | #include "stdafx.h"
#include "mutation.h"
extern std::vector<individual* > generation; //initial size = populationsize
extern std::vector<individual* > variation; //initially empty
extern std::vector<individual* > matingpool;
int mu = 10;
int solutionsize = 10;//20;//for epi
float variable_swap_probability = 0.9;//crossover
float variable_mutation_probability = 0.5; //mutation
int update_from_arc(std::vector<individual*>& population)
// Removes the individuals, that are not in the archive
{
int size, result;
//int *keep;
int i, current;
size = population.size();
std::vector<int > keep(size);
result = 0;
// keep = (int *) malloc(sizeof(int)*size);
/*if (keep == NULL)
{
std::cout<<"SPEA variator: out of memory"<<std::endl;
exit(1);
}*/
for(i=0; i < size; i++)
keep[i] = population[i]->index;
// sort the array of indexes to keep,
// so we can go through the array and delete all indexes,
// that are in between
//qsort(keep, (size_t) size, sizeof(int), cmp_int);
// delete all indexes in global_population not found in keep array
for(int i=0; i<generation.size(); i++){
if(std::find(keep.begin(),keep.end(),generation[i]->index) == keep.end()){//no need to keep this one
generation.erase(generation.begin()+i);
i--;
}
}
/* int count = 0;
current = generation[count]->index;
for(i = 0; i < size; i++)
{
while(current < keep[i])
{
generation[count] = NULL;
generation.erase(generation.begin()+count);
//count--;
current = generation[count]->index;
}
if (current == keep[i])
{
count++;
if(count<generation.size())
current = generation[count]->index;
} // this one we keep
else // current must be bigger than keep[i],
// something went wrong...
{
std::cout<<"identity in archive is not in the global population!"<<std::endl;
exit(1);
}
}*/
// delete the last individuals at end of list
while(generation.size() > population.size())
generation.erase(generation.end()-1);
//free(keep);
return (0);
}
int variate(std::vector<individual*>& selected)
// Performs the real variation of individuals
// *selected points to the selected individuals
// *result_ids will contain the offspring individuals
{
int result, i, k;
result = 1;
// copying all individuals from selected to global population
//for(int j=0; j<selected.size(); j++)
// generation.push_back(selected[j]);
// if odd number of individuals, last one is left as is
if((((double)mu/2) - (int)(mu/2)) != 0) k = mu - 1;
else k = mu;
// do recombination
for(i = 0; i < k; i+= 2) {
if (rn_01() <= variable_swap_probability) {
single_point_crossover(selected[i],selected[i+1]);
}
}
// do mutation
for(i = 0; i < mu; i++) {
if (rn_01() <= variable_mutation_probability) {
mutation(selected[i]);
}
}
return (0);
}
void single_point_crossover(individual *ind1, individual *ind2)
{
//select two points in the vector and swap
int start, end, tmp;
start = rn_integers(0,solutionsize);
while(start == solutionsize)
start = rn_integers(0,solutionsize);
end = rn_integers(0,solutionsize);
while(end == solutionsize)
end = rn_integers(0,solutionsize);
if(start > end){
tmp = start;
start = end;
end = tmp;
}
for(int i=start; i<=end; i++){
tmp = ind1->solution[i];
ind1->solution[i] = ind2->solution[i];
ind2->solution[i] = tmp;
}
return;
}
void mutation(individual* ind){
if (ind == NULL) {
exit(1);
}
for (int i = 0; i < solutionsize; i++) {
//replacing mutation
if(rn_01() <= variable_mutation_probability){
int mut = rn_integers(0,types);
while(mut == types) mut = rn_integers(0,types);
ind->solution[i] = mut;
}
//reordering mutation
}
return ;
} | [
"andyzhang870914@gmail.com@0f0f248c-0e70-7bf0-40e6-9a9aec565ee8"
] | andyzhang870914@gmail.com@0f0f248c-0e70-7bf0-40e6-9a9aec565ee8 |
8aadadc1a7827974a901c88b78b24d2d550986e9 | dc2e0d49f99951bc40e323fb92ea4ddd5d9644a0 | /SDK/ThirdLibrary/include/activemq-cpp/decaf/internal/DecafRuntime.cpp | 86d2a830d11975c1655b6fdb93f74f6e8a769d6a | [] | no_license | wenyu826/CecilySolution | 8696290d1723fdfe6e41ce63e07c7c25a9295ded | 14c4ba9adbb937d0ae236040b2752e2c7337b048 | refs/heads/master | 2020-07-03T06:26:07.875201 | 2016-11-19T07:04:29 | 2016-11-19T07:04:29 | 74,192,785 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,678 | cpp | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 "DecafRuntime.h"
#include <apr.h>
#include <apr_general.h>
#include <apr_pools.h>
#include <decaf/lang/System.h>
#include <decaf/lang/Thread.h>
#include <decaf/internal/net/Network.h>
#include <decaf/internal/security/SecurityRuntime.h>
#include <decaf/internal/util/concurrent/Threading.h>
using namespace decaf;
using namespace decaf::internal;
using namespace decaf::internal::net;
using namespace decaf::internal::security;
using namespace decaf::internal::util::concurrent;
using namespace decaf::lang;
using namespace decaf::util::concurrent;
////////////////////////////////////////////////////////////////////////////////
namespace {
apr_pool_t* aprPool;
Mutex* globalLock;
}
////////////////////////////////////////////////////////////////////////////////
DecafRuntime::DecafRuntime() : decaf::lang::Runtime() {
}
////////////////////////////////////////////////////////////////////////////////
DecafRuntime::~DecafRuntime() {
}
////////////////////////////////////////////////////////////////////////////////
apr_pool_t* DecafRuntime::getGlobalPool() const {
return aprPool;
}
////////////////////////////////////////////////////////////////////////////////
Mutex* DecafRuntime::getGlobalLock() {
return globalLock;
}
////////////////////////////////////////////////////////////////////////////////
Runtime* Runtime::getRuntime() {
static DecafRuntime runtime;
return &runtime;
}
////////////////////////////////////////////////////////////////////////////////
void Runtime::initializeRuntime(int argc, char **argv) {
// Initializes the APR Runtime from within a library.
apr_initialize();
apr_pool_create_ex(&aprPool, NULL, NULL, NULL);
Runtime::getRuntime();
Threading::initialize();
globalLock = new Mutex;
System::initSystem(argc, argv);
Network::initializeNetworking();
SecurityRuntime::initializeSecurity();
}
////////////////////////////////////////////////////////////////////////////////
void Runtime::initializeRuntime() {
Runtime::initializeRuntime(0, NULL);
}
////////////////////////////////////////////////////////////////////////////////
void Runtime::shutdownRuntime() {
SecurityRuntime::shutdownSecurity();
// Shutdown the networking layer before Threading, many network routines need
// to be thread safe and require Threading primitives.
Network::shutdownNetworking();
System::shutdownSystem();
// This must go away before Threading is shutdown.
delete globalLock;
// Threading is the last to by shutdown since most other parts of the Runtime
// need to make use of Thread primitives.
Threading::shutdown();
// Cleans up APR data structures.
apr_pool_destroy(aprPool);
apr_terminate();
}
| [
"626955115@qq.com"
] | 626955115@qq.com |
c3c44080ecac01ae1a6931b50bff95dc281bd140 | 3762eafb1544217ca71081ec7215d71d6e1cc9e2 | /Dynamic Programming/Dynamic Programming/1937.cpp | 9acd9d11b71a0f923092d0b3060fbfa983073e01 | [] | no_license | challenger71498/Algorithm | 710f4a75d5adadb6bd555ae02c0c7974c3e77a77 | 09db61e56f7e657210dde91061ea218d4d09e41f | refs/heads/master | 2020-12-20T02:43:33.965776 | 2020-02-03T17:03:09 | 2020-02-03T17:03:09 | 235,936,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,187 | cpp | #include <iostream>
#include <deque>
#include <algorithm>
#include <climits>
using namespace std;
typedef pair<int, int> ii;
int arr[502][502];
deque<ii> st;
int len[502][502];
int n;
void chk(int x, int y) {
int v = arr[x][y];
int* l = &len[x][y];
if (v != arr[x + 1][y]) {
*l = max(*l, len[x + 1][y]);
}
if (v != arr[x - 1][y]) {
*l = max(*l, len[x - 1][y]);
}
if (v != arr[x][y + 1]) {
*l = max(*l, len[x][y + 1]);
}
if (v != arr[x][y - 1]) {
*l = max(*l, len[x][y - 1]);
}
*l += 1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
cin >> arr[i][j];
st.push_back({ i, j });
}
}
sort(st.begin(), st.end(), [](ii a, ii b) {
return arr[a.first][a.second] > arr[b.first][b.second];
});
for (int i = 0; i < st.size(); ++i) {
chk(st[i].first, st[i].second);
/*for (int j = 1; j <= n; ++j) {
for (int k = 1; k <= n; ++k) {
cout << len[j][k] << ' ';
}
cout << '\n';
}
cout << '\n';*/
}
int maxi = INT_MIN;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
maxi = max(maxi, len[i][j]);
}
}
cout << maxi << '\n';
} | [
"challenger71498@gmail.com"
] | challenger71498@gmail.com |
7679563da73d36201fbc00a0d67dceb06a22bfac | db1c300a95ec1e11263b78e0d2aab797fa812558 | /Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal/cbtfiapt.cc | e1aeeb6b2cc8a99aa8e2f5b3314b67fdc763f6b5 | [] | no_license | graywzc/leetcode2 | cd218e9d0de2600f10a66aabc5602e0b075e824b | 243c5c5671d26a6b5c174faa43509876a28a3073 | refs/heads/master | 2016-09-06T15:52:20.846244 | 2015-05-30T20:11:37 | 2015-05-30T20:11:37 | 34,969,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | cc | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(const vector<int>& inorder,
int istart,
int iend,
const vector<int>& postorder,
int pstart,
int pend)
{
if(istart>iend)
return NULL;
else if(istart == iend)
{
TreeNode *root = new TreeNode(inorder[istart]);
return root;
}
else
{
TreeNode *root = new TreeNode(postorder[pend]);
int i = istart;
while(inorder[i]!=postorder[pend])
i++;
root->left = buildTree(inorder,istart,i-1,postorder,pstart,i-1-istart+pstart);
root->right = buildTree(inorder,i+1,iend,postorder,i-istart+pstart,pend-1);
return root;
}
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
}
};
| [
"graywzc@gmail.com"
] | graywzc@gmail.com |
5483e62b35f56845325429369351c2de3374ab7e | a0bdedcc814dfcbf6f1742c398b64a31619af4df | /ideccmbd/gbl/JobIdecStereo_blks.cpp | 679c968af03cbea563358db9fb24041f3e07f981 | [
"BSD-2-Clause"
] | permissive | mpsitech/idec_public | ec7231939b8987fd66482d99276609e16d4ad3f7 | a74cf1c7095e08ee61b237fddc1642f83dbb852d | refs/heads/master | 2021-05-13T20:43:55.046131 | 2018-06-09T16:11:30 | 2018-06-09T16:11:30 | 116,916,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,209 | cpp | /**
* \file JobIdecStereo_blks.cpp
* job handler for job JobIdecStereo (implementation of blocks)
* \author Alexander Wirthmueller
* \date created: 30 Dec 2017
* \date modified: 30 Dec 2017
*/
/******************************************************************************
class JobIdecStereo::VecVSge
******************************************************************************/
uint JobIdecStereo::VecVSge::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "idle") return IDLE;
else if (s == "ready") return READY;
else if (s == "acqidle") return ACQIDLE;
else if (s == "acq") return ACQ;
else if (s == "prcidle") return PRCIDLE;
else if (s == "prc") return PRC;
return(0);
};
string JobIdecStereo::VecVSge::getSref(
const uint ix
) {
if (ix == IDLE) return("idle");
else if (ix == READY) return("ready");
else if (ix == ACQIDLE) return("acqidle");
else if (ix == ACQ) return("acq");
else if (ix == PRCIDLE) return("prcidle");
else if (ix == PRC) return("prc");
return("");
};
void JobIdecStereo::VecVSge::fillFeed(
Feed& feed
) {
feed.clear();
for (unsigned int i=1;i<=6;i++) feed.appendIxSrefTitles(i, getSref(i), getSref(i));
};
| [
"mpsitech@ungenio.local"
] | mpsitech@ungenio.local |
61c61ac3e66e4f56395f2d311e1a854d3dcbc737 | 6ae42ae04953d0bd619554b2191ae4a63adec3d0 | /PlistToFnt/dialog.cpp | a19d2e4c8853b8c3a7ccf1c31d4fb4f04695e030 | [] | no_license | wolfand11/Tools_PlistToFnt | ce0a0138dc8f6bac98300060c9507341fe757426 | 51a5b3d893d00edcf4a8a4cfed02aa42fddfb4b3 | refs/heads/master | 2016-09-05T18:04:12.857367 | 2013-12-10T11:42:23 | 2013-12-10T11:42:23 | 14,587,375 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,880 | cpp | #include "dialog.h"
#include "ui_dialog.h"
#include <QFileDialog>
#include <QDir>
#include "gsetting.h"
#include "./libs/qtplist/PListParser.h"
#include "./libs/qtplist/PListSerializer.h"
#include "./libs/fnt/fntserializer.h"
#define kPlistFileSuffix ".plist"
#define kFntFileSuffix ".fnt"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::ShowMessage(const QString& msg)
{
ui->textEdit->setText(msg);
}
void Dialog::selectFile()
{
QString plistFilePath = GSetting::GetInstance()->ReadPlistFilePathSetting();
m_fileFullPath = QFileDialog::getOpenFileName(this,
"Select Plist File",
plistFilePath,
tr("Plist (*.plist)"));
if(m_fileFullPath.isEmpty())
{
m_message = "Please select plist file";
}
else
{
m_message = "You Selected File: \n\n";
m_message += m_fileFullPath;
GSetting::GetInstance()->WritePlistFilePathSetting(m_fileFullPath);
}
ShowMessage(m_message);
}
void Dialog::convertFile()
{
QFile readFile(m_fileFullPath);
if(!readFile.open(QFile::ReadOnly | QIODevice::Text))
{
ShowMessage("ERROR:\n Open plist file failed!\n Please Select Plist file.");
return;
}
QVariant plistVar = PListParser::parsePList(&readFile);
QString fntStr = FntSerializer::ConvertPlistVarToFntDataStr(plistVar);
QString fntFileFullPath = m_fileFullPath.replace(kPlistFileSuffix,kFntFileSuffix);
QFile writeFile(fntFileFullPath);
writeFile.open(QFile::WriteOnly | QIODevice::Text);
writeFile.write(fntStr.toStdString().c_str());
ShowMessage("Convert Completed!\n Please Select Plist file.");
}
| [
"smile_guodong@163.com"
] | smile_guodong@163.com |
18a5aeda1b3358b41fc847a8057a50df9cc49512 | 8784d329b85af404060555631e47887258f4cc4b | /libHttp/lib_socket.h | 05950423733db3828033cb03bfd727e72283b8c1 | [] | no_license | mojo55aa/libHttp | d0a5285f64ca6b1351e447b1aed98b62137a11ca | 0ecd0f80978f8dd502060d1e5a5df8bdf572c53d | refs/heads/master | 2020-04-21T07:01:57.413947 | 2019-02-08T02:55:07 | 2019-02-08T02:55:07 | 169,382,006 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | h | //#pragma once
#include <string>
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define DNS_ERROR "dns_err"
#ifdef __LINUX__
#include <sys/socket.h>
#define INVALID_SOCKET -1
typedef int SOCKET;
#else
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#endif // __LINUX__
class LIBSocket
{
public:
LIBSocket();
virtual ~LIBSocket();
bool Connect(const char* ip, unsigned int port);
__int64 Send(const char* buff, unsigned int nbytes);
__int64 Recv(char* buff, unsigned int nbytes);
protected:
private:
SOCKET mSocket;
};
std::string GetSockErrMsg();
std::string GetIpByDomain(const char* domain); | [
"format0103@163.com"
] | format0103@163.com |
17bfbe68ebd0abf874c7784bb510a3d1669972f2 | 0e227713c07dbbc686432913c69a95f7f047fdc8 | /finalProject/finalProject/greyShell.cpp | 8694c55bd0e5d0d9afec66fad551e1696e533cab | [] | no_license | MeetPuppet/2019-WIN-API | aecb2e2fa54515d6c7d6b4d730891ef600487315 | 1aa0056b5d6eebfd34b5ac538b4997862987e2f8 | refs/heads/master | 2022-12-20T02:24:04.899545 | 2020-10-20T04:57:43 | 2020-10-20T04:57:43 | 186,378,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 477 | cpp | #include "stdafx.h"
#include "greyShell.h"
greyShell::greyShell()
{
}
greyShell::~greyShell()
{
}
HRESULT greyShell::init(int x, int y, int sizeX, int sizeY)
{
objectNode::init("greyShell", x, y, sizeX, sizeY);
timenum = 0;
return S_OK;
}
void greyShell::update()
{
objectNode::update();
timenum++;
if (timenum > 100) {
if (frameX == 0) {
frameX = 1;
}
else
frameX = 0;
}
if (timenum > 500) {
}
}
void greyShell::render()
{
objectNode::render();
} | [
"gnslgns2000@naver.com"
] | gnslgns2000@naver.com |
f00cb7fe4d1750a9d81afb4c71cb92354c843d40 | 3a50c0712e0a31b88d0a5e80a0c01dbefc6a6e75 | /thrift/test/FieldRefBenchmark.cpp | 706f851ea29b5cc158903e35fe401137cd7bc28a | [
"Apache-2.0"
] | permissive | facebook/fbthrift | 3b7b94a533666c965ce69cfd6054041218b1ea6f | 53cf6f138a7648efe5aef9a263aabed3d282df91 | refs/heads/main | 2023-08-24T12:51:32.367985 | 2023-08-24T08:28:35 | 2023-08-24T08:28:35 | 11,131,631 | 2,347 | 666 | Apache-2.0 | 2023-09-01T01:44:39 | 2013-07-02T18:15:51 | C++ | UTF-8 | C++ | false | false | 2,109 | cpp | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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 <glog/logging.h>
#include <folly/Benchmark.h>
#include <folly/Portability.h>
#include <folly/init/Init.h>
#include <thrift/test/gen-cpp2/optionals_types.h>
using namespace std;
using namespace cpp2;
using namespace folly;
BENCHMARK_COUNTERS(field_ref_direct, counters, n) {
HasOptionals a;
counters["stack_mem"] = sizeof(a);
int64_t k = n * (1 + 'a');
while (n--) {
a.int64Opt() = 1;
k -= a.int64Opt().value();
a.stringOpt() = "a";
k -= a.stringOpt().value()[0];
}
CHECK_EQ(k, 0);
folly::doNotOptimizeAway(k);
}
template <class T, class U>
FOLLY_NOINLINE void run(T int64Opt_ref, U stringOpt_ref, int n) {
int64_t k = n * (1 + 'a');
while (n--) {
int64Opt_ref = 1;
k -= int64Opt_ref.value();
stringOpt_ref = "a";
k -= stringOpt_ref.value()[0];
}
CHECK_EQ(k, 0);
folly::doNotOptimizeAway(k);
}
BENCHMARK_RELATIVE(field_ref_indirect, n) {
HasOptionals a;
run(a.int64Opt(), a.stringOpt(), n);
}
BENCHMARK_RELATIVE(unsafe, n) {
HasOptionals a;
apache::thrift::ensure_isset_unsafe(a.int64Opt());
apache::thrift::ensure_isset_unsafe(a.stringOpt());
int64_t k = n * (1 + 'a');
while (n--) {
a.int64Opt().value_unchecked() = 1;
k -= a.int64Opt().value_unchecked();
a.stringOpt().value_unchecked() = "a";
k -= a.stringOpt().value_unchecked()[0];
}
CHECK_EQ(k, 0);
folly::doNotOptimizeAway(k);
}
int main(int argc, char** argv) {
folly::init(&argc, &argv);
runBenchmarks();
return 0;
}
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
02554a3ef3162531d98ec7e3fa683c8a17eaa75a | 89870ca1f16af0f2ba65ec0175cd089da852afbc | /codeforces/round-737-div-2/c.cpp | 90e3c2dd6745a05279a7185f3eb4059d68db05de | [] | no_license | Merisho/comprog | 3b8ce833f0f16dbcfa252f9c6678c160bf081a11 | fb4829ba93fcb376078a5baccda0c07ce35d6d04 | refs/heads/master | 2023-08-18T00:10:45.535195 | 2023-08-11T07:16:02 | 2023-08-11T07:16:02 | 216,174,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,560 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr ll MOD = 1e9 + 7;
ll binexp(ll n, ll e, ll p) {
if (e == 0) {
return 1;
}
if (e % 2 == 0) {
ll a = binexp(n, e / 2, p);
return (a * a) % p;
}
return (binexp(n, e - 1, p) * n) % p;
}
ll modinv(ll n, ll p) {
return binexp(n, p - 2, p);
}
vector<ll> mem_fact(300000, -1);
ll fact(ll n, ll p) {
mem_fact[0] = 1;
mem_fact[1] = 1;
if (mem_fact[n] > -1) {
return mem_fact[n];
}
for (ll i = 2; i <= n; ++i) {
mem_fact[i] = (mem_fact[i - 1] * i) % p;
}
return mem_fact[n];
}
ll choose(ll n, ll k, ll p) {
ll nf = fact(n, p);
ll kf = fact(k, p);
ll df = fact(n - k, p);
return (((nf * modinv(kf, p)) % p) * modinv(df, p)) % p;
}
int main() {
ll T;
cin >> T;
for (ll test_case = 1; test_case <= T; ++test_case) {
ll n, k;
cin >> n >> k;
ll odd = 0;
ll even = 0;
for (ll i = 0; i < n; ++i) {
if (i % 2 == 0) {
even = (even + choose(n, i, MOD)) % MOD;
} else {
odd = (odd + choose(n, i, MOD)) % MOD;
}
}
ll dp[k + 1][2];
dp[0][0] = 1;
dp[0][1] = 0;
for (ll i = 0; i < k; ++i) {
dp[i + 1][0] = (dp[i][0] * even) % MOD;
dp[i + 1][1] = (dp[i][1] * even) % MOD;
dp[i + 1][1] = (dp[i + 1][1] + ((dp[i][1] * odd) % MOD)) % MOD;
dp[i + 1][1] = (dp[i + 1][1] + dp[i][1]) % MOD;
if (n % 2 == 0) {
dp[i + 1][1] = (dp[i + 1][1] + dp[i][0]) % MOD;
} else {
dp[i + 1][0] = (dp[i + 1][0] + dp[i][0]) % MOD;
}
}
ll res = (dp[k][0] + dp[k][1]) % MOD;
cout << res << endl;
}
return 0;
}
| [
"merishot@gmail.com"
] | merishot@gmail.com |
606bab50851eb5b8b34c3fb298e057efabdb181e | 780f8126f04a71080a229b9b72b6b69b6f7b49d7 | /multiview/multiview_cpp/src/perceive/cost-functions/features-2d/run-scharr.cpp | 2192c7adead2511742ebb7c9943de6cc23d99726 | [
"Apache-2.0"
] | permissive | shang766/multiview | b882ae5d1d84ee29609535c6a81b8a715453fcda | 1a03e14855292967ffb0c0ec7fff855c5abbc9d2 | refs/heads/main | 2023-08-28T19:35:11.279270 | 2021-10-03T01:14:22 | 2021-10-03T01:14:22 | 452,168,226 | 1 | 0 | Apache-2.0 | 2022-01-26T06:42:52 | 2022-01-26T06:42:51 | null | UTF-8 | C++ | false | false | 3,062 | cpp |
#include "features-2d.hpp"
#include "perceive/foundation.hpp"
#include "perceive/geometry/vector.hpp"
#include "perceive/graphics/colour-set.hpp"
#include <opencv2/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
namespace perceive
{
// ---------------------------------------------------------------------- Scharr
void run_scharr(ImageFeatures2d& ss,
const cv::Mat& grey,
const ImageFeatures2d::Params& p,
std::function<bool(void)> is_canceled)
{
Expects(ss.w != 0);
Expects(ss.h != 0);
const auto w = ss.w;
const auto h = ss.h;
if(is_canceled()) return;
unsigned blur_sz = p.scharr_blur_sz;
double blur_sigma = p.scharr_blur_sigma;
// Apply Gaussian blur
auto sz = cv::Size(int(blur_sz), int(blur_sz));
cv::GaussianBlur(grey, grey, sz, blur_sigma, blur_sigma, cv::BORDER_DEFAULT);
/// Generate grad_x and grad_y
cv::Mat grad_x, grad_y;
cv::Mat abs_grad_x, abs_grad_y;
/// Gradient X and Y
auto ddepth = CV_32F; // produce floating-point images
Scharr(grey, grad_x, ddepth, 1, 0);
Scharr(grey, grad_y, ddepth, 0, 1);
if(is_canceled()) return;
// Convert to a field...
auto& field = ss.scharr;
auto& invmag = ss.scharr_invmag;
field.resize(grey.cols, grey.rows);
invmag.resize(grey.cols, grey.rows);
// Pack result into our field...
auto dst = field.data();
auto d2 = invmag.data();
std::vector<real> mags;
mags.reserve(size_t(grey.rows * grey.cols));
for(int y = 0; y < grey.rows; ++y) {
const float* src_x = grad_x.ptr<const float>(y);
const float* src_y = grad_y.ptr<const float>(y);
for(int x = 0; x < grey.cols; ++x) {
dst->x = real(*src_x++);
dst->y = real(*src_y++);
auto norm = dst->norm();
auto mag_inv = 1.0 / norm;
mags.emplace_back(norm);
// if(!std::isfinite(mag_inv)) {
// cout << format("mag_inv = {}, dst = {}",
// mag_inv, dst->to_string())
// << endl;
// FATAL("kBAM!");
// }
*d2++ = float(mag_inv);
dst++;
}
}
// Calculate statistics
ss.scharr_mag_stats = calc_sample_statistics(mags.begin(), mags.end());
// Make the threshold image
const auto threshold
= ss.scharr_mag_stats.median
+ p.scharr_threshold_absdevs * ss.scharr_mag_stats.absdev;
{
auto& im = ss.scharr_binary;
im.resize(field.width, field.height);
im.resize(w, h);
im.zero();
for(auto y = 0u; y < field.height; ++y) {
for(auto x = 0u; x < field.width; ++x) {
Vector2 v = field(x, y);
if(v.norm() > threshold) {
auto theta = atan2(v.y, v.x);
if(theta < 0) theta += M_PI;
im(x, y) = angle_to_colour(theta);
}
}
}
}
}
} // namespace perceive
| [
"everett@perceiveinc.com"
] | everett@perceiveinc.com |
ccda5af3e7a546b7549e05cac8ec9b8ee73b9375 | d47ed5449b8cda84f4343750f122a09ef537b090 | /Source/Game/public/SGameMode.h | cd3c17714b3797761a6aa96cac68388b191c301b | [] | no_license | Helaly96/UE4-BarthGame | 1993b5631e96117b0ec81c0d4f4f5a7f1cbab331 | 7119885a8fc7d2d3d8641a6d81faa8f3710b2581 | refs/heads/master | 2022-09-25T10:50:45.477744 | 2020-06-05T00:46:14 | 2020-06-05T00:46:14 | 266,905,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "SGameMode.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnActorKilled ,AActor*, KillerActor, AActor*, KilledActor,AController *,KillerController);
struct FCurrentScore;
/**
*
*/
UCLASS()
class GAME_API ASGameMode : public AGameModeBase
{
GENERATED_BODY()
protected:
UFUNCTION(BlueprintImplementableEvent)
void SpawnNewBot();
void SpawnBotTimerElapsed();
void StartWave();
void PrepareForNextWave();
void EndWave();
void SetMatchScore(FCurrentScore Score);
void AssignTeams();
//bots to spawn in a current wave
float NoOfBots;
//Number of survived waves
int WaveCount;
FTimerHandle TimerHandle_SpawnBot;
UPROPERTY(EditDefaultsOnly)
float TimeBetweenWaves;
public:
void RestartDeadPlayers();
APlayerController* PlayerToRevive;
virtual void Tick(float DeltaSeconds) override;
void Revive();
ASGameMode();
virtual void StartPlay() override;
UPROPERTY(BlueprintAssignable)
FOnActorKilled OnActorKilled;
int next_assignable_team;
};
| [
"zfaesu@gmail.com"
] | zfaesu@gmail.com |
6127da0c80ed45d083b9e43a73a58508665871c7 | ced632b0a81654ec9ea3f270e2e51d36170dd050 | /src/localization/src/frombfl/mobile_robot.h | da3e93d8fb332fb51c3fadaec4dad849421f169f | [] | no_license | lian16thu/RoboCup | 4a0b84f54a6253a1284e3922c54210bb8239087b | 95dbd5753be3f0391176420ec2cb012d8fda59fe | refs/heads/master | 2020-04-30T15:21:31.379146 | 2019-03-21T10:04:40 | 2019-03-21T10:04:40 | 176,918,206 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,766 | h | // $Id: mobile_robot.h tdelaet $
// Copyright (C) 2006 Tinne De Laet <first dot last at mech dot kuleuven dot be>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef MOBILE_ROBOT_HPP
#define MOBILE_ROBOT_HPP
#include <bfl/model/analyticsystemmodel_gaussianuncertainty.h>
#include <bfl/model/linearanalyticmeasurementmodel_gaussianuncertainty.h>
#include <bfl/pdf/gaussian.h>
#include "matrix_wrapper.h"
#include "vector_wrapper.h"
#include <bfl/wrappers/matrix/matrix_NEWMAT.h>
#include <bfl/wrappers/matrix/matrix_LTI.h>
#include <bfl/wrappers/matrix/matrix_BOOST.h>
namespace BFL{
class MobileRobot
{
public:
// Constructor
MobileRobot();
~MobileRobot();
void Move(MatrixWrapper::ColumnVector inputs);
MatrixWrapper::ColumnVector Measure();
MatrixWrapper::ColumnVector GetState(); //method only for simulation purposes
private:
Gaussian* _sys_noise;
Gaussian* _meas_noise;
MatrixWrapper::Matrix _meas_model;
MatrixWrapper::ColumnVector _state;
};
}
#endif
| [
"lian16thu"
] | lian16thu |
059ebc32b0ffa6e7552d68da8b9de8f10236b4a0 | 03d3231478373089a3de04db162f61b79a388fd3 | /l2packets/l2world/L2Npc.cpp | 816cef502291c3a828bb8ed370bb4bb6e461c5ce | [] | no_license | minlexx/l2-unlegits | f4b0e9d70afe2a0a26f81daa16123eb2fe31cc13 | fc189ca35edf14439a5eeac81359b30112496b80 | refs/heads/master | 2021-01-17T05:35:09.738039 | 2015-06-28T09:16:13 | 2015-06-28T09:16:13 | 38,192,499 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,552 | cpp | #include "stdafx.h"
#include "L2Npc.h"
#include "../l2data/L2Data.h"
#include "../game/L2GamePacket.h"
#include "../os/os_abstraction.h"
L2Npc::L2Npc()
{
setUnused();
}
L2Npc::~L2Npc()
{
setUnused();
}
L2Npc::L2Npc( const L2Npc& other ): L2Character()
{
setUnused();
operator=( other );
}
const L2Npc& L2Npc::operator=( const L2Npc& other )
{
if( this == &other ) return (*this);
L2Character::operator=( other );
templateID = other.templateID;
isAttackable = other.isAttackable;
iid_left_hand = other.iid_left_hand;
iid_right_hand = other.iid_right_hand;
iid_chest = other.iid_chest;
return (*this);
}
void L2Npc::setUnused()
{
L2Character::setUnused();
templateID = 0;
isAttackable = 0;
// weapon
iid_left_hand = iid_right_hand = iid_chest = 0;
}
void L2Npc::setNpcNameTitleByTemplate()
{
char db_name[256], db_title[256];
db_name[0] = db_title[0] = 0;
if( L2Data_DB_GetNPCNameTitleByID( templateID, db_name, db_title ) )
{
setName( db_name );
setTitle( db_title );
}
}
bool L2Npc::parse_NpcInfo( void *l2_game_packet, L2_VERSION l2_version )
{
if( !l2_game_packet ) return false;
L2GamePacket *p = (L2GamePacket *)l2_game_packet;
// parse
unsigned char ptype = p->getPacketType();
if( ptype != 0x0C ) return false; // 0x0C NpcInfo
//
objectID = p->readUInt();
templateID = p->readUInt() - 1000000; // ? :) L2J adds 1000000 to this field
isAttackable = p->readD(); // _isAttackable
x = p->readD();
y = p->readD();
z = p->readD();
heading = p->readUInt();
p->readD(); // 0x00
mAtkSpd = p->readD();
pAtkSpd = p->readD();
runSpeed = p->readD();
walkSpeed = p->readD();
p->readD(); // swim run speed
p->readD(); // swim walk speed
p->readD(); // fl run speed (?)
p->readD(); // fl walk speed (?)
p->readD(); // fly run speed (?) same as fl
p->readD(); // fly walk speed (?)
double moveSpeedMultiplier = p->readF();
double attackSpeedMultiplier = p->readF();
if( moveSpeedMultiplier > 0 )
{
runSpeed = (int)( ((double)runSpeed) * moveSpeedMultiplier );
walkSpeed = (int)( ((double)walkSpeed) * moveSpeedMultiplier );
}
if( attackSpeedMultiplier > 0 ) pAtkSpd = (int)( ((double)pAtkSpd) * attackSpeedMultiplier );
collisionRadius = p->readF();
collisionHeight = p->readF();
iid_right_hand = p->readUInt();
iid_chest = p->readUInt();
iid_left_hand = p->readUInt();
p->readC(); // has title
isRunning = p->readC();
isInCombat = p->readC();
isAlikeDead = p->readC();
p->readC(); // is summoned
setName( p->readUnicodeStringPtr() );
setTitle( p->readUnicodeStringPtr() );
p->readD(); // title color
p->readD(); // 0x00
pvpFlag = p->readD(); // pvp flag
abnormalEffect = p->readUInt();
clanID = p->readUInt(); // Gracia Final
clanCrestID = p->readUInt(); // Gracia Final
isFlying = p->readC(); // Gracia Final
p->readC(); // 0x00
p->readF(); // collisionRadius (again?)
p->readF(); // collisionHeight (again?)
p->readD(); // 0x00
p->readD(); // isFlying? (again?) Gracia Final
p->readD(); // 0x00
p->readD(); // pet form and skills (?)
// Gracia Final has some more to read
if( l2_version >= L2_VERSION_T23 )
{
p->readC(); // 0x01
p->readC(); // 0x01
p->readD(); // 0x00000000
}
// set last time when npc coordinates were known exactly
lastMoveTickTime = OS_GetTickCount();
return true;
}
| [
"alexey.min@gmail.com"
] | alexey.min@gmail.com |
4ef662429e50863f690dd73786eb250f3ae20629 | ed2aa12a14dd8594b303bb508923bdda3a62eeb9 | /PhotonChat/LoadBalancing-cpp/inc/Enums/MatchmakingMode.h | a16798abd987717bfcb9546a076821d8b9a0586d | [
"MIT"
] | permissive | anhtrangg/PhotonChat | c7e83dae1107746abc83f43e541ae4b85ed54dd0 | 4bd5788fe4ec89dab83ae01d7f372b6e9bd5ebc9 | refs/heads/master | 2023-04-12T09:53:53.273785 | 2021-05-17T08:27:32 | 2021-05-17T08:27:32 | 364,878,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,009 | h | /* Exit Games Photon LoadBalancing - C++ Client Lib
* Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved.
* http://www.photonengine.com
* mailto:developer@photonengine.com
*/
#pragma once
#include "Common-cpp/inc/Common.h"
namespace ExitGames
{
namespace LoadBalancing
{
/**
Options for matchmaking rules for OpJoinRandomRoom.*/
namespace MatchmakingMode
{
static const nByte FILL_ROOM = 0; ///<Fills up rooms (oldest first) to get players together as fast as possible. Default. Makes most sense with MaxPlayers > 0 and games that can only start with more players.
static const nByte SERIAL_MATCHING = 1; ///<Distributes players across available rooms sequentially but takes filters into account. Without filters, rooms get players evenly distributed.
static const nByte RANDOM_MATCHING = 2; ///<Joins a (fully) random room. Expected properties must match, but aside from this, any available room might be selected.
}
/** @file */
}
} | [
"anh.tran@gogame.net"
] | anh.tran@gogame.net |
9fc4222e178dc2ac51fd665ee8fca3e6e40e08f5 | 3d5f96474b2596fe743a87323285c79aae047185 | /GLES3/GLES/HelloScene.cpp | 890dcc2cda32c21c6cd60660ddd75013e9665bcf | [] | no_license | 1414648814/GLES3 | 932dda44c6e79767cc1a3a54798e8be79ef3750c | 8a4fd6e61fcfef37f53783136255f2c1623712f8 | refs/heads/sceneisnode | 2021-01-22T04:14:46.233071 | 2017-02-12T07:22:59 | 2017-02-12T07:22:59 | 81,521,232 | 0 | 0 | null | 2017-02-12T07:22:59 | 2017-02-10T03:14:17 | C++ | UTF-8 | C++ | false | false | 802 | cpp | //
// HelloScene.cpp
// GLES
//
// Created by staff on 2016/12/27.
// Copyright © 2016年 George1994. All rights reserved.
//
#include "HelloScene.h"
#include "CCGame.h"
HelloScene::HelloScene() : Scene() {
}
HelloScene::~HelloScene() {
}
Scene* HelloScene::scene() {
HelloScene* scene = new HelloScene();
if (scene && scene->init()) {
return scene;
}
return nullptr;
}
// insert code into here
bool HelloScene::init() {
if (!Scene::init()) {
return false;
}
auto visibleSize = Game::getInstance()->getVisibleSize();
auto sp = Sprite::create("/Users/staff/Desktop/GLES3/GLES3/wall.jpg", 1);
sp->setAnchorPoint(Vector2(0.0, 0.0));
sp->setPosition(Vector2(150, 50));
this->addChild(sp, 1);
return true;
} | [
"1414648814@qq.com"
] | 1414648814@qq.com |
b60fea8cc6b976d323fae0dda2e654c378a55b4b | 1513f7e79a7142c933636066908b79ebc131f10e | /squashfs-root/usr/include/KF5/KI18n/kuitmarkup.h | e17073b72afc7922f210223501eeeee7992b54b7 | [] | no_license | softwarenerd7/eXternOS-Base | 1e11dd26ae2dfebe77cf3a46c0e6925bc7f83542 | 2e202775e52dd69352b7325d270090323121111d | refs/heads/master | 2023-01-12T10:31:48.635447 | 2020-11-17T21:08:36 | 2020-11-17T21:08:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,502 | h | /* This file is part of the KDE libraries
Copyright (C) 2013 Chusslove Illich <caslav.ilic@gmx.net>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef KUITMARKUP_H
#define KUITMARKUP_H
#include <ki18n_export.h>
#include <QString>
#include <QStringList>
#include <QHash>
class KuitSetup;
/**
* Global constants and functions related to KUIT markup.
*/
namespace Kuit
{
/**
* Visual formats into which KUIT markup can be resolved.
*/
enum VisualFormat {
/**
* Visual format not defined.
* This value can be explicitly set
* (e.g. through \c KLocalizedString::withFormat)
* to indicate that the format should be decided
* by another mechanism (e.g. context UI marker).
*/
UndefinedFormat = 0,
/**
* Plain text.
*/
PlainText = 10,
/**
* Qt rich text (HTML subset).
*/
RichText = 20,
/**
* Terminal escape sequences.
*/
TermText = 30
};
/**
* Classification of KUIT tags.
*/
enum TagClass {
/**
* Tags wrapping text inserted into running text.
*/
PhraseTag = 0,
/**
* Tags spliting text into paragraph-level blocks.
*/
StructTag = 1
};
/**
* Functions accepted by tag formatting functions.
*
* \param languages the target languages (by decreasing priority)
* \param tagName the wrapping tag name
* \param attributes the attribute name-value pairs in the tag
* \param text the wrapped text
* \param tagPath the ordered list of ancestor tag names, parent first
* \param format the target visual format
* \return formatted text
*/
typedef QString(*TagFormatter)(const QStringList &languages,
const QString &tagName,
const QHash<QString, QString> &attributes,
const QString &text,
const QStringList &tagPath,
Kuit::VisualFormat format);
/**
* Get hold of the KUIT setup object for a given domain.
*
* \param domain the translation domain
* \return pointer to KUIT setup object
*/
KuitSetup &setupForDomain(const char *domain);
KuitSetup &setupForDomain(const QByteArray& domain);
}
class KLocalizedString;
class KuitSetupPrivate;
class KuitFormatterPrivate;
/**
* @class KuitSetup kuitmarkup.h <KuitSetup>
*
* Class for modifying KUIT markup in a given domain.
*
* Not directly constructed, but obtained through \c Kuit::setupForDomain.
*/
class KI18N_EXPORT KuitSetup
{
friend KuitSetup &Kuit::setupForDomain(const QByteArray& domain);
friend class KuitFormatterPrivate;
public:
/**
* Destructor.
*/
~KuitSetup();
/**
* Set the formatting string for a tag with attributes combination.
*
* If a new tag name is given, this effectively defines a new tag.
* The same holds for attribute names.
*
* The pattern string \p pattern should contain placeholders
* for inserting the text and the attribute values.
* %1 will be replaced with the wrapped text, and %2 and upwards
* with attribute values in the order given by \p attrNames.
* Non markup-aware translation call with context (\c ki18nc)
* should be used to create the pattern string.
*
* In addition to the pattern, a formatting function
* of the type \c TagFormatter can be given.
* This function receives the full markup parsing context,
* so that it can do whatever is necessary with the wrapped text.
* The result of this function is then substituted into the pattern.
* You can also give an empty pattern (as <tt>KLocalizedString()</tt>)
* together with the formatting function, in which case the function
* is assumed to do everything and no substitution is performed.
*
* \param tagName the name of the tag
* \param attribNames the names of the attributes (empty names are ignored)
* \param format the target visual format
* \param pattern the pattern string
* \param leadingNewlines the number of new lines (\\n) to be maintained
* between any preceding text and the text wrapped
* with this tag (for formats where it matters)
*/
void setTagPattern(const QString &tagName,
const QStringList &attribNames,
Kuit::VisualFormat format,
const KLocalizedString &pattern,
Kuit::TagFormatter formatter = nullptr,
int leadingNewlines = 0);
/**
* Set the KUIT class of the tag.
*
* \param tagName the name of the tag
* \param aClass the KUIT tag class
*/
void setTagClass(const QString &tagName, Kuit::TagClass aClass);
/**
* Set the default visual format for a given UI marker.
*
* Giving <tt>"@<major>"</tt> for \p marker means to set the format
* only for standalone <tt>\@\<major\></tt> marker,
* while <tt>"@<major>:"</tt> (with trailing colon) means to set
* the same format for all <tt>\@\<major\>:\<minor\></tt> combinations.
*
* Defined UI marker major/minor combinations are listed in the section
* \ref uimark_ctxt. If an UI marker combination outside of the defined
* is given as \p marker, it will be ignored.
*
* Setting \c Kuit::UndefinedFormat as \p format
* means to fall back to default format for the given UI marker.
*
* \param marker the UI marker
* \param format the visual format
*/
void setFormatForMarker(const QString &marker, Kuit::VisualFormat format);
private:
KuitSetup(const QByteArray &domain);
Q_DISABLE_COPY(KuitSetup)
KuitSetupPrivate *const d;
};
#endif // KUITMARKUP_H
| [
"anesuemail@gmail.com"
] | anesuemail@gmail.com |
dafca8af74d70cd289ebd105cd4010a1bed9d6fb | bac010ab15283d0ec3f7bbe33f5ce2a0c28a822c | /SCANF6.CPP | 836dbf321b511725c7653c6050680b61f2be43d2 | [
"MIT"
] | permissive | sonu2016-stack/CPP_Programming_Language_Practice_Code | 8d12073e2544c891d9cbd322b784f92c7c16fbc6 | 50b143124690249e5dbd4eaaddfb8a3dadf48f1f | refs/heads/master | 2023-04-28T22:17:18.459328 | 2021-05-16T21:27:21 | 2021-05-16T21:27:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | cpp | //Program to Swap or Interchange the Value Using Third Variable
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
clrscr();
printf("Enter the Value of a= ");
scanf("%d",&a);
printf("Enter the Value of b= ");
scanf("%d",&b);
c=a;
a=b;
b=c;
printf("\nAfter Swapping Value of a= %d",a);
printf("\nAfter Swapping Value of b= %d",b);
getch();
} | [
"Kumarashish79924@gmail.com"
] | Kumarashish79924@gmail.com |
38cb27f00fe1c71e9743989fe7b1091dc0e2f9dd | e9fd7bc03ba68c04ee5dccb683158a59b4b9ad21 | /A1120.cpp | 79cc3314d5b4492a5efcfde9c2f4fd8335309dd6 | [] | no_license | LittleVolcano/MY-PAT | 77cc0890611106be797eb0e85d73efd9108c73b4 | 0489bb5ff1913ac4b8458368f391b47e36ea70e1 | refs/heads/master | 2021-05-09T03:53:41.683631 | 2018-04-08T03:06:52 | 2018-04-08T03:06:52 | 119,255,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | cpp |
#include<stdio.h>
int main()
{
int a[50] = {0};
int n;
int temp;
int friid;
int sum = 0;
int flag = 0;
scanf("%d",&n);
for(int i = 0;i < n; ++i)
{
friid = 0;
scanf("%d",&temp);
while(temp != 0)
{
friid += temp % 10;
temp /= 10;
}
a[friid]++;
}
for(int i = 0;i < 50; ++i)
{
if(a[i] != 0 )
++sum;
}
printf("%d\n",sum);
for(int i = 0;i < 50; ++i)
{
if(a[i] != 0 )
{
if(flag == 1)
printf(" ");
printf("%d",i);
flag = 1;
}
}
return 0;
}
| [
"495328602@qq.com"
] | 495328602@qq.com |
a4b3546f8dca8a4f9748227b4c3cdb0405a781cf | 45ae4cf99ef88c0348619030b9378a5f44a15e5f | /src/rnnhubo/rnn.cpp | a911acd98fdbc0bac4bd5c58974d6ee37accb2cd | [] | no_license | datemoon/rnn_lm_score | d24f5d70072f52d60a3b08d70b70d24e20a3d364 | 1ab69d656883f1fe846deeff484c7a33282108d1 | refs/heads/master | 2020-06-12T07:14:51.903019 | 2019-06-28T07:53:25 | 2019-06-28T07:53:25 | 194,229,279 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,505 | cpp | #include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "rnn.h"
void Rnn::LoadRNNLM(string modelname)
{
LoadTextRNNLM(modelname);
}
void Rnn::LoadTextRNNLM (string modelname)
{
int i, a, b;
float v;
char word[1024];
FILE *fptr = NULL;
// read model file
fptr = fopen (modelname.c_str(), "r");
if (fptr == NULL)
{
printf ("ERROR: Failed to read RNNLM model file(%s)\n", modelname.c_str());
exit (0);
}
fscanf (fptr, "cuedrnnlm v%f\n", &v);
if (v - 0.1 > 0.1 || v - 0.1 < -0.1)
{
printf ("Error: the version of rnnlm model(v%.1f) is not consistent with binary supported(v%.1f)\n", v, 0.1);
exit (0);
}
fscanf (fptr, "train file: %s\n", word); trainfile = word;
fscanf (fptr, "valid file: %s\n", word); validfile = word;
fscanf (fptr, "number of iteration: %d\n", &iter);
fscanf (fptr, "#train words: %d\n", &trainwordcnt);
fscanf (fptr, "#valid words: %d\n", &validwordcnt);
fscanf (fptr, "#layer: %d\n", &num_layer);
layersizes.resize(num_layer+1);
for (i=0; i<layersizes.size(); i++)
{
fscanf (fptr, "layer %d size: %d\n", &b, &a);
assert(b==i);
layersizes[i] = a;
}
fscanf (fptr, "feature dimension: %d\n", &dim_fea);
fscanf (fptr, "class layer dimension: %d\n", &nclass);
allocMem();
fscanf (fptr, "independent mode: %d\n", &independent);
fscanf (fptr, "train crit mode: %d\n", &traincritmode);
for (i=0; i<num_layer; i++)
{
fscanf (fptr, "layer %d -> %d\n", &a, &b);
assert (a==i);
assert (b==(i+1));
for (a=0; a<layersizes[i]; a++)
{
for (b=0; b<layersizes[i+1]; b++)
{
fscanf (fptr, "%f", &v);
if(0 != layers[i]->SetData(a, b, v))
{
fprintf(stderr,"matrix SetData error!\n");
return ;
}
}
fscanf (fptr, "\n");
}
}
fscanf (fptr, "recurrent layer 1 -> 1\n");
for (a=0; a<layersizes[1]; a++)
{
for (b=0; b<layersizes[1]; b++)
{
fscanf (fptr, "%f", &v);
if(0 != hidtohid_weight[0]->SetData(a, b, v))
{
fprintf(stderr,"matrix SetData error!\n");
return ;
}
}
fscanf (fptr, "\n");
}
/*
if (dim_fea > 0)
{
fscanf (fptr, "feature layer weight\n");
for (a=0; a<dim_fea; a++)
{
for (b=0; b<layersizes[1]; b++)
{
fscanf (fptr, "%f", &v);
layer0_fea->assignhostvalue(a, b, v);
}
fscanf (fptr, "\n");
}
}*/
if (nclass > 0)
{
fscanf (fptr, "class layer weight\n");
for (a=0; a<layersizes[num_layer-1]; a++)
{
for (b=0; b<nclass; b++)
{
fscanf (fptr, "%f", &v);
class_layer_weight->SetData(a, b, v);
}
fscanf (fptr, "\n");
}
}
fscanf (fptr, "hidden layer ac\n");
for (a=0; a<layersizes[1]; a++)
{
fscanf (fptr, "%f", &v);
for (b=0; b<minibatch; b++)
neu0_ac_hist->SetData(a, b, v);
}
fscanf (fptr, "\n");
fscanf (fptr, "%d", &a);
if (a != 9999999)
{
printf ("ERROR: failed to read the check number(%d) when reading model\n",9999999);// CHECKNUM);
exit (0);
}
// if (debug > 1)
{
printf ("Successfully loaded model: %s\n", modelname.c_str());
}
fclose (fptr);
}
void Rnn::allocMem()
{
hidtohid_weight.resize(1);
hidtohid_weight[0] = new Matrix(layersizes[1], layersizes[1]);
layers.resize(num_layer);
for(int i=0;i<num_layer;++i)
{
layers[i] = new Matrix(layersizes[i],layersizes[i+1]);
}
if(nclass > 0)
{
class_layer_weight = new Matrix(layersizes[num_layer-1], nclass);
}
neu0_ac_hist = new Matrix(layersizes[1],1);
}
//only calculate word output layer.
float Rnn::forword(int curword,float *hidden,float hiddim,
float *class_out,int class_dim,float *output, int outdim)
{
memset(output,0x00,sizeof(float)*outdim);
int nrow = layersizes[num_layer-1];
//int ncol = layersizes[num_layer];
int clsid = word2class[curword];
int swordid = classinfo[clsid*3];
int nword = classinfo[clsid*3+2];
float *wgt = layers[num_layer-1]->GetDataP();
matrixXvector(hidden,wgt+swordid*nrow,output+swordid, nrow, nword);
SoftMax(output+swordid,nword);
if(nclass > 0)
{
int clsid = word2class[curword];
return output[curword] * class_out[clsid];
}
else
{
return output[curword];
}
}
//iodim: iput and oput dim ,it's word list length.
//iput,oput,hidden_out:external application for memory.
float Rnn::forword (int prevword, int curword,float *iput,float *oput,int iodim,
float *hid_in,int hid_dim,float *class_out,int class_dim)
{
int a, b;
//int c;
int nrow, ncol;
//float v, norm, maxv;
nrow = layersizes[1];
ncol = layersizes[1];
float *wgt;
//iodim == layersizes[0]
//hidden_out == layersizes[1]
//class_dim == nclass
memset(iput,0x00,sizeof(float)*iodim);
memset(oput,0x00,sizeof(float)*iodim);
memset(class_out,0x00,sizeof(float)*class_dim);
// neu0 -> neu1
for (a=0; a<layers.size(); a++)
{
if (a==0)//calculate feature * weight,first layer
{
memcpy(iput,hid_in ,hid_dim*sizeof(float));
wgt = hidtohid_weight[0]->GetDataP();
// oput = neu_ac[1]->gethostdataptr();
nrow = layersizes[1];
ncol = layersizes[1];
memset(oput, 0, sizeof(float)*ncol);
for(b=0;b<ncol;++b)
{
oput[b] = layers[0]->GetData(prevword,b);
}
}
else//last layer
{
if(a==1)
memcpy(hid_in,oput,hid_dim*sizeof(float));
float *tmp=NULL;
tmp = iput;
iput = oput;
oput = tmp;
nrow = layersizes[a];
ncol = layersizes[a+1];
memset(oput, 0, sizeof(float)*ncol);
wgt = layers[a]->GetDataP();
}
if (a+1==num_layer)
{
if(lognormconst < 0)
{
if (nclass > 0)
{
int ncol_cls = nclass;
float *cls_w = class_layer_weight->GetDataP();
matrixXvector(iput,cls_w,
class_out,nrow, ncol_cls);
//for(int i=0;i<ncol_cls;++i)
SoftMax(class_out,ncol_cls);
int clsid = word2class[curword];
int swordid = classinfo[clsid*3];
//int ewordid = classinfo[clsid*3+1];
int nword = classinfo[clsid*3+2];
matrixXvector(iput, wgt+swordid*nrow, oput+swordid, nrow, nword);
SoftMax(oput+swordid,nword);
}
else
{
matrixXvector(iput,wgt,oput,nrow, ncol);
SoftMax(oput,ncol);
}
}
else
{
float v = 0;
for (int i=0; i<nrow; i++)
{
v += iput[i]*layers[a]->GetData(i,curword);
}
oput[curword] = exp(v-lognormconst);
}
}
else
{
matrixXvector (iput, wgt, oput, nrow, ncol);
for(int i=0;i<ncol;++i)
oput[i]=SigMoid(oput[i]);
}
}
if(nclass > 0)
{
int clsid = word2class[curword];
return oput[curword] * class_out[clsid];
}
else
{
return oput[curword];
}
}
float Rnn::SigMoid(float A)
{
return 1/(1+exp(-A));
}
void Rnn::SoftMax(float *A,int dim)
{
int a, maxi;
float v, norm, maxv = 1e-8;
maxv = 1e-10;
for (a=0; a<dim; a++)
{
v = A[a];
if(v > maxv)
{
maxv = v;
maxi = a;
}
}
norm = 0;
for (a=0; a<dim; a++)
{
v = A[a] - maxv;
A[a] = exp(v);
norm += A[a];
}
for (a=0; a<dim; a++)
{
v = A[a] / norm;
A[a] = v;
}
}
void Rnn::matrixXvector(float *src, float *wgt, float *dst, int nr, int nc)
{
#ifndef CBLAS
int i,j;
for (i=0; i<nc; i++)
{
for (j=0; j<nr; j++)
{
dst[i] += wgt[j+i*nr]*src[j];
}
}
#else
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,
1,nc,nr,1.0,(float const *)src,nr,(float const *)wgt,nr,1.0,dst,nc);
#endif
return ;
}
void Rnn::ReadWordlist(string inputlist, string outputlist)
{
int i;
//int a, b;
//float v;
char word[1024];
FILE *finlst, *foutlst;
finlst = fopen (inputlist.c_str(), "r");
foutlst = fopen (outputlist.c_str(), "r");
if (finlst == NULL || foutlst == NULL)
{
printf ("ERROR: Failed to open input (%s) or output list file(%s)\n", inputlist.c_str(), outputlist.c_str());
exit (0);
}
inputmap.insert(make_pair(string("<s>"), 0));
outputmap.insert(make_pair(string("</s>"), 0));
inputvec.clear();
outputvec.clear();
inputvec.push_back("<s>");
outputvec.push_back("</s>");
int index = 1;
while (!feof(finlst))
{
if(fscanf (finlst, "%d%s", &i, word) == 2)
{
if (inputmap.find(word) == inputmap.end())
{
// printf("%d %s\n",i,word);
inputmap[word] = index;
inputvec.push_back(word);
index ++;
}
}
}
if (inputmap.find("<OOS>") == inputmap.end())
{
inputmap.insert(make_pair(string("<OOS>"), index));
inputvec.push_back("<OOS>");
}
else
{
assert (inputmap["<OOS>"] == inputvec.size()-1);
}
index = 1;
// allocate memory for class information
if (nclass > 0)
{
word2class = new int[layersizes[num_layer]];
classinfo = new int[nclass*3];
classinfo[0] = 0;
}
int clsid, prevclsid = 0;
while (!feof(foutlst))
{
if (nclass > 0)
{
if (fscanf(foutlst, "%d%s%d", &i, word, &clsid) == 3)
{
// printf("%d %s\n",i,word);
if (outputmap.find(word) == outputmap.end())
{
outputmap[word] = index;
outputvec.push_back(word);
index ++;
}
int idx = outputmap[word];
word2class[idx] = clsid;
if (clsid != prevclsid)
{
classinfo[prevclsid*3+1] = idx-1;
classinfo[prevclsid*3+2] = idx-classinfo[prevclsid*3];
classinfo[3*clsid]=idx;
}
prevclsid = clsid;
}
}
else
{
if (fscanf(foutlst, "%d%s", &i, word) == 2)
{
if (outputmap.find(word) == outputmap.end())
{
outputmap[word] = index;
outputvec.push_back(word);
index ++;
}
}
}
}
if (nclass > 0)
{
classinfo[prevclsid*3+1] = layersizes[num_layer]-1;
classinfo[prevclsid*3+2] = layersizes[num_layer]-classinfo[prevclsid*3];
}
if (outputmap.find("<OOS>") == outputmap.end())
{
outputmap.insert(make_pair(string("<OOS>"), index));
outputvec.push_back("<OOS>");
}
else
{
assert (outputmap["<OOS>"] == outputvec.size()-1);
}
fprintf(stderr,"inputvec %ld layersizes[0] %d\n", inputvec.size(), layersizes[0]);
assert (inputvec.size() == layersizes[0]);
assert (outputvec.size() == layersizes[num_layer]);
inStartindex = 0;
outEndindex = 0;
inOOSindex = inputvec.size() - 1;
outOOSindex = outputvec.size() - 1;
assert (outOOSindex == outputmap["<OOS>"]);
assert (inOOSindex == inputmap["<OOS>"]);
fclose (finlst);
fclose (foutlst);
}
| [
"hubo@1057277483@qq.com"
] | hubo@1057277483@qq.com |
9ebfe0b30acf0a05a4de133c45ce19f2f0b88a20 | 6768858dfdb0aec72ff95ed78e32760bc7198347 | /Sorting Algorithm/Algorithm_assignment/main.cpp | 1451dafed9fa112b7af3d8d6d421395df19e95f6 | [] | no_license | dhk1349/Algorithm | fe58f8d6bd48e02f30005f0ff440af7888a04424 | a9d547fa16eedf1338d049700688f3545b5b8686 | refs/heads/master | 2021-12-30T16:48:10.813904 | 2021-12-27T16:57:09 | 2021-12-27T16:57:09 | 194,836,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 509 | cpp | #include<iostream>
#include<fstream>
#include <string>
#include <ctime>
#include "Sorting_algorithm.h"
using namespace std;
int main() {
int testarr[15000];
int result=get_arr("test_array.csv",testarr,15000);
//ERROR
if (result == -1) {
cerr << "\tFailed to load array file!\n";
return -1;
}
//
clock_t begin = clock();
Bubble(testarr,15000);
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << elapsed_secs << "seconds"<<endl;
return 1;
}
| [
"dhk1349@naver.com"
] | dhk1349@naver.com |
6aa3b8afde4d7bb2ba2cb3e5ed63fe53a78044f6 | c7f254879ddbc7e14120c6ae7afa8f104fe44e57 | /NanoguiModule/nanogui/label.h | 40f652f2bad2cb30acba3e49fddaef660117f19f | [] | no_license | Hurleyworks/NanoguiBlock | 6926bb57dae837a9f6ef782dbfbd572c0cd75be8 | b3dd7edfa8c1c865b70bf68daebf041259dc4578 | refs/heads/master | 2021-01-10T17:55:46.177295 | 2016-11-08T20:16:25 | 2016-11-08T20:16:25 | 45,840,075 | 11 | 13 | null | 2020-04-18T03:48:05 | 2015-11-09T13:38:21 | C++ | UTF-8 | C++ | false | false | 1,827 | h | /*
nanogui/label.h -- Text label with an arbitrary font, color, and size
NanoGUI was developed by Wenzel Jakob <wenzel@inf.ethz.ch>.
The widget drawing code is based on the NanoVG demo application
by Mikko Mononen.
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE.txt file.
*/
#pragma once
NAMESPACE_BEGIN (nanogui)
/**
\brief Text label widget
The font and color can be customized. When \ref Widget::setFixedWidth()
is used, the text is wrapped when it surpasses the specified width
*/
class Label : public Widget
{
public:
Label (Widget * parent, const std::string & caption,
const std::string & font = "sans", int fontSize = -1);
/// Get the label's text caption
const std::string & caption() const
{
return mCaption;
}
/// Set the label's text caption
void setCaption (const std::string & caption)
{
mCaption = caption;
}
/// Set the currently active font (2 are available by default: 'sans' and 'sans-bold')
void setFont (const std::string & font)
{
mFont = font;
}
/// Get the currently active font
const std::string & font() const
{
return mFont;
}
/// Get the label color
Colour color() const
{
return mColor;
}
/// Set the label color
void setColor (Colour color)
{
mColor = color;
}
/// Compute the size needed to fully display the label
virtual ivec2 preferredSize (NVGcontext * ctx) const;
/// Draw the label
virtual void draw (NVGcontext * ctx);
protected:
std::string mCaption;
std::string mFont;
Colour mColor;
};
NAMESPACE_END (nanogui)
| [
"github@hurleyworks.com"
] | github@hurleyworks.com |
6da92fb60696181195412c98b4f98a06af53716c | d928143913c7b298b7bc637c2dcfa2ae617229e7 | /src/System/SilentSoundSystem/SilentSoundBuffer.cpp | c6af19b974cb0439f59decd8e5c424ee2673b943 | [] | no_license | hackerlank/Mengine | d7e649c29ab6cfd861bd85c75e514939ba7a09d6 | 108491a9ef86946fc4abed0662b0beafbde4fda4 | refs/heads/master | 2021-01-12T06:19:27.136456 | 2016-12-13T00:55:25 | 2016-12-13T00:55:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,284 | cpp | # include "SilentSoundBuffer.h"
# include "Interface/SoundCodecInterface.h"
# include <time.h>
namespace Menge
{
//////////////////////////////////////////////////////////////////////////
static float s_getTimeMs()
{
clock_t cl = clock();
float sec = (float)(cl) / float(CLOCKS_PER_SEC);
return sec;
}
//////////////////////////////////////////////////////////////////////////
SilentSoundBuffer::SilentSoundBuffer()
: m_playTime(0.f)
, m_pauseTime(0.f)
, m_frequency(0)
, m_channels(0)
, m_length(0.f)
, m_isStereo(false)
{
}
//////////////////////////////////////////////////////////////////////////
SilentSoundBuffer::~SilentSoundBuffer()
{
}
//////////////////////////////////////////////////////////////////////////
bool SilentSoundBuffer::update()
{
return false;
}
//////////////////////////////////////////////////////////////////////////
const SoundDecoderInterfacePtr & SilentSoundBuffer::getDecoder() const
{
return m_soundDecoder;
}
//////////////////////////////////////////////////////////////////////////
bool SilentSoundBuffer::load( const SoundDecoderInterfacePtr & _soundDecoder )
{
m_soundDecoder = _soundDecoder;
const SoundCodecDataInfo* dataInfo = m_soundDecoder->getCodecDataInfo();
m_frequency = dataInfo->frequency;
m_channels = dataInfo->channels;
m_length = dataInfo->length;
//size_t size = dataInfo->size;
if( m_channels == 1 )
{
m_isStereo = false;
}
else
{
m_isStereo = true;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void SilentSoundBuffer::play( uint32_t _id, bool _looped, float _pos )
{
(void)_id;
(void)_looped;
(void)_pos;
float sec = s_getTimeMs();
m_playTime = sec;
m_pauseTime = 0.f;
}
//////////////////////////////////////////////////////////////////////////
bool SilentSoundBuffer::resume( uint32_t _id )
{
(void)_id;
float sec = s_getTimeMs();
float deltha = m_pauseTime - m_playTime;
m_playTime = sec - deltha;
m_pauseTime = 0.f;
return true;
}
//////////////////////////////////////////////////////////////////////////
void SilentSoundBuffer::pause( uint32_t _id )
{
(void)_id;
float sec = s_getTimeMs();
m_pauseTime = sec;
}
//////////////////////////////////////////////////////////////////////////
void SilentSoundBuffer::stop( uint32_t _id )
{
(void)_id;
m_playTime = 0.f;
m_pauseTime = 0.f;
}
//////////////////////////////////////////////////////////////////////////
float SilentSoundBuffer::getTimePos( uint32_t _id ) const
{
(void)_id;
if( m_pauseTime > m_playTime )
{
return m_pauseTime;
}
float sec = s_getTimeMs();
return sec - m_playTime;
}
//////////////////////////////////////////////////////////////////////////
float SilentSoundBuffer::getTimeTotal() const
{
return m_length;
}
//////////////////////////////////////////////////////////////////////////
} // namespace Menge
| [
"yuriy_levchenko@202150c4-1a32-4ab8-af31-e3358ecdd631"
] | yuriy_levchenko@202150c4-1a32-4ab8-af31-e3358ecdd631 |
e7b0716dd88c67d53c548157167a627d939366d7 | 0c1f5efe63ded94e7c5d3f3eec7ffa17e7e2ccd8 | /Smart_House.ino | 1dac4aae9dd7fca0dd1286dc40b29e5400ddfff5 | [] | no_license | nancy9taya/Smart_House | 404fb66c484b0715e13ffd5cc8e6d98e11d4af0c | 94310aa6d4e12f3327955ed23c4240f9f2a24243 | refs/heads/master | 2022-05-12T14:46:24.891455 | 2020-04-28T02:53:42 | 2020-04-28T02:53:42 | 259,439,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,855 | ino | #include<Keypad.h>
#include<LiquidCrystal.h>
LiquidCrystal lcd(A1,A2,3,2,1,A3);
const byte ROWS = 4;
const byte COLS = 4;
char KeyMap[ROWS][COLS] = {
{'7', '8', '9', '*'},
{'4', '5', '6', '/'},
{'1', '2', '3', '-'},
{'#', '0', '=', '+'}
};
byte rowPins[ROWS] = {11, 10, 9, 8};
byte colPins[COLS] = {7,6, 5, 4};
Keypad customKeypad = Keypad(makeKeymap(KeyMap), rowPins, colPins, ROWS, COLS);
int controller = 13;
int House = 12;
int Fan = 0;
volatile int buttonState;
int input;
char password[4]={'9','2','4','8'};
boolean flag = 1;
float temp_old, temp_new;
int x=0;
int password_enterd =0;
void setup() {
lcd.begin(16,2);
pinMode(controller, INPUT);
pinMode(House, OUTPUT);
pinMode(Fan, OUTPUT);
lcd.print(" password");
attachInterrupt(1, pin_input, CHANGE);
}
void loop() {
flag=1;
//wait for owner to enter the password to enter house
if( password_enterd == 0){
for(int i = 0 ;i <sizeof(password) ;i++){
char key = customKeypad.waitForKey();
//lcd.clear();
lcd.setCursor(i,1);
lcd.print("#");
// lcd.scroll()
if(key != password[i]){
flag = 0;
}
}
}
if(flag){
x=1;
password_enterd =1;
}
temp_old = analogRead(A0);
temp_new = temp_old * 0.489;
// input = digitalRead(controller);
if(flag ){
//digitalWrite(House, HIGH);
if(temp_new >= 25){
digitalWrite(Fan, HIGH);
}
else{
digitalWrite(Fan, LOW);
}
lcd.clear();
lcd.setCursor(1,0);
lcd.print("temp is");
lcd.setCursor(0,1);
lcd.print(temp_new);
delay(1000);
}
else if(flag == 0){
lcd.clear();
lcd.setCursor(1,0);
lcd.print("wrong");
}
}
void pin_input() {
buttonState = digitalRead(controller);
if(x ==1){
if(buttonState == 0 ){
digitalWrite(House, LOW);
}
else{
digitalWrite(House, HIGH);
}
}
}
| [
"nancy.hassan1998@gmail.com"
] | nancy.hassan1998@gmail.com |
0ce1705be0ac31f1e99b5a49599c1200ff88361a | 17f2dd4fde9cbcd9b3b0cd101fc740d3495bbe80 | /165 - 红黑树/RedBlackTree.hpp | 3fb9d65f73f1e5745b5d1f036505554ddece371c | [
"Apache-2.0"
] | permissive | NekoSilverFox/CPP | 0a7f48b50ee1769bb5ba318fb6fb6c6c342e5544 | c6797264fceda4a65ac3452acca496e468d1365a | refs/heads/master | 2021-11-11T17:48:48.514822 | 2021-11-01T20:30:31 | 2021-11-01T20:30:31 | 230,780,197 | 11 | 7 | null | 2021-04-11T22:24:56 | 2019-12-29T17:12:19 | C++ | GB18030 | C++ | false | false | 8,178 | hpp | #pragma once
#include "MyErrorInfo.h"
#include <iostream>
#define red true
#define black false
class RedBlackTree
{
private:
struct Node
{
Node() : key_(0), colour_(red), p_(nullptr), left_(nullptr), right_(nullptr) {}
Node(int key) : key_(key), colour_(red), p_(nullptr), left_(nullptr), right_(nullptr) {}
int key_;
bool colour_; // red - true; black - false;
Node* p_;
Node* left_;
Node* right_;
};
Node* root_;
public:
RedBlackTree()
{
root_ = new Node;
root_->key_ = -1;
root_->colour_ = red;
root_->p_ = nullptr;
root_->left_ = nullptr;
root_->right_ = nullptr;
}
void insert(int key_insert)
{
/*
* bool init 为标识符,判断是否为第一个插入的节点,如果是,直接将 root_结点更新为 key_insert
*/
static bool init = false;
if (false == init)
{
init = true;
root_->key_ = key_insert;
root_->colour_ = black;
}
else
{
Node* node_insert = new Node;
node_insert->key_ = key_insert;
insertNode(root_, node_insert);
}
}
void foreach()
{
foreachRBTree(root_);
}
private:
void insertNode(Node* root, Node* node_insert)
{
if (nullptr == root) throw MyErrorInfo("nullptr_in_insertNode");
if (node_insert->key_ > root->key_)
{
if (nullptr != root->right_) { insertNode(root->right_, node_insert); }
else
{
root->right_ = node_insert;
node_insert->p_ = root;
judgmentAdjustmentCondition(node_insert);
}
}
else if (node_insert->key_ < root->key_)
{
if (nullptr != root->left_) { insertNode(root->left_, node_insert); }
else
{
root->left_ = node_insert;
node_insert->p_ = root;
judgmentAdjustmentCondition(node_insert);
}
}
else
{
return;
}
}
void foreachRBTree(Node* root)
{
if (nullptr == root) return;
foreachRBTree(root->left_);
std::cout << root->key_ << " ";
foreachRBTree(root->right_);
}
int judgmentAdjustmentCondition(Node* node)
{
if (nullptr == node) throw MyErrorInfo("nullptr_node_judgmentAdjustmentCondition");
if (nullptr == node->p_) return 0;
if (black == node->p_->colour_)
{
cout << "\033[31m (2) \033[0m";
return 2;
}
else if (red == node->p_->colour_)
{
// 叔叔结点存在,且为红结点
if (
node->p_ == node->p_->p_->left_ &&
nullptr != node->p_->p_->right_ &&
red == node->p_->p_->right_->colour_
)
{
adjustRedBlackTree_411(node);
cout << "\033[31m (411) \033[0m";
return 411;
}
// 叔叔结点存在,且为红结点
else if
(
node->p_ == node->p_->p_->right_ &&
nullptr != node->p_->p_->left_ &&
red == node->p_->p_->left_->colour_
)
{
adjustRedBlackTree_412(node);
cout << "\033[31m (412) \033[0m";
return 412;
}
else if
(
(node->p_ == node->p_->p_->left_) &&
(
nullptr == node->p_->p_->right_ ||
black == node->p_->p_->right_->colour_
)
)
{
if (node == node->p_->left_)
{
adjustRedBlackTree_421(node);
cout << "\033[31m (421) \033[0m";
return 421;
}
if (node == node->p_->right_)
{
adjustRedBlackTree_422(node);
cout << "\033[31m (422) \033[0m";
return 422;
}
}
else if
(
(node->p_ == node->p_->p_->right_) &&
(
nullptr == node->p_->p_->left_ ||
black == node->p_->p_->left_->colour_
)
)
{
if (node == node->p_->left_)
{
adjustRedBlackTree_431(node);
cout << "\033[31m (431) \033[0m";
return 431;
}
else if (node == node->p_->right_)
{
adjustRedBlackTree_432(node);
cout << "\033[31m (432) \033[0m";
return 432;
}
}
}
else
{
return 0;
}
}
// 叔叔结点存在,且为红结点
void adjustRedBlackTree_411(Node* node)
{
if (nullptr == node) throw MyErrorInfo("nullptr_node_in_411");
// 把父节点和叔叔结点设为black
node->p_->colour_ = black;
node->p_->p_->right_->colour_ = black;
// 把爷爷设为 red
node->p_->p_->colour_ = red;
judgmentAdjustmentCondition(node->p_->p_);
#if 0
// 将 pp 设为待插入的结点,如果 pp 的父节点为红,需要继续做自平衡处理
if (red == node->p_->p_->p_->colour_)
{
Node* tempNode = node->p_->p_;
adjustRedBlackTree_411(tempNode);
}
#endif
}
// 叔叔结点存在,且为红结点
void adjustRedBlackTree_412(Node* node)
{
if (nullptr == node) throw MyErrorInfo("nullptr_node_in_412");
// 把父节点和叔叔结点设为black
node->p_->colour_ = black;
node->p_->p_->right_->colour_ = black;
// 把爷爷设为 red
node->p_->p_->colour_ = red;
judgmentAdjustmentCondition(node->p_->p_);
#if 0
// 将 pp 设为待插入的结点,如果 pp 的父节点为红,需要继续做自平衡处理
if (red == node->p_->p_->p_->colour_)
{
Node* tempNode = node->p_->p_;
adjustRedBlackTree_411(tempNode);
}
#endif
}
// 叔叔结点不存在,或者为黑结点,并且插入的结点是父节点 是 祖父结点的左节点
// 插入节点是其父节点的左节点
void adjustRedBlackTree_421(Node* node)
{
if (nullptr == node) throw MyErrorInfo("nullptr_node_in_421");
node->p_->colour_ = black;
node->p_->p_->colour_ = red;
// 对pp进行右旋
// 缓存一下 pp
Node* temp_pp = node->p_->p_;
if (nullptr != temp_pp->p_)
{
if (temp_pp->p_->left_ == temp_pp)
{
temp_pp->p_->left_ = node->p_;
}
else if (temp_pp->p_->right_ == temp_pp)
{
temp_pp->p_->right_ = node->p_;
}
node->p_->right_ = temp_pp;
temp_pp->left_ = nullptr;
temp_pp->p_ = node->p_;
}
else
{
root_ = node->p_;
root_->p_ = nullptr;
root_->left_ = node;
node->p_ = root_;
root_->right_ = temp_pp;
temp_pp->left_ = nullptr;
temp_pp->p_ = root_;
//node->p_->p_ = node->p_;
//node->p_->p_ = nullptr;
//node->p_->right_ = temp_pp;
//temp_pp->p_ = node->p_;
//temp_pp->left_ = nullptr;
}
}
// 叔叔结点不存在,或者为黑结点,并且插入的结点是父节点 是 祖父结点的左节点
// 插入节点是其父节点的右节点
void adjustRedBlackTree_422(Node* node)
{
if (nullptr == node) throw MyErrorInfo("nullptr_node_in_422");
// 对p进行左旋
// 缓存一下 p
Node* temp_p = node->p_;
//if (temp_p->p_->left_ == temp_p->p_)
//{
// temp_p->p_->left_ = node;
//}
//else if (temp_p->p_->right_ == temp_p->p_)
//{
// temp_p->p_->right_ == node;
//}
node->p_->p_->left_ = node;
node->p_ = temp_p->p_;
node->right_ = temp_p;
temp_p->p_ = node;
temp_p->right_ = nullptr;
// 把 p 设置为插入节点,得到情景 4.2.1
// 进行 4.2.1 的处理
adjustRedBlackTree_421(temp_p);
}
// 叔叔结点不存在或为黑结点,并且插入的结点的父节点是祖父节点的右节点
// 插入节点是父节点的右节点
void adjustRedBlackTree_431(Node* node)
{
if (nullptr == node) throw MyErrorInfo("nullptr_node_in_431");
// 将 p 设为黑色
node->p_->colour_ = black;
// 将 pp 设为红色
node->p_->p_->colour_ = red;
// 将 pp 进行左旋
Node* temp_pp = node->p_->p_;
if (nullptr != temp_pp->p_)
{
if (temp_pp->p_->left_ == temp_pp)
{
temp_pp->p_->left_ = node->p_;
}
else if (temp_pp->p_->right_ == temp_pp)
{
temp_pp->p_->right_ = node->p_;
}
node->p_ = temp_pp->p_;
node->left_ = temp_pp;
temp_pp->p_ = node->p_;
temp_pp->right_ = nullptr;
}
else
{
root_ = node->p_;
root_->p_ = nullptr;
root_->left_ = temp_pp;
temp_pp->p_ = root_;
temp_pp->right_ = nullptr;
//node->p_ = temp_pp->p_;
//node->p_->left_ = temp_pp;
//temp_pp->p_ = node->p_;
//temp_pp->right_ = nullptr;
}
}
void adjustRedBlackTree_432(Node* node)
{
if (nullptr == node) throw MyErrorInfo("nullptr_node_in_432");
Node* temp_p = node->p_;
node->p_->p_->right_ = node;
node->right_ = temp_p;
node->p_ = temp_p->p_;
temp_p->p_ = node;
temp_p->left_ = nullptr;
//temp_p->p_->right_ = node;
//node->p_ = temp_p->p_;
//node->right_ = temp_p;
//temp_p->left_ = nullptr;
adjustRedBlackTree_431(temp_p);
}
};
| [
"weidufox@gmail.com"
] | weidufox@gmail.com |
5951799d160e1ed2d6c5c324d7663fce377040b0 | b0f2009e1c70d729574295697cc0d5d1dd465e97 | /labo/2015-2016/04/02.ino | d9ed29a9b2b76b3552d82d14bf9bc471a3109e43 | [] | no_license | oberonlievens/computertechnologie-3 | 36a60c54abdaefc8e29466299e9c41ac9c81ef3b | 1ef8502574def922039d5d261ac46440f753ea56 | refs/heads/master | 2022-04-02T19:07:56.006781 | 2020-01-30T09:06:09 | 2020-01-30T09:06:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | ino | #include <TimerOne.h>
int minute = 0;
int second = 0;
void setup() {
Timer1.initialize(1000000);
Timer1.attachInterrupt(timerIsr);
Serial.begin(9600);
}
void loop() {
minute < 10 ? Serial.print("0"):false;
Serial.print(minute);
Serial.print(":");
second < 10 ? Serial.print("0"):false;
Serial.println(second);
delay(1000);
}
void timerIsr() {
second++;
if (second == 60 ) {
second = 0;
minute++;
}
} | [
"hello@haroen.me"
] | hello@haroen.me |
d7877543ead429ced221511f784b137a8d1503f3 | dbaa90195352be895c97e92d1391d3df1314b1b8 | /xTen/src/graphics/mesh.cpp | 51332139d4bcfe56d999fb5f0851f52e0afef27d | [] | no_license | paubertin/xTen_old | 08610a81a3d43f73b9162090400eb9c531461aa3 | 9412b611ae9a8867a8b9b4d9907e99e064a63a97 | refs/heads/master | 2021-06-01T10:13:53.441813 | 2016-07-06T23:41:16 | 2016-07-06T23:41:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,424 | cpp | #include "mesh.h"
#include "../utils/utils.h"
#include "../maths/xmaths.h"
#include "texturemanager.h"
namespace xten { namespace xgraphics {
Mesh::MeshEntry::MeshEntry() :
m_VAO(NULL), m_VBO(NULL), m_IBO(NULL), numIndices(NULL), materialIndex(NULL)
{
}
Mesh::MeshEntry::~MeshEntry()
{
GLCall( glDeleteBuffers(1, &m_VBO) );
GLCall( glDeleteBuffers(1, &m_IBO) );
}
void Mesh::MeshEntry::init(const std::vector<Vertex>& vertices, const std::vector<GLuint>& indices)
{
numIndices = indices.size();
GLCall( glGenVertexArrays(1, &m_VAO) );
GLCall( glGenBuffers(1, &m_VBO) );
GLCall( glGenBuffers(1, &m_IBO) );
GLCall( glBindVertexArray(m_VAO) );
GLCall( glBindBuffer(GL_ARRAY_BUFFER, m_VBO) );
GLCall( glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * vertices.size(), &vertices[0], GL_STATIC_DRAW) );
GLCall( glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO) );
GLCall( glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * numIndices, &indices[0], GL_STATIC_DRAW) );
//positions
GLCall( glEnableVertexAttribArray(0) );
GLCall( glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(0)) );
//texcoord
GLCall( glEnableVertexAttribArray(1) );
GLCall( glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(offsetof(Vertex, Vertex::uv))) );
//normal
GLCall( glEnableVertexAttribArray(2) );
GLCall( glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)(offsetof(Vertex, Vertex::normal))) );
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//glBindBuffer(GL_ARRAY_BUFFER, 0);
GLCall( glBindVertexArray(0) );
}
Mesh::Mesh()
{}
Mesh::~Mesh()
{
clear();
}
void Mesh::clear()
{
for (GLuint i = 0; i < m_Textures.size(); ++i)
{
// XDEL(m_Textures[i]);
}
}
GLboolean Mesh::loadMesh(const std::string & filename)
{
clear();
GLboolean res = GL_FALSE;
Assimp::Importer import;
const aiScene* scene = import.ReadFile(filename.c_str(),
aiProcess_FlipUVs |
aiProcess_GenSmoothNormals |
aiProcess_Triangulate);
if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
std::string err = "[ASSIMP]. Could not load file: " + filename + "\n" + import.GetErrorString();
XTEN_ERROR(err);
return res;
}
else
{
res = initFromScene(scene, filename);
}
return res;
}
void Mesh::render()
{
for (GLuint i = 0; i < m_Entries.size(); i++)
{
const GLuint MaterialIndex = m_Entries[i].materialIndex;
if (MaterialIndex < m_Textures.size() && m_Textures[MaterialIndex])
{
m_Textures[MaterialIndex]->bind(GL_TEXTURE0);
}
GLCall( glBindVertexArray(m_Entries[i].m_VAO) );
GLCall( glDrawElements(GL_TRIANGLES, m_Entries[i].numIndices, GL_UNSIGNED_INT, NULL) );
GLCall( glBindVertexArray(0) );
}
}
GLboolean Mesh::initFromScene(const aiScene* scene, const std::string & filename)
{
m_Entries.resize(scene->mNumMeshes);
m_Textures.resize(scene->mNumMaterials);
for (GLuint i = 0; i < m_Entries.size(); ++i)
{
const aiMesh* aimesh = scene->mMeshes[i];
initMesh(i, aimesh);
}
return initMaterials(scene, filename);
}
void Mesh::initMesh(GLuint index, const aiMesh* aimesh)
{
using namespace xmaths;
std::vector<Vertex> vertices;
std::vector<GLuint> indices;
for (GLuint i = 0; i < aimesh->mNumVertices; i++)
{
vec3 position(aimesh->mVertices[i].x, aimesh->mVertices[i].y, aimesh->mVertices[i].z);
vec3 normal(aimesh->mNormals[i].x, aimesh->mNormals[i].y, aimesh->mNormals[i].z);
vec2 texcoord = aimesh->HasTextureCoords(0) ? vec2(aimesh->mTextureCoords[0][i].x, aimesh->mTextureCoords[0][i].y) : vec2(0.f);
vertices.push_back(Vertex(vec3(aimesh->mVertices[i].x, aimesh->mVertices[i].y, aimesh->mVertices[i].z),
aimesh->HasTextureCoords(0) ? vec2(aimesh->mTextureCoords[0][i].x, aimesh->mTextureCoords[0][i].y) : vec2(0.f),
vec3(aimesh->mNormals[i].x, aimesh->mNormals[i].y, aimesh->mNormals[i].z)));
}
for (GLuint i = 0; i < aimesh->mNumFaces; i++)
{
const aiFace& face = aimesh->mFaces[i];
XASSERT(face.mNumIndices == 3);
indices.push_back(face.mIndices[0]);
indices.push_back(face.mIndices[1]);
indices.push_back(face.mIndices[2]);
}
m_Entries[index].materialIndex = aimesh->mMaterialIndex;
m_Entries[index].init(vertices, indices);
}
GLboolean Mesh::initMaterials(const aiScene* scene, const std::string & filename)
{
// Extract the directory part from the file name
std::string::size_type SlashIndex = filename.find_last_of("/");
std::string Dir;
if (SlashIndex == std::string::npos) {
Dir = ".";
}
else if (SlashIndex == 0) {
Dir = "/";
}
else {
Dir = filename.substr(0, SlashIndex);
}
GLboolean res = GL_TRUE;
for (GLuint i = 0; i < scene->mNumMaterials; i++)
{
const aiMaterial * mat = scene->mMaterials[i];
m_Textures[i] = nullptr;
if (mat->GetTextureCount(aiTextureType_DIFFUSE) > 0)
{
aiString path;
if (mat->GetTexture(aiTextureType_DIFFUSE, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS)
{
std::string fullpath = Dir + "/" + path.data;
m_Textures[i] = TexManager::add(GL_TEXTURE_2D, path.data, fullpath, GL_TRUE);
}
}
if (!m_Textures[i])
{
m_Textures[i] = TexManager::get("default_white");
}
if (!m_Textures[i])
{
res = GL_FALSE;
}
}
return res;
}
} } | [
"paubertin@gmail.com"
] | paubertin@gmail.com |
944ccb4ba5c429aac8884b42b275dee4bd9baa0a | 8dcf1479ce569ffad7b607dd3d43115e3c8ebc41 | /DaQinBot/Source/MapTools.cpp | 8b317b04f602bd2e7006826417b349833978807b | [] | no_license | liongis/DaQin | 3d628aa481a4fcaa72582728851341863dece6bb | f851984c34b60da2bfa51baa3355e69153a617d3 | refs/heads/master | 2020-03-30T20:39:39.900596 | 2018-12-12T07:59:15 | 2018-12-12T07:59:15 | 151,597,967 | 8 | 0 | null | null | null | null | GB18030 | C++ | false | false | 25,001 | cpp | #include "MapTools.h"
#include "BuildingPlacer.h"
#include "InformationManager.h"
const double pi = 3.14159265358979323846;
namespace { auto & bwemMap = BWEM::Map::Instance(); }
namespace { auto & bwebMap = BWEB::Map::Instance(); }
using namespace UAlbertaBot;
MapTools & MapTools::Instance()
{
static MapTools instance;
return instance;
}
MapTools::MapTools()
{
// Figure out which tiles are walkable and buildable.
setBWAPIMapData();
_hasIslandBases = false;
for (BWTA::BaseLocation * base : BWTA::getBaseLocations())
{
if (base->isIsland())
{
_hasIslandBases = true;
break;
}
}
// Get all of the BWEM chokepoints
std::set<const BWEM::ChokePoint*> chokes;
for (const auto & area : bwemMap.Areas())
for (const BWEM::ChokePoint * choke : area.ChokePoints())
chokes.insert(choke);
// Store a ChokeData object for each choke
for (const BWEM::ChokePoint * choke : chokes)
{
choke->SetExt(new ChokeData(choke));
ChokeData & chokeData = *((ChokeData*)choke->Ext());
// Compute the choke width
// Because the ends are themselves walkable tiles, we need to add a bit of padding to estimate the actual walkable width of the choke
int width = BWAPI::Position(choke->Pos(choke->end1)).getApproxDistance(BWAPI::Position(choke->Pos(choke->end2))) + 15;
chokeData.width = width;
// Determine if the choke is a ramp
int firstAreaElevation = BWAPI::Broodwar->getGroundHeight(BWAPI::TilePosition(choke->GetAreas().first->Top()));
int secondAreaElevation = BWAPI::Broodwar->getGroundHeight(BWAPI::TilePosition(choke->GetAreas().second->Top()));
if (firstAreaElevation != secondAreaElevation)
{
chokeData.isRamp = true;
// For narrow ramps with a difference in elevation, compute a tile at high elevation close to the choke
// We will use this for pathfinding
if (chokeData.width < 96)
{
// Start by computing the angle of the choke
BWAPI::Position chokeDelta(choke->Pos(choke->end1) - choke->Pos(choke->end2));
double chokeAngle = atan2(chokeDelta.y, chokeDelta.x);
// Now find a tile a bit away from the middle of the choke that is at high elevation
int highestElevation = std::max(firstAreaElevation, secondAreaElevation);
BWAPI::Position center(choke->Center());
BWAPI::TilePosition closestToCenter = BWAPI::TilePositions::Invalid;
for (int step = 0; step <= 6; step++)
for (int direction = -1; direction <= 1; direction += 2)
{
BWAPI::TilePosition tile(BWAPI::Position(
center.x - (int)std::round(16 * step * std::cos(chokeAngle + direction * (pi / 2.0))),
center.y - (int)std::round(16 * step * std::sin(chokeAngle + direction * (pi / 2.0)))));
if (!tile.isValid()) continue;
if (!bwebMap.isWalkable(tile)) continue;
if (BWAPI::Broodwar->getGroundHeight(tile) == highestElevation)
{
chokeData.highElevationTile = tile;
}
}
}
}
}
// On Plasma, we enrich the BWEM chokepoints with data about mineral walking
if (BWAPI::Broodwar->mapHash() == "6f5295624a7e3887470f3f2e14727b1411321a67")
{
// Process each choke
for (const BWEM::ChokePoint * choke : chokes)
{
ChokeData & chokeData = *((ChokeData*)choke->Ext());
BWAPI::Position chokeCenter(choke->Center());
// Determine if the choke is blocked by eggs, and grab the close mineral patches
bool blockedByEggs = false;
BWAPI::Unit closestMineralPatch = nullptr;
BWAPI::Unit secondClosestMineralPatch = nullptr;
int closestMineralPatchDist = INT_MAX;
int secondClosestMineralPatchDist = INT_MAX;
for (const auto staticNeutral : BWAPI::Broodwar->getStaticNeutralUnits())
{
if (!blockedByEggs && staticNeutral->getType() == BWAPI::UnitTypes::Zerg_Egg &&
staticNeutral->getDistance(chokeCenter) < 100)
{
blockedByEggs = true;
}
if (staticNeutral->getType() == BWAPI::UnitTypes::Resource_Mineral_Field &&
staticNeutral->getResources() == 32)
{
int dist = staticNeutral->getDistance(chokeCenter);
if (dist <= closestMineralPatchDist)
{
secondClosestMineralPatchDist = closestMineralPatchDist;
closestMineralPatchDist = dist;
secondClosestMineralPatch = closestMineralPatch;
closestMineralPatch = staticNeutral;
}
else if (dist < secondClosestMineralPatchDist)
{
secondClosestMineralPatchDist = dist;
secondClosestMineralPatch = staticNeutral;
}
}
}
if (!blockedByEggs) continue;
chokeData.requiresMineralWalk = true;
chokeData.firstMineralPatch = closestMineralPatch;
chokeData.secondMineralPatch = secondClosestMineralPatch;
}
}
// TODO testing
//BWAPI::TilePosition homePosition = BWAPI::Broodwar->self()->getStartLocation();
//BWAPI::Broodwar->printf("start position %d,%d", homePosition.x, homePosition.y);
}
// Read the map data from BWAPI and remember which 32x32 build tiles are walkable.
// NOTE The game map is walkable at the resolution of 8x8 walk tiles, so this is an approximation.
// We're asking "Can big units walk here?" Small units may be able to squeeze into more places.
void MapTools::setBWAPIMapData()
{
// 1. Mark all tiles walkable and buildable at first.
_terrainWalkable = std::vector< std::vector<bool> >(BWAPI::Broodwar->mapWidth(), std::vector<bool>(BWAPI::Broodwar->mapHeight(), true));
_walkable = std::vector< std::vector<bool> >(BWAPI::Broodwar->mapWidth(), std::vector<bool>(BWAPI::Broodwar->mapHeight(), true));
_buildable = std::vector< std::vector<bool> >(BWAPI::Broodwar->mapWidth(), std::vector<bool>(BWAPI::Broodwar->mapHeight(), true));
_depotBuildable = std::vector< std::vector<bool> >(BWAPI::Broodwar->mapWidth(), std::vector<bool>(BWAPI::Broodwar->mapHeight(), true));
// 2. Check terrain: Is it buildable? Is it walkable?
// This sets _walkable and _terrainWalkable identically.
for (int x = 0; x < BWAPI::Broodwar->mapWidth(); ++x)
{
for (int y = 0; y < BWAPI::Broodwar->mapHeight(); ++y)
{
// This initializes all cells of _buildable and _depotBuildable.
bool buildable = BWAPI::Broodwar->isBuildable(BWAPI::TilePosition(x, y), false);
_buildable[x][y] = buildable;
_depotBuildable[x][y] = buildable;
bool walkable = true;
// Check each 8x8 walk tile within this 32x32 TilePosition.
int walkableWalkPositions = 0;
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
if (BWAPI::Broodwar->isWalkable(x * 4 + i, y * 4 + j)) walkableWalkPositions++;
}
}
// On Plasma, consider the tile walkable if at least 10 walk positions are walkable
if (walkableWalkPositions < 16 &&
(BWAPI::Broodwar->mapHash() != "6f5295624a7e3887470f3f2e14727b1411321a67" || walkableWalkPositions < 10))
{
_terrainWalkable[x][y] = false;
_walkable[x][y] = false;
}
}
}
// 3. Check neutral units: Do they block walkability?
// This affects _walkable but not _terrainWalkable. We don't update buildability here.
for (const auto unit : BWAPI::Broodwar->getStaticNeutralUnits())
{
// Ignore the eggs on Plasma
if (BWAPI::Broodwar->mapHash() == "6f5295624a7e3887470f3f2e14727b1411321a67" &&
unit->getType() == BWAPI::UnitTypes::Zerg_Egg)
continue;
// The neutral units may include moving critters which do not permanently block tiles.
// Something immobile blocks tiles it occupies until it is destroyed. (Are there exceptions?)
if (!unit->getType().canMove() && !unit->isFlying())
{
BWAPI::TilePosition pos = unit->getTilePosition();
for (int x = pos.x; x < pos.x + unit->getType().tileWidth(); ++x)
{
for (int y = pos.y; y < pos.y + unit->getType().tileHeight(); ++y)
{
if (BWAPI::TilePosition(x, y).isValid()) // assume it may be partly off the edge
{
_walkable[x][y] = false;
}
}
}
}
}
// 4. Check static resources: Do they block buildability?
for (const BWAPI::Unit resource : BWAPI::Broodwar->getStaticNeutralUnits())
{
if (!resource->getType().isResourceContainer())
{
continue;
}
int tileX = resource->getTilePosition().x;
int tileY = resource->getTilePosition().y;
for (int x = tileX; x<tileX + resource->getType().tileWidth(); ++x)
{
for (int y = tileY; y<tileY + resource->getType().tileHeight(); ++y)
{
_buildable[x][y] = false;
// depots can't be built within 3 tiles of any resource
// TODO rewrite this to be less disgusting
for (int dx = -3; dx <= 3; dx++)
{
for (int dy = -3; dy <= 3; dy++)
{
if (!BWAPI::TilePosition(x + dx, y + dy).isValid())
{
continue;
}
_depotBuildable[x + dx][y + dy] = false;
}
}
}
}
}
}
// Ground distance in tiles, -1 if no path exists.
// This is Manhattan distance, not walking distance. Still good for finding paths.
int MapTools::getGroundTileDistance(BWAPI::TilePosition origin, BWAPI::TilePosition destination)
{
// if we have too many maps, reset our stored maps in case we run out of memory
if (_allMaps.size() > allMapsSize)
{
_allMaps.clear();
if (Config::Debug::DrawMapDistances)
{
BWAPI::Broodwar->printf("Cleared distance map cache");
}
}
// Do we have a distance map to the destination?
auto it = _allMaps.find(destination);
if (it != _allMaps.end())
{
return (*it).second.getDistance(origin);
}
// It's symmetrical. A distance map to the origin is just as good.
it = _allMaps.find(origin);
if (it != _allMaps.end())
{
return (*it).second.getDistance(destination);
}
// Make a new map for this destination.
_allMaps.insert(std::pair<BWAPI::TilePosition, DistanceMap>(destination, DistanceMap(destination)));
return _allMaps[destination].getDistance(origin);
}
int MapTools::getGroundTileDistance(BWAPI::Position origin, BWAPI::Position destination)
{
return getGroundTileDistance(BWAPI::TilePosition(origin), BWAPI::TilePosition(destination));
}
// Ground distance in pixels (with TilePosition granularity), -1 if no path exists.
// TilePosition granularity means that the distance is a multiple of 32 pixels.
int MapTools::getGroundDistance(BWAPI::Position origin, BWAPI::Position destination)
{
int tiles = getGroundTileDistance(origin, destination);
if (tiles > 0)
{
return 32 * tiles;
}
return tiles; // 0 or -1
}
const std::vector<BWAPI::TilePosition> & MapTools::getClosestTilesTo(BWAPI::TilePosition pos)
{
// make sure the distance map is calculated with pos as a destination
int a = getGroundTileDistance(pos, pos);
return _allMaps[pos].getSortedTiles();
}
const std::vector<BWAPI::TilePosition> & MapTools::getClosestTilesTo(BWAPI::Position pos)
{
return getClosestTilesTo(BWAPI::TilePosition(pos));
}
bool MapTools::isBuildable(BWAPI::TilePosition tile, BWAPI::UnitType type) const
{
if (!tile.isValid())
{
return false;
}
int startX = tile.x;
int endX = tile.x + type.tileWidth();
int startY = tile.y;
int endY = tile.y + type.tileHeight();
for (int x = startX; x<endX; ++x)
{
for (int y = startY; y<endY; ++y)
{
BWAPI::TilePosition tile(x, y);
if (!tile.isValid() || !isBuildable(tile) || type.isResourceDepot() && !isDepotBuildable(tile))
{
return false;
}
}
}
return true;
}
void MapTools::drawHomeDistanceMap()
{
if (!Config::Debug::DrawMapDistances)
{
return;
}
BWAPI::TilePosition homePosition = BWAPI::Broodwar->self()->getStartLocation();
DistanceMap d(homePosition, false);
for (int x = 0; x < BWAPI::Broodwar->mapWidth(); ++x)
{
for (int y = 0; y < BWAPI::Broodwar->mapHeight(); ++y)
{
int dist = d.getDistance(x, y);
char color = dist == -1 ? orange : white;
BWAPI::Position pos(BWAPI::TilePosition(x, y));
BWAPI::Broodwar->drawTextMap(pos + BWAPI::Position(12, 12), "%c%d", color, dist);
if (homePosition.x == x && homePosition.y == y)
{
BWAPI::Broodwar->drawBoxMap(pos.x, pos.y, pos.x+33, pos.y+33, BWAPI::Colors::Yellow);
}
}
}
}
BWTA::BaseLocation * MapTools::nextExpansion(bool hidden, bool wantMinerals, bool wantGas)
{
UAB_ASSERT(wantMinerals || wantGas, "unwanted expansion");
// Abbreviations.
BWAPI::Player player = BWAPI::Broodwar->self();
BWAPI::Player enemy = BWAPI::Broodwar->enemy();
// We'll go through the bases and pick the one with the best score.
BWTA::BaseLocation * bestBase = nullptr;
double bestScore = -999999.0;
auto myBases = InformationManager::Instance().getMyBases();
auto enemyBases = InformationManager::Instance().getEnemyBases(); // may be empty
for (BWTA::BaseLocation * base : BWTA::getBaseLocations())
{
double score = 0.0;
// Do we demand a gas base?
if (wantGas && (base->isMineralOnly() || base->gas() == 0))
{
continue;
}
// Do we demand a mineral base?
// The constant is an arbitrary limit "enough minerals to be worth it".
if (wantMinerals && base->minerals() < 500)
{
continue;
}
// Don't expand to an existing base.
if (InformationManager::Instance().getBaseOwner(base) != BWAPI::Broodwar->neutral())
{
continue;
}
// Don't expand to a spider-mined base.
if (InformationManager::Instance().getBase(base)->spiderMined)
{
continue;
}
BWAPI::TilePosition tile = base->getTilePosition();
bool buildingInTheWay = false;
for (int x = 0; x < player->getRace().getCenter().tileWidth(); ++x)
{
for (int y = 0; y < player->getRace().getCenter().tileHeight(); ++y)
{
if (BuildingPlacer::Instance().isReserved(tile.x + x, tile.y + y))
{
// This happens if we were already planning to expand here. Try somewhere else.
buildingInTheWay = true;
break;
}
// TODO bug: this doesn't include enemy buildings which are known but out of sight
for (const auto unit : BWAPI::Broodwar->getUnitsOnTile(BWAPI::TilePosition (tile.x + x, tile.y + y)))
{
if (unit->getType().isBuilding() && !unit->isLifted())
{
buildingInTheWay = true;
break;
}
}
}
}
if (buildingInTheWay)
{
continue;
}
// Want to be close to our own base (unless this is to be a hidden base).
double distanceFromUs = closestBaseDistance(base, myBases);
// if it is not connected, continue
if (distanceFromUs < 0)
{
continue;
}
// Want to be far from the enemy base.
double distanceFromEnemy = std::max(0, closestBaseDistance(base, enemyBases));
// Add up the score.
score = hidden ? (distanceFromEnemy + distanceFromUs / 2.0) : (distanceFromEnemy / 1.5 - distanceFromUs);
// More resources -> better.
if (wantMinerals)
{
score += 0.01 * base->minerals();
}
if (wantGas)
{
score += 0.02 * base->gas();
}
// Big penalty for enemy buildings in the same region.
if (InformationManager::Instance().isEnemyBuildingInRegion(base->getRegion(), false))
{
score -= 100.0;
}
// BWAPI::Broodwar->printf("base score %d, %d -> %f", tile.x, tile.y, score);
if (score > bestScore)
{
bestBase = base;
bestScore = score;
}
}
if (bestBase)
{
return bestBase;
}
if (wantMinerals && wantGas)
{
// We wanted a gas base and there isn't one. Try for a mineral-only base.
return nextExpansion(hidden, true, false);
}
return nullptr;
}
int MapTools::closestBaseDistance(BWTA::BaseLocation * base, std::vector<BWTA::BaseLocation*> bases)
{
int closestDistance = -1;
for (auto other : bases)
{
int dist = getGroundTileDistance(base->getPosition(), other->getPosition());
if (dist >= 0 && (dist < closestDistance || closestDistance == -1))
closestDistance = dist;
}
return closestDistance;
}
BWAPI::TilePosition MapTools::getNextExpansion(bool hidden, bool wantMinerals, bool wantGas)
{
BWTA::BaseLocation * base = nextExpansion(hidden, wantMinerals, wantGas);
if (base)
{
// BWAPI::Broodwar->printf("foresee base @ %d, %d", base->getTilePosition().x, base->getTilePosition().y);
return base->getTilePosition();
}
return BWAPI::TilePositions::None;
}
/*
获取距离起点坐标指定长度的坐标,靠近用
*/
BWAPI::Position MapTools::getDistancePosition(BWAPI::Position start, BWAPI::Position end, double dist) {
double distance = sqrt(pow(start.x - end.x, 2) + pow(start.y - end.y, 2));// 两点的坐标距离
double lenthUnit = distance / 5;// 单位长度
// 第一步:求得直线方程相关参数y=kx+b
double k = (start.y - end.y) * 1.0 / (start.x - end.x);// 坐标直线斜率k
double b = start.y - k * start.x;// 坐标直线b
// 第二步:求得在直线y=kx+b上,距离当前坐标距离为L的某点
// 一元二次方程Ax^2+Bx+C=0中,
// 一元二次方程求根公式:
// 两根x1,x2= [-B±√(B^2-4AC)]/2A
// ①(y-y0)^2+(x-x0)^2=L^2;
// ②y=kx+b;
// 式中x,y即为根据以上lenthUnit单位长度(这里就是距离L)对应点的坐标
// 由①②表达式得到:(k^2+1)x^2+2[(b-y0)k-x0]x+[(b-y0)^2+x0^2-L^2]=0
double A = pow(k, 2) + 1;// A=k^2+1;
double B = 2 * ((b - start.y) * k - start.x);// B=2[(b-y0)k-x0];
int m = 1;
double L = m * dist;
// C=(b-y0)^2+x0^2-L^2
double C = pow(b - start.y, 2) + pow(start.x, 2)
- pow(L, 2);
// 两根x1,x2= [-B±√(B^2-4AC)]/2A
double x1 = (-B + sqrt(pow(B, 2) - 4 * A * C)) / (2 * A);
double x2 = (-B - sqrt(pow(B, 2) - 4 * A * C)) / (2 * A);
double x = 0;// 最后确定是在已知两点之间的某点
if (x1 == x2) {
x = x1;
}
else if (start.x <= x1 && x1 <= end.x || end.x <= x1
&& x1 <= start.x) {
x = x1;
}
else if (start.x <= x2 && x2 <= end.x || end.x <= x2
&& x2 <= start.x) {
x = x2;
}
double y = k * x + b;
return BWAPI::Position(x, y);
}
/*
获取距离起点延长指定长度的坐标,后退用
*/
BWAPI::Position MapTools::getExtendedPosition(BWAPI::Position start, BWAPI::Position end, double dist) {
double xab, yab;
double xbd, ybd;
double xd, yd;
xab = start.x - end.x;
yab = start.y - end.y;
xbd = sqrt((dist * dist) / ((yab / xab) * (yab / xab) + 1));
if (xab > 0) {
xbd = sqrt((dist * dist) / ((yab / xab) * (yab / xab) + 1));
}
else {
xbd = -sqrt((dist * dist) / ((yab / xab) * (yab / xab) + 1));
}
xd = start.x + xbd;
yd = start.y + yab / xab * xbd;
//printf("xd=%f,yd=%f\n", xd, yd);
return BWAPI::Position(xd, yd);
}
//求点到圆的切点
void MapTools::getCutPoint(BWAPI::Position center, double radius, BWAPI::Position sp, BWAPI::Position & rp1, BWAPI::Position & rp2)
{
double m = sp.x, n = sp.y;
double a = center.x, b = center.y;
double r = radius;
double dx = center.x - sp.x;
double dy = center.y - sp.y;
//计算点击处与圆心相对于X轴的夹角
double r1 = atan2(dy, dx);
//计算点击处与圆心、点击处与切点1这两条线段间的夹角
double d1 = sqrt(dx*dx + dy*dy);
double r2 = asin(radius / d1);
//计算从切点1向圆的垂直直径做垂线形成的直角三角形的一个角
double r3 = r1 - r2;
//计算坐标系中的角度
double r4 = r3 - 3.1415926 / 2;
//计算切点1相对于圆心的x、y坐标
double x1 = radius * cos(r4);
double y1 = radius * sin(r4);
//计算点击处与切线2相对于X轴的夹角
double r5 = 3.1415926 / 2 - r1 - r2;
//计算坐标系中的角度
double r6 = -r5;
//计算切点2相对于圆心的x、y坐标
double x2 = radius * cos(r6);
double y2 = radius * sin(r6);
rp1.x = center.x + x1;
rp1.y = center.y + y1;
rp2.x = center.x - x2;
rp2.y = center.y - y2;
}
std::vector<BWAPI::Position> MapTools::calculateEnemyRegionVertices(BWTA::BaseLocation * enemyBaseLocation) {
std::vector<BWAPI::Position> _regionVertices;
if (!enemyBaseLocation)
{
return _regionVertices;
}
BWTA::Region * enemyRegion = enemyBaseLocation->getRegion();
if (!enemyRegion)
{
return _regionVertices;
}
const BWAPI::Position basePosition = BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation());
const std::vector<BWAPI::TilePosition> & closestTobase = getClosestTilesTo(basePosition);
std::set<BWAPI::Position> unsortedVertices;
// check each tile position
for (size_t i(0); i < closestTobase.size(); ++i)
{
const BWAPI::TilePosition & tp = closestTobase[i];
if (BWTA::getRegion(tp) != enemyRegion)
{
continue;
}
// a tile is 'on an edge' unless
// 1) in all 4 directions there's a tile position in the current region
// 2) in all 4 directions there's a buildable tile
//瓷砖是 ' 在边缘 ', 除非
//1) 在所有4个方向在当前区域有一个瓷砖位置
//2) 在所有4个方向有一个可生成瓷砖
bool edge =
BWTA::getRegion(BWAPI::TilePosition(tp.x + 1, tp.y)) != enemyRegion || !BWAPI::Broodwar->isBuildable(BWAPI::TilePosition(tp.x + 1, tp.y))
|| BWTA::getRegion(BWAPI::TilePosition(tp.x, tp.y + 1)) != enemyRegion || !BWAPI::Broodwar->isBuildable(BWAPI::TilePosition(tp.x, tp.y + 1))
|| BWTA::getRegion(BWAPI::TilePosition(tp.x - 1, tp.y)) != enemyRegion || !BWAPI::Broodwar->isBuildable(BWAPI::TilePosition(tp.x - 1, tp.y))
|| BWTA::getRegion(BWAPI::TilePosition(tp.x, tp.y - 1)) != enemyRegion || !BWAPI::Broodwar->isBuildable(BWAPI::TilePosition(tp.x, tp.y - 1));
// push the tiles that aren't surrounded
//推开没有被包围的瓷砖
if (edge && BWAPI::Broodwar->isBuildable(tp))
{
if (Config::Debug::DrawScoutInfo)
{
int x1 = tp.x * 32 + 2;
int y1 = tp.y * 32 + 2;
int x2 = (tp.x + 1) * 32 - 2;
int y2 = (tp.y + 1) * 32 - 2;
BWAPI::Broodwar->drawTextMap(x1 + 3, y1 + 2, "%d", getGroundTileDistance(BWAPI::Position(tp), basePosition));
BWAPI::Broodwar->drawBoxMap(x1, y1, x2, y2, BWAPI::Colors::Green, false);
}
unsortedVertices.insert(BWAPI::Position(tp) + BWAPI::Position(16, 16));
}
}
std::vector<BWAPI::Position> sortedVertices;
BWAPI::Position current = *unsortedVertices.begin();
_regionVertices.push_back(current);
unsortedVertices.erase(current);
// while we still have unsorted vertices left, find the closest one remaining to current
//虽然我们仍然有未排序的顶点左, 找到最接近的一个剩余的当前
while (!unsortedVertices.empty())
{
double bestDist = 1000000;
BWAPI::Position bestPos;
for (const BWAPI::Position & pos : unsortedVertices)
{
double dist = pos.getDistance(current);
if (dist < bestDist)
{
bestDist = dist;
bestPos = pos;
}
}
current = bestPos;
sortedVertices.push_back(bestPos);
unsortedVertices.erase(bestPos);
}
// let's close loops on a threshold, eliminating death grooves
//让我们关闭循环的门槛, 消除死亡凹槽
int distanceThreshold = 100;
while (true)
{
// find the largest index difference whose distance is less than the threshold
//查找距离小于阈值的最大索引差异
int maxFarthest = 0;
int maxFarthestStart = 0;
int maxFarthestEnd = 0;
// for each starting vertex
for (int i(0); i < (int)sortedVertices.size(); ++i)
{
int farthest = 0;
int farthestIndex = 0;
// only test half way around because we'll find the other one on the way back
for (size_t j(1); j < sortedVertices.size() / 2; ++j)
{
int jindex = (i + j) % sortedVertices.size();
if (sortedVertices[i].getDistance(sortedVertices[jindex]) < distanceThreshold)
{
farthest = j;
farthestIndex = jindex;
}
}
if (farthest > maxFarthest)
{
maxFarthest = farthest;
maxFarthestStart = i;
maxFarthestEnd = farthestIndex;
}
}
// stop when we have no long chains within the threshold
if (maxFarthest < 4)
{
break;
}
std::vector<BWAPI::Position> temp;
for (size_t s(maxFarthestEnd); s != maxFarthestStart; s = (s + 1) % sortedVertices.size())
{
temp.push_back(sortedVertices[s]);
}
sortedVertices = temp;
}
return sortedVertices;
}
| [
"liongis@163.com"
] | liongis@163.com |
a12d7911d81f783de4df4204b3938ce06c3704d3 | 7044c0e66ed48d47dae188c2a2ab22ee6fd63ec3 | /src/Player.hpp | 91f04205af7da521e08bf7cf4c126239e49c3e46 | [] | no_license | fatumlegion/pelly | dba73fd20d9e92ddece6195364a7c31ed93b7285 | f4c51b79e3478648f4d91d7e6242174afff62d36 | refs/heads/master | 2016-08-04T20:32:35.147345 | 2013-08-21T01:30:37 | 2013-08-21T01:30:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 546 | hpp | #ifndef PLAYER_HPP
#define PLAYER_HPP
#include <SFML/Graphics.hpp>
#include "Block.hpp"
class Player
{
private:
sf::Sprite self;
bool right, left, moving, canJump, revGrav, canRotate, inRotation;
sf::Vector2f pos;
float xs, fric, grav, currentRotation, targetRotation;
sf::FloatRect box;
public:
Player(sf::Texture &txtr);
~Player();
void input(sf::Event &event);
void draw(sf::RenderWindow &rwin, float interp);
void update(float dt);
void touchBlock(Block &b);
sf::Vector2f getPosition() { return self.getPosition(); }
};
#endif | [
"fatumlegion@gmail.com"
] | fatumlegion@gmail.com |
1340b1353eb635b903b4f14353a07de75ee36a0d | 62232f6b7a23f990ccb781ce157dc0be91eac80c | /Engine/Source/Mesh/Mesh Overlay.cpp | 377d23c5ad95c6330503a651cd073d17e9d6dbc1 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | randydom/EsenthelEngine | 152adb45bac2e0f4a579f6479f209402c227708e | 4164781a2d906b136f66da2a021d649533a15ba9 | refs/heads/master | 2020-07-21T02:44:51.579450 | 2019-09-03T08:24:02 | 2019-09-03T08:24:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,835 | cpp | /******************************************************************************/
#include "stdafx.h"
namespace EE{
/******************************************************************************/
#define CC4_MSOV CC4('M','S','O','V')
/******************************************************************************/
static void SetBoxAndPlanes(Box &box, Memc<Plane> &planes, Matrix &matrix)
{
box.set(1)*=matrix;
planes.del();
Vec n;
// x
n=matrix.x; n.normalize();
planes.New().set(matrix.pos+matrix.x, n);
planes.New().set(matrix.pos-matrix.x, -n);
// y
n=matrix.y; n.normalize();
planes.New().set(matrix.pos+matrix.y, n);
planes.New().set(matrix.pos-matrix.y, -n);
// z
n=matrix.z; n.normalize();
planes.New().set(matrix.pos+matrix.z, n);
planes.New().set(matrix.pos-matrix.z, -n);
}
static void ClipMeshToPlanes(C Mesh &src, C Matrix *matrix, Mesh &dest, C Plane *clip_plane, Int clip_planes, C Box &box)
{
Mesh temp;
// box test
Vec corner[8]; src.ext.toCorners(corner); if(matrix)Transform(corner, *matrix, Elms(corner));
Bool all_inside=true;
REPD(p, clip_planes)
{
Bool inside=false,
outside=false;
REPAD(c, corner)
{
if(Dist(corner[c], clip_plane[p])<=0)inside=true;else outside=true;
}
if(!inside)goto finished; // if no vertexes are inside the plane then cancel
if(outside)all_inside=false;
}
// create dest
/*if(all_inside) can't be used because it may happen that we're operating on MeshRender
{
temp.create(src, flag_and);
if(matrix)
{
temp.transform(*matrix).setBox();
temp.lod_center=src.lod_center*(*matrix);
}
}else*/
{
Bool poly_cur=0;
Flt scale=(matrix ? matrix->maxScale() : 1);
Memc< Vec> poly[2];
Memc< Memc<Vec> > polys;
temp.copyParams(src);
FREPD(l, src.lods()) // order is important
{
C MeshLod &src_lod=src.lod(l);
REPA(src_lod)
{
// create 'polys' from MeshPart
C MeshPart &part=src_lod.parts[i];
Bool semi_transparent=false; if(part.material())if(part.material()->hasAlpha() || part.material()->technique==MTECH_FUR)semi_transparent=true;
if( !semi_transparent) // don't apply overlays on semi-transparent parts (because it will look like floating in air)
{
if(part.base.is()) // MSHB
{
C Vec *pos=part.base.vtx.pos();
REPA(part.base.tri) // TRI
{
VecI t=part.base.tri.ind(i);
poly[poly_cur].New()=pos[t.x];
poly[poly_cur].New()=pos[t.y];
poly[poly_cur].New()=pos[t.z];
if(matrix)REPAO(poly[poly_cur])*=*matrix;
Box b; b.from(poly[poly_cur].data(), poly[poly_cur].elms());
if(Cuts(b, box))
{
REPD(p, clip_planes)
{
ClipPoly(poly[poly_cur], clip_plane[p], poly[poly_cur^1]); poly_cur^=1;
if(poly[poly_cur].elms()<=2)goto mshb_tri_done;
}
Swap(poly[poly_cur], polys.New());
}
mshb_tri_done:;
poly[0].clear();
poly[1].clear();
}
REPA(part.base.quad) // QUAD
{
VecI4 q=part.base.quad.ind(i);
poly[poly_cur].New()=pos[q.x];
poly[poly_cur].New()=pos[q.y];
poly[poly_cur].New()=pos[q.z];
poly[poly_cur].New()=pos[q.w];
if(matrix)REPAO(poly[poly_cur])*=*matrix;
Box b; b.from(poly[poly_cur].data(), poly[poly_cur].elms());
if(Cuts(b, box))
{
REPD(p, clip_planes)
{
ClipPoly(poly[poly_cur], clip_plane[p], poly[poly_cur^1]); poly_cur^=1;
if(poly[poly_cur].elms()<=2)goto mshb_quad_done;
}
Swap(poly[poly_cur], polys.New());
}
mshb_quad_done:;
poly[0].clear();
poly[1].clear();
}
}else
if(part.render.is()) // MSHR
{
Int vtx_pos=part.render.vtxOfs(VTX_POS);
if( vtx_pos>=0)
if(C Byte *vtx=part.render.vtxLockRead())
{
vtx+=vtx_pos;
if(CPtr ind=part.render.indLockRead())
{
if(part.render._ib.bit16()) // 16 BIT
{
VecUS *tri=(VecUS*)ind;
REP(part.render.tris())
{
VecUS t=tri[i];
poly[poly_cur].New()=*(Vec*)(vtx+t.x*part.render.vtxSize());
poly[poly_cur].New()=*(Vec*)(vtx+t.y*part.render.vtxSize());
poly[poly_cur].New()=*(Vec*)(vtx+t.z*part.render.vtxSize());
if(matrix)REPAO(poly[poly_cur])*=*matrix;
Box b; b.from(poly[poly_cur].data(), poly[poly_cur].elms());
if(Cuts(b, box))
{
REPD(p, clip_planes)
{
ClipPoly(poly[poly_cur], clip_plane[p], poly[poly_cur^1]); poly_cur^=1;
if(poly[poly_cur].elms()<=2)goto mshr_tri16_done;
}
Swap(poly[poly_cur], polys.New());
}
mshr_tri16_done:;
poly[0].clear();
poly[1].clear();
}
}
else // 32 BIT
{
VecI *tri=(VecI*)ind;
REP(part.render.tris())
{
VecI t=tri[i];
poly[poly_cur].New()=*(Vec*)(vtx+t.x*part.render.vtxSize());
poly[poly_cur].New()=*(Vec*)(vtx+t.y*part.render.vtxSize());
poly[poly_cur].New()=*(Vec*)(vtx+t.z*part.render.vtxSize());
if(matrix)REPAO(poly[poly_cur])*=*matrix;
Box b; b.from(poly[poly_cur].data(), poly[poly_cur].elms());
if(Cuts(b, box))
{
REPD(p, clip_planes)
{
ClipPoly(poly[poly_cur], clip_plane[p], poly[poly_cur^1]); poly_cur^=1;
if(poly[poly_cur].elms()<=2)goto mshr_tri32_done;
}
Swap(poly[poly_cur], polys.New());
}
mshr_tri32_done:;
poly[0].clear();
poly[1].clear();
}
}
part.render.indUnlock();
}
part.render.vtxUnlock();
}
}
}
}
// create MeshBase from 'polys'
if(polys.elms())
{
MeshBase mshb; Triangulate(polys, mshb, EPS, true);
polys.clear();
if(mshb.vtxs() && mshb.faces())
{
MeshLod &dest_lod=(temp.parts.elms() ? temp.newLod() : temp);
dest_lod. copyParams(src_lod);
dest_lod.scaleParams(scale );
Swap(mshb, dest_lod.parts.New().base);
}
}
}
temp.setBox();
temp.lod_center=src.lod_center; if(matrix)temp.lod_center*=*matrix;
}
finished:;
Swap(dest, temp);
}
/******************************************************************************/
void MeshOverlay::zero()
{
_lod_center.zero();
_ext .zero();
_matrix .identity();
_shader=null;
}
MeshOverlay::MeshOverlay() {zero();}
MeshOverlay& MeshOverlay::del()
{
_lods .del ();
_material.clear();
zero(); return T;
}
/******************************************************************************/
Bool MeshOverlay::createStatic(C Mesh &mesh, C MaterialPtr &material, C Matrix &overlay_matrix, C Matrix *mesh_matrix)
{
del();
if(mesh.is())
{
_matrix=overlay_matrix;
Memc<Plane> planes;
Box box ; SetBoxAndPlanes(box, planes, _matrix);
Mesh temp ; ClipMeshToPlanes(mesh, mesh_matrix, temp, planes.data(), planes.elms(), box);
if(temp.is())
{
T._lod_center= temp.lod_center;
T._ext = temp.ext;
T._lods.setNum(temp.lods());
FREPD(l, temp.lods()) // order is important
{
MeshBase &mshb=temp.lod(l).parts[0].base;
#if 0
mshb.setNormals(); REPA(mshb.vtx)mshb.vtx.pos[i]+=mshb.vtx.nrm[i]*0.005f; // surface epsilon
#endif
#if 0
mshb.include(VTX_TEX0); REPA(mshb.vtx)mshb.vtx.tex0[i]=_matrix.convert(mshb.vtx.pos[i]); // maybe it will require changing axis length when restored
#endif
_lods[l].dist2=temp.lod(l).dist2;
_lods[l].mshr.create(mshb);
}
T.material(material);
return true;
}
}
return false;
}
Bool MeshOverlay::createAnimated(C Mesh &mesh, C MaterialPtr &material, C Matrix &overlay_matrix, C Matrix *mesh_matrix)
{
del();
if(mesh.is())
{
if(!mesh_matrix)_matrix=overlay_matrix;else
{
mesh_matrix->inverse(_matrix);
overlay_matrix.mul(_matrix, _matrix);
}
Memc<Plane> planes;
Box box ; SetBoxAndPlanes(box, planes, _matrix);
Mesh temp ; ClipMeshToPlanes(mesh, null, temp, planes.data(), planes.elms(), box);
if(temp.is())
{
T._lod_center= temp.lod_center;
T._ext = temp.ext;
T._lods.setNum(temp.lods());
FREPD(l, temp.lods()) // order is important
{
MeshBase &mshb=temp.lod(l).parts[0].base;
#if 0
mshb.setNormals(); REPA(mshb.vtx)mshb.vtx.pos[i]+=mshb.vtx.nrm[i]*0.005f; // surface epsilon
#endif
#if 0
mshb.include(VTX_TEX0); REPA(mshb.vtx)mshb.vtx.tex0[i]=_matrix.convert(mshb.vtx.pos[i]); // maybe it will require changing axis length when restored
#endif
_lods[l].dist2=temp.lod(l).dist2;
_lods[l].mshr.create(mshb);
}
T.material(material);
return true;
}
}
return false;
}
/******************************************************************************/
void MeshOverlay::setShader()
{
_shader=null;
if(_lods.elms() && _material && _material->base_0)_shader=ShaderFiles("Overlay")->get(ShaderOverlay(false, _material->base_1!=null));
}
MeshOverlay& MeshOverlay::material(C MaterialPtr &material)
{
T._material=material;
setShader();
return T;
}
#pragma pack(push, 4)
struct GOverlayClass
{
Vec4 param;
Matrix mtrx ;
};
#pragma pack(pop)
void MeshOverlay::setParams(Flt alpha)C // this is called only inside 'draw' methods, so '_material' is assumed to be != null
{
GOverlayClass overlay_params;
overlay_params.param.set(0.8f, alpha, 0, 0);
overlay_params.mtrx=_matrix;
Sh.OverlayParams->set(overlay_params);
_material ->setBlend();
D.depth(true);
D.cull (true);
//D.alpha(ALPHA_BLEND_FACTOR); not needed because ALPHA_BLEND_FACTOR is used everywhere in RM_OVERLAY
/*D.depthWrite(false); not needed because false is used everywhere in RM_OVERLAY*/ Renderer.needDepthTest(); // !! 'needDepthTest' after 'depthWrite' !!
}
/******************************************************************************/
C MeshRender& MeshOverlay::getDrawLod(C Matrix &matrix)C
{
if(_lods.elms()>1)
{
Flt dist2=GetLodDist2(_lod_center, matrix);
REPA(_lods){C Lod &test=_lods[i]; if(dist2>=test.dist2)return test.mshr;}
}
return _lods[0].mshr;
}
C MeshRender& MeshOverlay::getDrawLod(C MatrixM &matrix)C
{
if(_lods.elms()>1)
{
Flt dist2=GetLodDist2(_lod_center, matrix);
REPA(_lods){C Lod &test=_lods[i]; if(dist2>=test.dist2)return test.mshr;}
}
return _lods[0].mshr;
}
/******************************************************************************/
void MeshOverlay::draw(Flt alpha)C
{
if(_shader)
{
setParams(alpha);
_shader->begin(); C MeshRender &mshr=getDrawLod(ObjMatrix); mshr.set().draw();
}
}
void MeshOverlay::draw(C MatrixM &matrix, Flt alpha)C
{
if(_shader)
{
SetOneMatrix(matrix);
setParams(alpha);
_shader->begin(); C MeshRender &mshr=getDrawLod(matrix); mshr.set().draw();
}
}
void MeshOverlay::draw(C AnimatedSkeleton &anim_skel, Flt alpha)C
{
if(_shader)
{
anim_skel.setMatrix();
setParams(alpha);
_shader->begin(); C MeshRender &mshr=getDrawLod(anim_skel.matrix()); mshr.set(); mshr.draw();
}
}
/******************************************************************************/
Bool MeshOverlay::save(File &f, CChar *path)C
{
f.putMulti(Byte(0), Int(_lods.elms())); // version
if(_lods.elms())
{
f.putMulti(_lod_center, _ext, _matrix);
f.putAsset(_material.id());
FREPA(_lods)
{
f<<_lods[i].dist2;
if(!_lods[i].mshr.saveData(f))return false;
}
}
return f.ok();
}
Bool MeshOverlay::load(File &f, CChar *path)
{
del(); switch(f.decUIntV()) // version
{
case 0:
{
_lods.setNum(f.getInt());
if(_lods.elms())
{
f.getMulti(_lod_center, _ext, _matrix);
_material.require(f.getAssetID(), path);
FREPA(_lods)
{
f>>_lods[i].dist2;
if(!_lods[i].mshr.loadData(f))goto error;
}
setShader();
}
if(f.ok())return true;
}break;
}
error:
del(); return false;
}
/******************************************************************************/
}
/******************************************************************************/
| [
"esenthel@hotmail.com"
] | esenthel@hotmail.com |
b45a7be7429bc43e6fc6986cc06cc55538211716 | ba305b9bb38e6d9539f01400c180af4f93b3f567 | /quic_stream_factory.cc | 279b5eb993b1f09e1b0264ccacf778855f69d21e | [] | no_license | velicue/quic_codes | 2759ffff82f8741f99ef77bbef35fc4432d2925c | a0393aeccccb45ac40e8ece076f8fd026fe6b3d7 | refs/heads/master | 2021-01-01T18:38:33.596665 | 2014-07-19T00:50:19 | 2014-07-19T00:50:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,393 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quic/quic_stream_factory.h"
#include <set>
#include "base/cpu.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/metrics/histogram.h"
#include "base/rand_util.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "net/base/net_errors.h"
#include "net/cert/cert_verifier.h"
#include "net/dns/host_resolver.h"
#include "net/dns/single_request_host_resolver.h"
#include "net/http/http_server_properties.h"
#include "net/quic/congestion_control/tcp_receiver.h"
#include "net/quic/crypto/proof_verifier_chromium.h"
#include "net/quic/crypto/quic_random.h"
#include "net/quic/crypto/quic_server_info.h"
#include "net/quic/port_suggester.h"
#include "net/quic/quic_client_session.h"
#include "net/quic/quic_clock.h"
#include "net/quic/quic_connection.h"
#include "net/quic/quic_connection_helper.h"
#include "net/quic/quic_crypto_client_stream_factory.h"
#include "net/quic/quic_default_packet_writer.h"
#include "net/quic/quic_http_stream.h"
#include "net/quic/quic_protocol.h"
#include "net/quic/quic_server_id.h"
#include "net/socket/client_socket_factory.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
using std::string;
using std::vector;
namespace net {
namespace {
enum CreateSessionFailure {
CREATION_ERROR_CONNECTING_SOCKET,
CREATION_ERROR_SETTING_RECEIVE_BUFFER,
CREATION_ERROR_SETTING_SEND_BUFFER,
CREATION_ERROR_MAX
};
// When a connection is idle for 30 seconds it will be closed.
const int kIdleConnectionTimeoutSeconds = 30;
// The initial receive window size for both streams and sessions.
const int32 kInitialReceiveWindowSize = 10 * 1024 * 1024; // 10MB
// The suggested initial congestion windows for a server to use.
// TODO: This should be tested and optimized, and even better, suggest a window
// that corresponds to historical bandwidth and min-RTT.
// Larger initial congestion windows can, if we don't overshoot, reduce latency
// by avoiding the RTT needed for slow start to double (and re-double) from a
// default of 10.
// We match SPDY's use of 32 when secure (since we'd compete with SPDY).
const int32 kServerSecureInitialCongestionWindow = 32;
// Be conservative, and just use double a typical TCP ICWND for HTTP.
const int32 kServerInecureInitialCongestionWindow = 20;
void HistogramCreateSessionFailure(enum CreateSessionFailure error) {
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.CreationError", error,
CREATION_ERROR_MAX);
}
bool IsEcdsaSupported() {
#if defined(OS_WIN)
if (base::win::GetVersion() < base::win::VERSION_VISTA)
return false;
#endif
return true;
}
QuicConfig InitializeQuicConfig(bool enable_pacing,
bool enable_time_based_loss_detection,
QuicTagVector connection_options) {
QuicConfig config;
config.SetDefaults();
config.EnablePacing(enable_pacing);
if (enable_time_based_loss_detection)
config.SetLossDetectionToSend(kTIME);
config.set_idle_connection_state_lifetime(
QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds),
QuicTime::Delta::FromSeconds(kIdleConnectionTimeoutSeconds));
config.SetConnectionOptionsToSend(connection_options);
return config;
}
} // namespace
QuicStreamFactory::IpAliasKey::IpAliasKey() {}
QuicStreamFactory::IpAliasKey::IpAliasKey(IPEndPoint ip_endpoint,
bool is_https)
: ip_endpoint(ip_endpoint),
is_https(is_https) {}
QuicStreamFactory::IpAliasKey::~IpAliasKey() {}
bool QuicStreamFactory::IpAliasKey::operator<(
const QuicStreamFactory::IpAliasKey& other) const {
if (!(ip_endpoint == other.ip_endpoint)) {
return ip_endpoint < other.ip_endpoint;
}
return is_https < other.is_https;
}
bool QuicStreamFactory::IpAliasKey::operator==(
const QuicStreamFactory::IpAliasKey& other) const {
return is_https == other.is_https &&
ip_endpoint == other.ip_endpoint;
};
// Responsible for creating a new QUIC session to the specified server, and
// for notifying any associated requests when complete.
class QuicStreamFactory::Job {
public:
Job(QuicStreamFactory* factory,
HostResolver* host_resolver,
const HostPortPair& host_port_pair,
bool is_https,
bool was_alternate_protocol_recently_broken,
PrivacyMode privacy_mode,
base::StringPiece method,
QuicServerInfo* server_info,
const BoundNetLog& net_log);
// Creates a new job to handle the resumption of for connecting an
// existing session.
Job(QuicStreamFactory* factory,
HostResolver* host_resolver,
QuicClientSession* session,
QuicServerId server_id);
~Job();
int Run(const CompletionCallback& callback);
int DoLoop(int rv);
int DoResolveHost();
int DoResolveHostComplete(int rv);
int DoLoadServerInfo();
int DoLoadServerInfoComplete(int rv);
int DoConnect();
int DoResumeConnect();
int DoConnectComplete(int rv);
void OnIOComplete(int rv);
CompletionCallback callback() {
return callback_;
}
const QuicServerId server_id() const {
return server_id_;
}
private:
enum IoState {
STATE_NONE,
STATE_RESOLVE_HOST,
STATE_RESOLVE_HOST_COMPLETE,
STATE_LOAD_SERVER_INFO,
STATE_LOAD_SERVER_INFO_COMPLETE,
STATE_CONNECT,
STATE_RESUME_CONNECT,
STATE_CONNECT_COMPLETE,
};
IoState io_state_;
QuicStreamFactory* factory_;
SingleRequestHostResolver host_resolver_;
QuicServerId server_id_;
bool is_post_;
bool was_alternate_protocol_recently_broken_;
scoped_ptr<QuicServerInfo> server_info_;
const BoundNetLog net_log_;
QuicClientSession* session_;
CompletionCallback callback_;
AddressList address_list_;
base::TimeTicks disk_cache_load_start_time_;
base::WeakPtrFactory<Job> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(Job);
};
QuicStreamFactory::Job::Job(QuicStreamFactory* factory,
HostResolver* host_resolver,
const HostPortPair& host_port_pair,
bool is_https,
bool was_alternate_protocol_recently_broken,
PrivacyMode privacy_mode,
base::StringPiece method,
QuicServerInfo* server_info,
const BoundNetLog& net_log)
: io_state_(STATE_RESOLVE_HOST),
factory_(factory),
host_resolver_(host_resolver),
server_id_(host_port_pair, is_https, privacy_mode),
is_post_(method == "POST"),
was_alternate_protocol_recently_broken_(
was_alternate_protocol_recently_broken),
server_info_(server_info),
net_log_(net_log),
session_(NULL),
weak_factory_(this) {}
QuicStreamFactory::Job::Job(QuicStreamFactory* factory,
HostResolver* host_resolver,
QuicClientSession* session,
QuicServerId server_id)
: io_state_(STATE_RESUME_CONNECT),
factory_(factory),
host_resolver_(host_resolver), // unused
server_id_(server_id),
is_post_(false), // unused
was_alternate_protocol_recently_broken_(false), // unused
net_log_(session->net_log()), // unused
session_(session),
weak_factory_(this) {}
QuicStreamFactory::Job::~Job() {
}
int QuicStreamFactory::Job::Run(const CompletionCallback& callback) {
int rv = DoLoop(OK);
if (rv == ERR_IO_PENDING)
callback_ = callback;
return rv > 0 ? OK : rv;
}
int QuicStreamFactory::Job::DoLoop(int rv) {
do {
IoState state = io_state_;
io_state_ = STATE_NONE;
switch (state) {
case STATE_RESOLVE_HOST:
CHECK_EQ(OK, rv);
rv = DoResolveHost();
break;
case STATE_RESOLVE_HOST_COMPLETE:
rv = DoResolveHostComplete(rv);
break;
case STATE_LOAD_SERVER_INFO:
CHECK_EQ(OK, rv);
rv = DoLoadServerInfo();
break;
case STATE_LOAD_SERVER_INFO_COMPLETE:
rv = DoLoadServerInfoComplete(rv);
break;
case STATE_CONNECT:
CHECK_EQ(OK, rv);
rv = DoConnect();
break;
case STATE_RESUME_CONNECT:
CHECK_EQ(OK, rv);
rv = DoResumeConnect();
break;
case STATE_CONNECT_COMPLETE:
rv = DoConnectComplete(rv);
break;
default:
NOTREACHED() << "io_state_: " << io_state_;
break;
}
} while (io_state_ != STATE_NONE && rv != ERR_IO_PENDING);
return rv;
}
void QuicStreamFactory::Job::OnIOComplete(int rv) {
rv = DoLoop(rv);
if (rv != ERR_IO_PENDING && !callback_.is_null()) {
callback_.Run(rv);
}
}
int QuicStreamFactory::Job::DoResolveHost() {
// Start loading the data now, and wait for it after we resolve the host.
if (server_info_) {
disk_cache_load_start_time_ = base::TimeTicks::Now();
server_info_->Start();
}
io_state_ = STATE_RESOLVE_HOST_COMPLETE;
return host_resolver_.Resolve(
HostResolver::RequestInfo(server_id_.host_port_pair()),
DEFAULT_PRIORITY,
&address_list_,
base::Bind(&QuicStreamFactory::Job::OnIOComplete,
weak_factory_.GetWeakPtr()),
net_log_);
}
int QuicStreamFactory::Job::DoResolveHostComplete(int rv) {
if (rv != OK)
return rv;
DCHECK(!factory_->HasActiveSession(server_id_));
// Inform the factory of this resolution, which will set up
// a session alias, if possible.
if (factory_->OnResolution(server_id_, address_list_)) {
return OK;
}
io_state_ = STATE_LOAD_SERVER_INFO;
return OK;
}
int QuicStreamFactory::Job::DoLoadServerInfo() {
io_state_ = STATE_LOAD_SERVER_INFO_COMPLETE;
if (!server_info_)
return OK;
return server_info_->WaitForDataReady(
base::Bind(&QuicStreamFactory::Job::OnIOComplete,
weak_factory_.GetWeakPtr()));
}
int QuicStreamFactory::Job::DoLoadServerInfoComplete(int rv) {
if (server_info_) {
UMA_HISTOGRAM_TIMES("Net.QuicServerInfo.DiskCacheReadTime",
base::TimeTicks::Now() - disk_cache_load_start_time_);
}
if (rv != OK) {
server_info_.reset();
}
io_state_ = STATE_CONNECT;
return OK;
}
int QuicStreamFactory::Job::DoConnect() {
io_state_ = STATE_CONNECT_COMPLETE;
int rv = factory_->CreateSession(server_id_, server_info_.Pass(),
address_list_, net_log_, &session_);
if (rv != OK) {
DCHECK(rv != ERR_IO_PENDING);
DCHECK(!session_);
return rv;
}
session_->StartReading();
if (!session_->connection()->connected()) {
return ERR_QUIC_PROTOCOL_ERROR;
}
bool require_confirmation =
factory_->require_confirmation() || is_post_ ||
was_alternate_protocol_recently_broken_;
rv = session_->CryptoConnect(
require_confirmation,
base::Bind(&QuicStreamFactory::Job::OnIOComplete,
base::Unretained(this)));
return rv;
}
int QuicStreamFactory::Job::DoResumeConnect() {
io_state_ = STATE_CONNECT_COMPLETE;
int rv = session_->ResumeCryptoConnect(
base::Bind(&QuicStreamFactory::Job::OnIOComplete,
base::Unretained(this)));
return rv;
}
int QuicStreamFactory::Job::DoConnectComplete(int rv) {
if (rv != OK)
return rv;
DCHECK(!factory_->HasActiveSession(server_id_));
// There may well now be an active session for this IP. If so, use the
// existing session instead.
AddressList address(session_->connection()->peer_address());
if (factory_->OnResolution(server_id_, address)) {
session_->connection()->SendConnectionClose(QUIC_CONNECTION_IP_POOLED);
session_ = NULL;
return OK;
}
factory_->ActivateSession(server_id_, session_);
return OK;
}
QuicStreamRequest::QuicStreamRequest(QuicStreamFactory* factory)
: factory_(factory) {}
QuicStreamRequest::~QuicStreamRequest() {
if (factory_ && !callback_.is_null())
factory_->CancelRequest(this);
}
int QuicStreamRequest::Request(const HostPortPair& host_port_pair,
bool is_https,
PrivacyMode privacy_mode,
base::StringPiece method,
const BoundNetLog& net_log,
const CompletionCallback& callback) {
DCHECK(!stream_);
DCHECK(callback_.is_null());
DCHECK(factory_);
int rv = factory_->Create(host_port_pair, is_https, privacy_mode, method,
net_log, this);
if (rv == ERR_IO_PENDING) {
host_port_pair_ = host_port_pair;
is_https_ = is_https;
net_log_ = net_log;
callback_ = callback;
} else {
factory_ = NULL;
}
if (rv == OK)
DCHECK(stream_);
return rv;
}
void QuicStreamRequest::set_stream(scoped_ptr<QuicHttpStream> stream) {
DCHECK(stream);
stream_ = stream.Pass();
}
void QuicStreamRequest::OnRequestComplete(int rv) {
factory_ = NULL;
callback_.Run(rv);
}
scoped_ptr<QuicHttpStream> QuicStreamRequest::ReleaseStream() {
DCHECK(stream_);
return stream_.Pass();
}
QuicStreamFactory::QuicStreamFactory(
HostResolver* host_resolver,
ClientSocketFactory* client_socket_factory,
base::WeakPtr<HttpServerProperties> http_server_properties,
CertVerifier* cert_verifier,
QuicCryptoClientStreamFactory* quic_crypto_client_stream_factory,
QuicRandom* random_generator,
QuicClock* clock,
size_t max_packet_length,
const std::string& user_agent_id,
const QuicVersionVector& supported_versions,
bool enable_port_selection,
bool enable_pacing,
bool enable_time_based_loss_detection,
QuicTagVector connection_options)
: require_confirmation_(true),
host_resolver_(host_resolver),
client_socket_factory_(client_socket_factory),
http_server_properties_(http_server_properties),
cert_verifier_(cert_verifier),
quic_server_info_factory_(NULL),
quic_crypto_client_stream_factory_(quic_crypto_client_stream_factory),
random_generator_(random_generator),
clock_(clock),
max_packet_length_(max_packet_length),
config_(InitializeQuicConfig(enable_pacing,
enable_time_based_loss_detection,
connection_options)),
supported_versions_(supported_versions),
enable_port_selection_(enable_port_selection),
port_seed_(random_generator_->RandUint64()),
weak_factory_(this) {
crypto_config_.SetDefaults();
crypto_config_.set_user_agent_id(user_agent_id);
crypto_config_.AddCanonicalSuffix(".c.youtube.com");
crypto_config_.AddCanonicalSuffix(".googlevideo.com");
crypto_config_.SetProofVerifier(new ProofVerifierChromium(cert_verifier));
base::CPU cpu;
if (cpu.has_aesni() && cpu.has_avx())
crypto_config_.PreferAesGcm();
if (!IsEcdsaSupported())
crypto_config_.DisableEcdsa();
}
QuicStreamFactory::~QuicStreamFactory() {
CloseAllSessions(ERR_ABORTED);
while (!all_sessions_.empty()) {
delete all_sessions_.begin()->first;
all_sessions_.erase(all_sessions_.begin());
}
STLDeleteValues(&active_jobs_);
}
int QuicStreamFactory::Create(const HostPortPair& host_port_pair,
bool is_https,
PrivacyMode privacy_mode,
base::StringPiece method,
const BoundNetLog& net_log,
QuicStreamRequest* request) {
QuicServerId server_id(host_port_pair, is_https, privacy_mode);
if (HasActiveSession(server_id)) {
request->set_stream(CreateIfSessionExists(server_id, net_log));
return OK;
}
if (HasActiveJob(server_id)) {
Job* job = active_jobs_[server_id];
active_requests_[request] = job;
job_requests_map_[job].insert(request);
return ERR_IO_PENDING;
}
QuicServerInfo* quic_server_info = NULL;
if (quic_server_info_factory_) {
QuicCryptoClientConfig::CachedState* cached =
crypto_config_.LookupOrCreate(server_id);
DCHECK(cached);
if (cached->IsEmpty()) {
quic_server_info = quic_server_info_factory_->GetForServer(server_id);
}
}
bool was_alternate_protocol_recently_broken =
http_server_properties_ &&
http_server_properties_->WasAlternateProtocolRecentlyBroken(
server_id.host_port_pair());
scoped_ptr<Job> job(new Job(this, host_resolver_, host_port_pair, is_https,
was_alternate_protocol_recently_broken,
privacy_mode, method, quic_server_info, net_log));
int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
base::Unretained(this), job.get()));
if (rv == ERR_IO_PENDING) {
active_requests_[request] = job.get();
job_requests_map_[job.get()].insert(request);
active_jobs_[server_id] = job.release();
}
if (rv == OK) {
DCHECK(HasActiveSession(server_id));
request->set_stream(CreateIfSessionExists(server_id, net_log));
}
return rv;
}
bool QuicStreamFactory::OnResolution(
const QuicServerId& server_id,
const AddressList& address_list) {
DCHECK(!HasActiveSession(server_id));
for (size_t i = 0; i < address_list.size(); ++i) {
const IPEndPoint& address = address_list[i];
const IpAliasKey ip_alias_key(address, server_id.is_https());
if (!ContainsKey(ip_aliases_, ip_alias_key))
continue;
const SessionSet& sessions = ip_aliases_[ip_alias_key];
for (SessionSet::const_iterator i = sessions.begin();
i != sessions.end(); ++i) {
QuicClientSession* session = *i;
if (!session->CanPool(server_id.host()))
continue;
active_sessions_[server_id] = session;
session_aliases_[session].insert(server_id);
return true;
}
}
return false;
}
void QuicStreamFactory::OnJobComplete(Job* job, int rv) {
if (rv == OK) {
require_confirmation_ = false;
// Create all the streams, but do not notify them yet.
for (RequestSet::iterator it = job_requests_map_[job].begin();
it != job_requests_map_[job].end() ; ++it) {
DCHECK(HasActiveSession(job->server_id()));
(*it)->set_stream(CreateIfSessionExists(job->server_id(),
(*it)->net_log()));
}
}
while (!job_requests_map_[job].empty()) {
RequestSet::iterator it = job_requests_map_[job].begin();
QuicStreamRequest* request = *it;
job_requests_map_[job].erase(it);
active_requests_.erase(request);
// Even though we're invoking callbacks here, we don't need to worry
// about |this| being deleted, because the factory is owned by the
// profile which can not be deleted via callbacks.
request->OnRequestComplete(rv);
}
active_jobs_.erase(job->server_id());
job_requests_map_.erase(job);
delete job;
return;
}
// Returns a newly created QuicHttpStream owned by the caller, if a
// matching session already exists. Returns NULL otherwise.
scoped_ptr<QuicHttpStream> QuicStreamFactory::CreateIfSessionExists(
const QuicServerId& server_id,
const BoundNetLog& net_log) {
if (!HasActiveSession(server_id)) {
DVLOG(1) << "No active session";
return scoped_ptr<QuicHttpStream>();
}
QuicClientSession* session = active_sessions_[server_id];
DCHECK(session);
return scoped_ptr<QuicHttpStream>(
new QuicHttpStream(session->GetWeakPtr()));
}
void QuicStreamFactory::OnIdleSession(QuicClientSession* session) {
}
void QuicStreamFactory::OnSessionGoingAway(QuicClientSession* session) {
const AliasSet& aliases = session_aliases_[session];
for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
++it) {
DCHECK(active_sessions_.count(*it));
DCHECK_EQ(session, active_sessions_[*it]);
// Track sessions which have recently gone away so that we can disable
// port suggestions.
if (session->goaway_received()) {
gone_away_aliases_.insert(*it);
}
active_sessions_.erase(*it);
ProcessGoingAwaySession(session, *it, true);
}
ProcessGoingAwaySession(session, all_sessions_[session], false);
if (!aliases.empty()) {
const IpAliasKey ip_alias_key(session->connection()->peer_address(),
aliases.begin()->is_https());
ip_aliases_[ip_alias_key].erase(session);
if (ip_aliases_[ip_alias_key].empty()) {
ip_aliases_.erase(ip_alias_key);
}
}
session_aliases_.erase(session);
}
void QuicStreamFactory::OnSessionClosed(QuicClientSession* session) {
DCHECK_EQ(0u, session->GetNumOpenStreams());
OnSessionGoingAway(session);
delete session;
all_sessions_.erase(session);
}
void QuicStreamFactory::OnSessionConnectTimeout(
QuicClientSession* session) {
const AliasSet& aliases = session_aliases_[session];
for (AliasSet::const_iterator it = aliases.begin(); it != aliases.end();
++it) {
DCHECK(active_sessions_.count(*it));
DCHECK_EQ(session, active_sessions_[*it]);
active_sessions_.erase(*it);
}
if (aliases.empty()) {
return;
}
const IpAliasKey ip_alias_key(session->connection()->peer_address(),
aliases.begin()->is_https());
ip_aliases_[ip_alias_key].erase(session);
if (ip_aliases_[ip_alias_key].empty()) {
ip_aliases_.erase(ip_alias_key);
}
QuicServerId server_id = *aliases.begin();
session_aliases_.erase(session);
Job* job = new Job(this, host_resolver_, session, server_id);
active_jobs_[server_id] = job;
int rv = job->Run(base::Bind(&QuicStreamFactory::OnJobComplete,
base::Unretained(this), job));
DCHECK_EQ(ERR_IO_PENDING, rv);
}
void QuicStreamFactory::CancelRequest(QuicStreamRequest* request) {
DCHECK(ContainsKey(active_requests_, request));
Job* job = active_requests_[request];
job_requests_map_[job].erase(request);
active_requests_.erase(request);
}
void QuicStreamFactory::CloseAllSessions(int error) {
while (!active_sessions_.empty()) {
size_t initial_size = active_sessions_.size();
active_sessions_.begin()->second->CloseSessionOnError(error);
DCHECK_NE(initial_size, active_sessions_.size());
}
while (!all_sessions_.empty()) {
size_t initial_size = all_sessions_.size();
all_sessions_.begin()->first->CloseSessionOnError(error);
DCHECK_NE(initial_size, all_sessions_.size());
}
DCHECK(all_sessions_.empty());
}
base::Value* QuicStreamFactory::QuicStreamFactoryInfoToValue() const {
base::ListValue* list = new base::ListValue();
for (SessionMap::const_iterator it = active_sessions_.begin();
it != active_sessions_.end(); ++it) {
const QuicServerId& server_id = it->first;
QuicClientSession* session = it->second;
const AliasSet& aliases = session_aliases_.find(session)->second;
// Only add a session to the list once.
if (server_id == *aliases.begin()) {
std::set<HostPortPair> hosts;
for (AliasSet::const_iterator alias_it = aliases.begin();
alias_it != aliases.end(); ++alias_it) {
hosts.insert(alias_it->host_port_pair());
}
list->Append(session->GetInfoAsValue(hosts));
}
}
return list;
}
void QuicStreamFactory::ClearCachedStatesInCryptoConfig() {
crypto_config_.ClearCachedStates();
}
void QuicStreamFactory::OnIPAddressChanged() {
CloseAllSessions(ERR_NETWORK_CHANGED);
require_confirmation_ = true;
}
void QuicStreamFactory::OnCertAdded(const X509Certificate* cert) {
CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
}
void QuicStreamFactory::OnCACertChanged(const X509Certificate* cert) {
// We should flush the sessions if we removed trust from a
// cert, because a previously trusted server may have become
// untrusted.
//
// We should not flush the sessions if we added trust to a cert.
//
// Since the OnCACertChanged method doesn't tell us what
// kind of change it is, we have to flush the socket
// pools to be safe.
CloseAllSessions(ERR_CERT_DATABASE_CHANGED);
}
bool QuicStreamFactory::HasActiveSession(
const QuicServerId& server_id) const {
return ContainsKey(active_sessions_, server_id);
}
int QuicStreamFactory::CreateSession(
const QuicServerId& server_id,
scoped_ptr<QuicServerInfo> server_info,
const AddressList& address_list,
const BoundNetLog& net_log,
QuicClientSession** session) {
bool enable_port_selection = enable_port_selection_;
if (enable_port_selection &&
ContainsKey(gone_away_aliases_, server_id)) {
// Disable port selection when the server is going away.
// There is no point in trying to return to the same server, if
// that server is no longer handling requests.
enable_port_selection = false;
gone_away_aliases_.erase(server_id);
}
QuicConnectionId connection_id = random_generator_->RandUint64();
IPEndPoint addr = *address_list.begin();
scoped_refptr<PortSuggester> port_suggester =
new PortSuggester(server_id.host_port_pair(), port_seed_);
DatagramSocket::BindType bind_type = enable_port_selection ?
DatagramSocket::RANDOM_BIND : // Use our callback.
DatagramSocket::DEFAULT_BIND; // Use OS to randomize.
scoped_ptr<DatagramClientSocket> socket(
client_socket_factory_->CreateDatagramClientSocket(
bind_type,
base::Bind(&PortSuggester::SuggestPort, port_suggester),
net_log.net_log(), net_log.source()));
int rv = socket->Connect(addr);
if (rv != OK) {
HistogramCreateSessionFailure(CREATION_ERROR_CONNECTING_SOCKET);
return rv;
}
UMA_HISTOGRAM_COUNTS("Net.QuicEphemeralPortsSuggested",
port_suggester->call_count());
if (enable_port_selection) {
DCHECK_LE(1u, port_suggester->call_count());
} else {
DCHECK_EQ(0u, port_suggester->call_count());
}
// We should adaptively set this buffer size, but for now, we'll use a size
// that is more than large enough for a full receive window, and yet
// does not consume "too much" memory. If we see bursty packet loss, we may
// revisit this setting and test for its impact.
const int32 kSocketBufferSize(TcpReceiver::kReceiveWindowTCP);
rv = socket->SetReceiveBufferSize(kSocketBufferSize);
if (rv != OK) {
HistogramCreateSessionFailure(CREATION_ERROR_SETTING_RECEIVE_BUFFER);
return rv;
}
// Set a buffer large enough to contain the initial CWND's worth of packet
// to work around the problem with CHLO packets being sent out with the
// wrong encryption level, when the send buffer is full.
rv = socket->SetSendBufferSize(kMaxPacketSize * 20);
if (rv != OK) {
HistogramCreateSessionFailure(CREATION_ERROR_SETTING_SEND_BUFFER);
return rv;
}
scoped_ptr<QuicDefaultPacketWriter> writer(
new QuicDefaultPacketWriter(socket.get()));
if (!helper_.get()) {
helper_.reset(new QuicConnectionHelper(
base::MessageLoop::current()->message_loop_proxy().get(),
clock_.get(), random_generator_));
}
QuicConnection* connection =
new QuicConnection(connection_id, addr, helper_.get(), writer.get(),
false, supported_versions_);
writer->SetConnection(connection);
connection->set_max_packet_length(max_packet_length_);
InitializeCachedStateInCryptoConfig(server_id, server_info);
QuicConfig config = config_;
config.SetInitialCongestionWindowToSend(
server_id.is_https() ? kServerSecureInitialCongestionWindow
: kServerInecureInitialCongestionWindow);
config.SetInitialFlowControlWindowToSend(kInitialReceiveWindowSize);
config.SetInitialStreamFlowControlWindowToSend(kInitialReceiveWindowSize);
config.SetInitialSessionFlowControlWindowToSend(kInitialReceiveWindowSize);
if (http_server_properties_) {
const HttpServerProperties::NetworkStats* stats =
http_server_properties_->GetServerNetworkStats(
server_id.host_port_pair());
if (stats != NULL) {
config.SetInitialRoundTripTimeUsToSend(stats->srtt.InMicroseconds());
}
}
*session = new QuicClientSession(
connection, socket.Pass(), writer.Pass(), this,
quic_crypto_client_stream_factory_, server_info.Pass(), server_id,
config, &crypto_config_,
base::MessageLoop::current()->message_loop_proxy().get(),
net_log.net_log());
all_sessions_[*session] = server_id; // owning pointer
return OK;
}
bool QuicStreamFactory::HasActiveJob(const QuicServerId& key) const {
return ContainsKey(active_jobs_, key);
}
void QuicStreamFactory::ActivateSession(
const QuicServerId& server_id,
QuicClientSession* session) {
DCHECK(!HasActiveSession(server_id));
UMA_HISTOGRAM_COUNTS("Net.QuicActiveSessions", active_sessions_.size());
active_sessions_[server_id] = session;
session_aliases_[session].insert(server_id);
const IpAliasKey ip_alias_key(session->connection()->peer_address(),
server_id.is_https());
DCHECK(!ContainsKey(ip_aliases_[ip_alias_key], session));
ip_aliases_[ip_alias_key].insert(session);
}
void QuicStreamFactory::InitializeCachedStateInCryptoConfig(
const QuicServerId& server_id,
const scoped_ptr<QuicServerInfo>& server_info) {
if (!server_info)
return;
QuicCryptoClientConfig::CachedState* cached =
crypto_config_.LookupOrCreate(server_id);
if (!cached->IsEmpty())
return;
if (!cached->Initialize(server_info->state().server_config,
server_info->state().source_address_token,
server_info->state().certs,
server_info->state().server_config_sig,
clock_->WallNow()))
return;
if (!server_id.is_https()) {
// Don't check the certificates for insecure QUIC.
cached->SetProofValid();
}
}
void QuicStreamFactory::ProcessGoingAwaySession(
QuicClientSession* session,
const QuicServerId& server_id,
bool session_was_active) {
if (!http_server_properties_)
return;
const QuicConnectionStats& stats = session->connection()->GetStats();
if (session->IsCryptoHandshakeConfirmed()) {
HttpServerProperties::NetworkStats network_stats;
network_stats.srtt = base::TimeDelta::FromMicroseconds(stats.srtt_us);
network_stats.bandwidth_estimate = stats.estimated_bandwidth;
http_server_properties_->SetServerNetworkStats(server_id.host_port_pair(),
network_stats);
return;
}
UMA_HISTOGRAM_COUNTS("Net.QuicHandshakeNotConfirmedNumPacketsReceived",
stats.packets_received);
if (!session_was_active)
return;
const HostPortPair& server = server_id.host_port_pair();
// Don't try to change the alternate-protocol state, if the
// alternate-protocol state is unknown.
if (!http_server_properties_->HasAlternateProtocol(server))
return;
// TODO(rch): In the special case where the session has received no
// packets from the peer, we should consider blacklisting this
// differently so that we still race TCP but we don't consider the
// session connected until the handshake has been confirmed.
HistogramBrokenAlternateProtocolLocation(
BROKEN_ALTERNATE_PROTOCOL_LOCATION_QUIC_STREAM_FACTORY);
PortAlternateProtocolPair alternate =
http_server_properties_->GetAlternateProtocol(server);
DCHECK_EQ(QUIC, alternate.protocol);
// Since the session was active, there's no longer an
// HttpStreamFactoryImpl::Job running which can mark it broken, unless the
// TCP job also fails. So to avoid not using QUIC when we otherwise could,
// we mark it as broken, and then immediately re-enable it. This leaves
// QUIC as "recently broken" which means that 0-RTT will be disabled but
// we'll still race.
http_server_properties_->SetBrokenAlternateProtocol(server);
http_server_properties_->ClearAlternateProtocol(server);
http_server_properties_->SetAlternateProtocol(
server, alternate.port, alternate.protocol);
DCHECK_EQ(QUIC,
http_server_properties_->GetAlternateProtocol(server).protocol);
DCHECK(http_server_properties_->WasAlternateProtocolRecentlyBroken(
server));
}
} // namespace net
| [
"chenming.eecs@pku.edu.cn"
] | chenming.eecs@pku.edu.cn |
1918cb6291fd4e38dcf6cf0851e449b0e53543f4 | 5740ea2c2d9d5fb5626ff5ad651f3789048ae86b | /PlasmaLibraries/Serialization/OldDataTreeParser.hpp | 0380bdab33ccf0345749d098d5a43b997159bd44 | [
"MIT"
] | permissive | donovan680/Plasma | 4945b92b7c6e642a557f12e05c7d53819186de55 | 51d40ef0669b7a3015f95e3c84c6d639d5469b62 | refs/heads/master | 2022-04-15T02:42:26.469268 | 2020-02-26T22:32:12 | 2020-02-26T22:32:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,936 | hpp | ////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// Authors: Joshua Claeys
/// Copyright 2016, DigiPen Institute of Technology
///
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Plasma
{
class DataNode;
struct DataTreeContext;
//------------------------------------------------------------ Data Tree Grammar
class DataTreeGrammar
{
public:
static DataTreeGrammar& GetInstance();
DataTreeGrammar();
// Tokenizer
GrammarSet<Character> mTokenGrammar;
GrammarRule<Character>* mTokenStart;
GrammarRule<Character>* mEnum;
GrammarRule<Character>* mIdentifier;
GrammarRule<Character>* mFloat;
GrammarRule<Character>* mInteger;
GrammarRule<Character>* mHex;
GrammarRule<Character>* mWhitespace;
GrammarRule<Character>* mStringLiteral;
GrammarRule<Character>* mTrue;
GrammarRule<Character>* mFalse;
GrammarRule<Character>* mVar;
// Parser
GrammarSet<Token> mParserGrammar;
GrammarRule<Token>* mParserStart;
GrammarRule<Token>* mObject;
GrammarRule<Token>* mAttribute;
GrammarRule<Token>* mProperty;
GrammarRule<Token>* mValue;
};
//------------------------------------------------------------- Data Tree Parser
class OldDataTreeParser
{
public:
static DataNode* BuildTree(DataTreeContext& context, StringRange data);
OldDataTreeParser();
/// Parser template interface.
void StartRule(GrammarRule<Token>* rule);
void EndRule(ParseNodeInfo<Token>* info);
void TokenParsed(ParseNodeInfo<Token>* info) {}
void StartParsing() {}
void EndParsing() {}
/// Set all flags on nodes based on the read in attributes.
void PostProcessAttributes(DataNode* node);
bool mOpenedProperty;
bool mAttributeStarted;
Array<DataNode*> mNodeStack;
bool mPropertyObject;
DataTreeContext* mContext;
DataNode* mLastEndedNode;
};
}//namespace Plasma
| [
"dragonCASTjosh@gmail.com"
] | dragonCASTjosh@gmail.com |
e2f3e32e8fc8cd12c0bae06a54c1165edf919a10 | 29dc7d8a031e7f686dc223d054cdd3ee62058371 | /Networking/Network/Src/MemoryStream.cpp | 6e64e31308cef98d46412476aef02df60b47265b | [] | no_license | teddysot/Engine | c4ca8503762570027662e28b4a4a7c6784bcbc3b | 2aaf6cdc566e7b83fd805998c708415882d288ae | refs/heads/master | 2020-04-07T21:31:30.938297 | 2018-11-22T18:00:57 | 2018-11-22T18:00:57 | 158,730,601 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,729 | cpp | //====================================================================================================
// Filename: MemoryStream.cpp
// Created by: Peter Chan
//====================================================================================================
#include "Precompiled.h"
#include "MemoryStream.h"
using namespace Network;
//----------------------------------------------------------------------------------------------------
MemoryStream::MemoryStream()
: mBuffer(nullptr)
, mHead(0)
, mCapacity(0)
{
}
//----------------------------------------------------------------------------------------------------
MemoryStream::MemoryStream(uint32_t capacity)
: mBuffer(nullptr)
, mHead(0)
, mCapacity(0)
{
ReallocBuffer(capacity);
}
//----------------------------------------------------------------------------------------------------
MemoryStream::MemoryStream(const uint8_t* data, uint32_t size, bool takeOwnership)
: mBuffer(nullptr)
, mHead(0)
, mCapacity(size)
{
if (takeOwnership)
{
mBuffer = const_cast<uint8_t*>(data);
}
else
{
mBuffer = static_cast<uint8_t*>(std::malloc(size));
memcpy(mBuffer, data, size);
}
}
//----------------------------------------------------------------------------------------------------
MemoryStream::~MemoryStream()
{
std::free(mBuffer);
}
//----------------------------------------------------------------------------------------------------
void MemoryStream::Reset()
{
mHead = 0;
}
//----------------------------------------------------------------------------------------------------
void MemoryStream::ReallocBuffer(uint32_t newCapacity)
{
mBuffer = static_cast<uint8_t*>(std::realloc(mBuffer, newCapacity));
mCapacity = newCapacity;
} | [
"earth_sot@hotmail.com"
] | earth_sot@hotmail.com |
6c6a5fd5de14e43e38cef7a7007f649fb01e95e0 | 745a45b6bcf85fe497fc1acd06ef0b68b934626a | /suif/suif2b/suifbrowser/visual/vtcl.h | 835c8fbebe7351d1cca1d31e82a6b5b4c4dfea2d | [] | no_license | jrk/suif2 | e7c9f5e644f30422f7735837734e34248115cd2c | 6f4dee1a906cfd00d3b57a7ead6f9fc807d7455d | refs/heads/master | 2021-01-23T11:54:36.487230 | 2011-03-23T03:18:28 | 2011-03-23T03:18:28 | 1,514,729 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,211 | h | #ifndef VTCL_H
#define VTCL_H
//#include <sty.h>
#include "common/suif_list.h"
#include "vcommands.h"
#include <tcl.h>
#include <tk.h>
#include <stdlib.h>
#include <string.h>
#include "suifkernel/suifkernel_messages.h"
/* globals */
extern Tcl_Interp *v_interp; // Visual interpreter
/*
* tcl command interface class
*
*/
#define COMMAND_INCREMENT_SIZE 500
class tcl_terminator {
};
extern tcl_terminator *tcl_end; // end of tcl command, will call tcl to
// interpret the command
extern char *tcl_0;
class tcl_command {
private:
char *command; // points to current tcl_command (or 0)
int end_command; // offset of the last valid element of string (the 0)
int end_reserved_space; // the first offset past the allocation area
// (all usable offsets have to be smaller)
Tcl_Interp *interp;
protected:
char* reserve_space( int size_to_reserve ) {
// space_remaining can be negative! (in the beginning)
int space_remaining = end_reserved_space - end_command - 1;
if ( size_to_reserve > space_remaining ) {
int increment_size = size_to_reserve < COMMAND_INCREMENT_SIZE ?
COMMAND_INCREMENT_SIZE : size_to_reserve;
end_reserved_space = end_reserved_space + increment_size;
if ( !command ) end_reserved_space++; // space for extra 0
char* new_space = new char[ end_reserved_space ];
// initialize the new string
if ( command ) {
strcpy( new_space, command );
} else {
assert( end_command == 0 );
new_space[0]=0;
}
delete [] command;
command = new_space;
}
suif_assert_message( ( command[end_command]==0 ), ("End of string must be 0" ));
return command+end_command;
}
void reset_string() {
delete [] command;
command = 0;
end_command = 0;
end_reserved_space = 0;
}
public:
tcl_command() {
command = 0;
reset_string();
interp = 0;
}
~tcl_command() {
reset_string();
}
void set_interp(Tcl_Interp *tcl_interp) {
interp = tcl_interp;
}
Tcl_Interp *get_interp(void) {
return interp;
}
/*
* create command
*/
void create_command(char *cmdName, Tcl_CmdProc *proc,
ClientData clientData,
Tcl_CmdDeleteProc *deleteProc) {
Tcl_CreateCommand(interp, cmdName, proc, clientData, deleteProc);
}
int link_var(char *varName, char *addr, int type) {
return (Tcl_LinkVar(interp, varName, addr, type));
}
void unlink_var(char *varName) {
Tcl_UnlinkVar(interp, varName);
}
/*
* Evaluating tcl command
*
*/
int operator << (const tcl_terminator *) {
assert( command );
// ATTENTION: This might be invoked recursively!!
// => reinitialize this object before invoking eval
char* current_command = command;
command = 0;
reset_string();
int result = eval( current_command );
delete [] current_command;
return result;
}
tcl_command &operator << (const char *string) {
int length = strlen( string );
char* start = reserve_space( length );
sprintf( start, "{%s} ", string);
end_command += length + 3;
return *this;
}
tcl_command &operator << (const void *data) {
const int buffer_size = 20;
char buffer[ buffer_size ];
sprintf( buffer, "%p ", data );
int len = strlen( buffer );
suif_assert_message( (len<=buffer_size), ("Pointer to string conversion has unexpected size (too large).\n") );
strcat( reserve_space( len ), buffer );
end_command += len;
return *this;
}
tcl_command &operator << (int data) {
const int buffer_size = 40;
char buffer[ buffer_size ];
sprintf( buffer, "%d ", data );
int len = strlen( buffer );
suif_assert_message(( len<=buffer_size), ("Int to string conversion has unexpected size (too large).\n" ));
strcat( reserve_space( len ), buffer );
end_command += len;
return *this;
}
tcl_command &operator << ( double data ) {
const int buffer_size = 40;
char buffer[ buffer_size ];
sprintf( buffer, "%f ", data );
int len = strlen( buffer );
suif_assert_message( (len<=buffer_size), ("Double to string conversion has unexpected size (too large).\n") );
strcat( reserve_space( len ), buffer );
end_command += len;
return *this;
}
int eval(char *string) {
int result = Tcl_Eval(interp, string);
if (result != TCL_OK) {
v_warning("Tcl command `%s': (%d) %s",
string, result, interp->result);
}
return result;
}
int eval_file(char *filename) {
return (Tcl_EvalFile(interp, filename));
}
/*
* Get results from tcl
*/
int operator >> (int &data) {
data = atoi(interp->result);
return TCL_OK;
}
int operator >> (char *&data) {
strcpy(data, interp->result);
return TCL_OK;
}
int operator >> (void *&data) {
if (sscanf(interp->result, "%p", &data) != 1) {
return TCL_ERROR;
} else {
return TCL_OK;
}
}
char *result() {
return interp->result;
}
/*
* Misc
*/
void print(FILE *fd = stdout) {
fprintf(fd, "%s\n", command ? command : "<NO COMMAND>");
}
};
extern tcl_command tcl;
#endif
| [
"jrk@csail.mit.edu"
] | jrk@csail.mit.edu |
762fb49da685c868d046e7de42cd53aefce10d80 | 814fd0bea5bc063a4e34ebdd0a5597c9ff67532b | /content/child/web_gesture_curve_impl.cc | da8a18cecaf9e1b34016c612f07ac35af0ac53a1 | [
"BSD-3-Clause"
] | permissive | rzr/chromium-crosswalk | 1b22208ff556d69c009ad292bc17dca3fe15c493 | d391344809adf7b4f39764ac0e15c378169b805f | refs/heads/master | 2021-01-21T09:11:07.316526 | 2015-02-16T11:52:21 | 2015-02-16T11:52:21 | 38,887,985 | 0 | 0 | NOASSERTION | 2019-08-07T21:59:20 | 2015-07-10T15:35:50 | C++ | UTF-8 | C++ | false | false | 4,749 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/child/web_gesture_curve_impl.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "third_party/WebKit/public/platform/WebFloatSize.h"
#include "third_party/WebKit/public/platform/WebGestureCurveTarget.h"
#include "ui/events/gestures/fling_curve.h"
#include "ui/gfx/geometry/safe_integer_conversions.h"
#include "ui/gfx/geometry/vector2d.h"
#if defined(OS_ANDROID)
#include "ui/events/android/scroller.h"
#endif
using blink::WebGestureCurve;
namespace content {
namespace {
scoped_ptr<ui::GestureCurve> CreateDefaultPlatformCurve(
const gfx::Vector2dF& initial_velocity) {
DCHECK(!initial_velocity.IsZero());
#if defined(OS_ANDROID)
auto scroller = make_scoped_ptr(new ui::Scroller(ui::Scroller::Config()));
scroller->Fling(0,
0,
initial_velocity.x(),
initial_velocity.y(),
INT_MIN,
INT_MAX,
INT_MIN,
INT_MAX,
base::TimeTicks());
return scroller.Pass();
#else
return make_scoped_ptr(
new ui::FlingCurve(initial_velocity, base::TimeTicks()));
#endif
}
} // namespace
// static
scoped_ptr<WebGestureCurve> WebGestureCurveImpl::CreateFromDefaultPlatformCurve(
const gfx::Vector2dF& initial_velocity,
const gfx::Vector2dF& initial_offset,
bool on_main_thread) {
return scoped_ptr<WebGestureCurve>(new WebGestureCurveImpl(
CreateDefaultPlatformCurve(initial_velocity), initial_offset,
on_main_thread ? ThreadType::MAIN : ThreadType::IMPL));
}
// static
scoped_ptr<WebGestureCurve> WebGestureCurveImpl::CreateFromUICurveForTesting(
scoped_ptr<ui::GestureCurve> curve,
const gfx::Vector2dF& initial_offset) {
return scoped_ptr<WebGestureCurve>(
new WebGestureCurveImpl(curve.Pass(), initial_offset, ThreadType::TEST));
}
WebGestureCurveImpl::WebGestureCurveImpl(scoped_ptr<ui::GestureCurve> curve,
const gfx::Vector2dF& initial_offset,
ThreadType animating_thread_type)
: curve_(curve.Pass()),
last_offset_(initial_offset),
animating_thread_type_(animating_thread_type),
ticks_since_first_animate_(0),
first_animate_time_(0),
last_animate_time_(0) {
}
WebGestureCurveImpl::~WebGestureCurveImpl() {
if (ticks_since_first_animate_ <= 1)
return;
if (last_animate_time_ <= first_animate_time_)
return;
switch (animating_thread_type_) {
case ThreadType::MAIN:
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Event.Frequency.Renderer.FlingAnimate",
gfx::ToRoundedInt(ticks_since_first_animate_ /
(last_animate_time_ - first_animate_time_)),
1, 240, 120);
break;
case ThreadType::IMPL:
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Event.Frequency.RendererImpl.FlingAnimate",
gfx::ToRoundedInt(ticks_since_first_animate_ /
(last_animate_time_ - first_animate_time_)),
1, 240, 120);
break;
case ThreadType::TEST:
break;
}
}
bool WebGestureCurveImpl::apply(double time,
blink::WebGestureCurveTarget* target) {
// If the fling has yet to start, simply return and report true to prevent
// fling termination.
if (time <= 0)
return true;
if (!first_animate_time_) {
first_animate_time_ = last_animate_time_ = time;
} else if (time != last_animate_time_) {
// Animation can occur multiple times a frame, but with the same timestamp.
// Suppress recording of such redundant animate calls, avoiding artificially
// inflated FPS computation.
last_animate_time_ = time;
++ticks_since_first_animate_;
}
const base::TimeTicks time_ticks =
base::TimeTicks() + base::TimeDelta::FromSecondsD(time);
gfx::Vector2dF offset, velocity;
bool still_active =
curve_->ComputeScrollOffset(time_ticks, &offset, &velocity);
gfx::Vector2dF delta = offset - last_offset_;
last_offset_ = offset;
// As successive timestamps can be arbitrarily close (but monotonic!), don't
// assume that a zero delta means the curve has terminated.
if (delta.IsZero())
return still_active;
// scrollBy() could delete this curve if the animation is over, so don't touch
// any member variables after making that call.
bool did_scroll = target->scrollBy(blink::WebFloatSize(delta),
blink::WebFloatSize(velocity));
return did_scroll && still_active;
}
} // namespace content
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
22e6d2846ed6bcd8b03f459713a13d189e46ec41 | ccfe4094847ca44b9cd3e2b747964b1063132355 | /C++/hw5_10.cpp | 73b9f9320ef4f407e04bde517115443bba60369f | [] | no_license | dils12001/C_Practice | 53fdee47a17e0c0e69ff01318cdd727fa2dab291 | c80d6698c048eb03dfef0bf52b5f1faaaaf26272 | refs/heads/master | 2023-08-01T00:13:16.521740 | 2021-09-04T11:23:14 | 2021-09-04T11:23:14 | 403,036,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 479 | cpp | #include <iostream>
int main()
{
using namespace std;
cout << "Enter number of rows: ";
int num;
cin >> num;
for(int row = 1;row <= num;row++)
{
for(int col = 1;col <= num;col++)
{
if(col == num)
cout << "*\n";
else if(col > (num-row))
cout << "*";
else
cout << ".";
}
}
cout << "\n\n\n";
for(int i = 0;i < num;i++)
{
int j = 0;
for(;j < (num-i-1);j++)
cout << ".";
for(;j < num;j++)
cout << "*";
cout << "\n";
}
} | [
"dils210293@gmail.com"
] | dils210293@gmail.com |
64178d56059f9b8209762d8ceeec9448faedb734 | 0b6aa7ce3ea19c3f7fcac64daa9857ef4e13d6fd | /cncState.hh | 40e3c5b027f1580bcacd21817423683ebd65945f | [] | no_license | lumpyh/LHCNC | 23b2903cd10a516684b631b606febfbcdb605414 | 42ea14ef5dce4a4593afe171b449433c837ab1e0 | refs/heads/master | 2020-12-12T13:59:27.599846 | 2016-11-26T20:57:47 | 2016-11-26T20:57:47 | 51,971,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 479 | hh | #ifndef CNCSTATE_HH
#define CNCSTATE_HH
#include "point.hh"
class cncState{
public:
cncState();
bool isAbsolute();
bool isInMill();
int getStepsPerMill();
const point<int>& getStepPos();
const point<double>& getPos();
void setAbsolute( bool);
void setInMill( bool);
void setStepPos( int, int, int);
void setPos( double, double, double);
private:
bool absolute;
bool inMill;
int stepsPerMill;
point<int> stepPos;
point<double> pos;
};
#endif
| [
"lumpy.hega@gmx.de"
] | lumpy.hega@gmx.de |
5037069d4dc20035675ca6de3d82c9ae48dfe2b9 | 94e5a9e157d3520374d95c43fe6fec97f1fc3c9b | /@DOC by DIPTA/dipta007_final/Max-flow/sgtlaugh-mincost-maxflow(Dijkstra+Potentials).cpp | 8f67f28fd32f68b1cfad3425cc05e0b5eb0fb158 | [
"MIT"
] | permissive | dipta007/Competitive-Programming | 0127c550ad523884a84eb3ea333d08de8b4ba528 | 998d47f08984703c5b415b98365ddbc84ad289c4 | refs/heads/master | 2021-01-21T14:06:40.082553 | 2020-07-06T17:40:46 | 2020-07-06T17:40:46 | 54,851,014 | 8 | 4 | null | 2020-05-02T13:14:41 | 2016-03-27T22:30:02 | C++ | UTF-8 | C++ | false | false | 2,864 | cpp | #include <stdio.h>
#include <bits/stdtr1c++.h>
#define MAX 200010 /// 2 * max(nodes, edges)
#define clr(ar) memset(ar, 0, sizeof(ar))
#define read() freopen("lol.txt", "r", stdin)
#define dbg(x) cout << #x << " = " << x << endl
#define ran(a, b) ((((rand() << 15) ^ rand()) % ((b) - (a) + 1)) + (a))
using namespace std;
/// Min-cost Max-flow using dijkstra with potentials
/// 0 Based indexed for directed weighted graphs (for undirected graphs, just add two directed edges)
/// Runs in around 2 seconds when n <= 200 and m = n * (n - 1) / 2
/// Runs well for sparse graphs though, e.g, m <= 10 * n
/// Costs must be non-negative
namespace mcmf{
const long long INF = 1LL << 60;
long long potential[MAX], dis[MAX], cap[MAX], cost[MAX];
int n, m, s, t, to[MAX], from[MAX], last[MAX], next[MAX], adj[MAX];
struct compare{
inline bool operator()(int a, int b){
if (dis[a] == dis[b]) return (a < b);
return (dis[a] < dis[b]);
}
};
set<int, compare> S;
void init(int nodes, int source, int sink){
m = 0, n = nodes;
s = source, t = sink;
for (int i = 0; i <= n; i++) potential[i] = 0, last[i] = -1;
}
/// u -> v, capacity, cost
void addEdge(int u, int v, long long c, long long w){
from[m] = u, adj[m] = v, cap[m] = c, cost[m] = w, next[m] = last[u], last[u] = m++;
from[m] = v, adj[m] = u, cap[m] = 0, cost[m] = -w, next[m] = last[v], last[v] = m++;
}
pair<long long, long long> solve(){
int i, j, e, u, v;
long long w, aug = 0, mincost = 0, maxflow = 0;
while (1){
S.clear();
for (i = 0; i < n; i++) dis[i] = INF;
dis[s] = 0, S.insert(s);
while (!S.empty()){
u = *(S.begin());
if (u == t) break;
S.erase(S.begin());
for (e = last[u]; e != -1; e = next[e]){
if (cap[e] != 0){
v = adj[e];
w = dis[u] + potential[u] + cost[e] - potential[v];
if (dis[v] > w){
S.erase(v);
dis[v] = w, to[v] = e;
S.insert(v);
}
}
}
}
if (dis[t] >= (INF >> 1)) break;
aug = cap[to[t]];
for (i = t; i != s; i = from[to[i]]) aug = min(aug, cap[to[i]]);
for (i = t; i != s; i = from[to[i]]){
cap[to[i]] -= aug;
cap[to[i] ^ 1] += aug;
mincost += (cost[to[i]] * aug);
}
for (i = 0; i <= n; i++) potential[i] = min(potential[i] + dis[i], INF);
maxflow += aug;
}
return make_pair(mincost, maxflow);
}
}
int main(){
}
| [
"iamdipta@gmail.com"
] | iamdipta@gmail.com |
2ece42c1d4ae91578b1e5312f9a8ff8b3ffc9856 | d3289431cb91bcb55edefee17ab4168a80392cef | /Minos/Game/InputReplay.h | 0de6cd75a0c46d777bfb7a3d85fe99d63f1151f4 | [] | no_license | Sumez/Minos | fd6071f6f5fcf46d9418f4961e9b0cb9275970f2 | f7584657856b28388a41a68a6c62c5ac002521e1 | refs/heads/master | 2021-01-19T05:29:38.606819 | 2016-07-05T13:58:45 | 2016-07-05T13:58:45 | 61,880,163 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | h | #pragma once
#include <inttypes.h>
#include "../InputHandler.h"
class InputReplay : public InputHandler {
public:
InputReplay(std::vector<int>& recording);
virtual Coords GetMouseCoords();
virtual bool IsHolding(ControlButton button);
virtual bool JustPressed(ControlButton button);
virtual bool WasMouseButtonClicked(MouseButton button);
virtual bool IsMouseButtonHeld(MouseButton button);
virtual void BindControl(ControlButton button);
virtual void CancelBind();
virtual bool IsWaitingForBind(ControlButton button) { return false; }
virtual std::string GetInputFor(ControlButton button);
virtual void AdvanceFrame();
virtual void BeginRecording();
virtual std::vector<int>& GetRecording() { return _recording; };
private:
void ProcessInput();
uint64_t _pointer = 0;
uint64_t _frame = 0;
std::vector<int>& _recording;
}; | [
"morten@eternal.dk"
] | morten@eternal.dk |
0c9bc57859f194698df7543260efaf70cf289d54 | e4df4dd3c33ecb4b04b433330c0dbe3fcf7c5c4e | /AStar/UI/UIManager.h | 7f2d9619ba686a9cc47128bc164d000e201fdabd | [] | no_license | soelusoelu/AStar | 0b0d9dc0021c940b45bc36d04c858f86c7b134a4 | c8006ecf0e6c54340f1a9586ad43bf80c8973047 | refs/heads/master | 2020-11-24T07:51:06.623562 | 2019-12-14T14:43:28 | 2019-12-14T14:43:28 | 228,038,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | h | #pragma once
#include "../Utility/IManager.h"
#include <list>
#include <memory>
class UI;
class UIManager : public IManager<UI> {
public:
UIManager();
~UIManager();
virtual void update() override;
virtual void draw() const override;
void add(UI* add);
virtual void remove() override;
virtual void clear() override;
private:
UIManager(const UIManager&) = delete;
UIManager& operator=(const UIManager&) = delete;
private:
std::list<std::unique_ptr<UI>> mUIStack;
};
| [
"llmn.0419@gmail.com"
] | llmn.0419@gmail.com |
62a62f70f7dc2c66e011312594ee24329e8aedff | ae956d4076e4fc03b632a8c0e987e9ea5ca89f56 | /SDK/TBP_UI_Quest_Objective_Notification_Item_functions.cpp | c8c3277f475af07bf35576662f13557157ddaee3 | [] | no_license | BrownBison/Bloodhunt-BASE | 5c79c00917fcd43c4e1932bee3b94e85c89b6bc7 | 8ae1104b748dd4b294609717142404066b6bc1e6 | refs/heads/main | 2023-08-07T12:04:49.234272 | 2021-10-02T15:13:42 | 2021-10-02T15:13:42 | 638,649,990 | 1 | 0 | null | 2023-05-09T20:02:24 | 2023-05-09T20:02:23 | null | UTF-8 | C++ | false | false | 3,116 | cpp | // Name: bbbbbbbbbbbbbbbbbbbbbbblod, Version: 1
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_UI_Quest_Objective_Notification_Item.TBP_UI_Quest_Objective_Notification_Item_C.SetupDataFromQuestObjective
// Flags -> (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UTigerQuestObjective* TigerQuestObjective (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_UI_Quest_Objective_Notification_Item_C::SetupDataFromQuestObjective(class UTigerQuestObjective* TigerQuestObjective)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_UI_Quest_Objective_Notification_Item.TBP_UI_Quest_Objective_Notification_Item_C.SetupDataFromQuestObjective");
UTBP_UI_Quest_Objective_Notification_Item_C_SetupDataFromQuestObjective_Params params;
params.TigerQuestObjective = TigerQuestObjective;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_UI_Quest_Objective_Notification_Item.TBP_UI_Quest_Objective_Notification_Item_C.Construct
// Flags -> (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UTBP_UI_Quest_Objective_Notification_Item_C::Construct()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_UI_Quest_Objective_Notification_Item.TBP_UI_Quest_Objective_Notification_Item_C.Construct");
UTBP_UI_Quest_Objective_Notification_Item_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x016C0340
// Name -> Function TBP_UI_Quest_Objective_Notification_Item.TBP_UI_Quest_Objective_Notification_Item_C.ExecuteUbergraph_TBP_UI_Quest_Objective_Notification_Item
// Flags -> (Final)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UTBP_UI_Quest_Objective_Notification_Item_C::ExecuteUbergraph_TBP_UI_Quest_Objective_Notification_Item(int EntryPoint)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_UI_Quest_Objective_Notification_Item.TBP_UI_Quest_Objective_Notification_Item_C.ExecuteUbergraph_TBP_UI_Quest_Objective_Notification_Item");
UTBP_UI_Quest_Objective_Notification_Item_C_ExecuteUbergraph_TBP_UI_Quest_Objective_Notification_Item_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"69031575+leoireo@users.noreply.github.com"
] | 69031575+leoireo@users.noreply.github.com |
985ccc1b83815dad8fdd35a710ad2b7a858ef987 | 6cdd54e4a9f02b49f8bbc03a67a5722e33f66d52 | /lab/3-4.cc | 2cb2fdce2dae8d85df3755d80f4ba1efd804dfbe | [] | no_license | dr3w-an/oop-studies | 17284e63f112d829377af9950d0cb1438da991bf | eb61168d6a1b411f8243daca52c79605fbc7f65f | refs/heads/master | 2021-07-13T14:54:14.420686 | 2019-06-29T01:27:24 | 2019-06-29T01:27:24 | 172,923,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,562 | cc | #include <iostream>
#include <math.h>
class Vector {
public:
double x, y;
double abs() {
return sqrt(pow(x, 2) + pow(y, 2));
}
Vector add(Vector vector) {
Vector result;
result.x = x + vector.x;
result.y = y + vector.y;
return result;
}
Vector substract(Vector vector) {
Vector result;
result.x = x - vector.x;
result.y = y - vector.y;
return result;
}
};
int main() {
Vector first_vector;
std::cout << "Введите абсциссу первого вектора: ";
std::cin >> first_vector.x;
std::cout << "Введите ординату первого вектора: ";
std::cin >> first_vector.y;
Vector second_vector;
std::cout << "Введите абсциссу второго вектора: ";
std::cin >> second_vector.x;
std::cout << "Введите ординату второго вектора: ";
std::cin >> second_vector.y;
Vector sum = first_vector.add(second_vector);
Vector dif = first_vector.substract(second_vector);
std::cout << "Модуль первого вектора: " << first_vector.abs() << '\n'
<< "Модуль второго вектора: " << second_vector.abs() << '\n'
<< "Сумма векторов: (" << sum.x << ", " << sum.y << ")\n"
<< "Разность векторов: (" << dif.x << ", " << dif.y << ')' << std::endl;
return 0;
}
| [
"dr3w.an@yandex.ru"
] | dr3w.an@yandex.ru |
93706c34197a3eee316994c0147cc89074f20c82 | 67d0fb30fb385791af1d6a0ae6187ef0a7991eff | /ABC037/a.cpp | 4d6b058fb5128a6cab04c80f48aed4e346e801af | [] | no_license | misogi/atcoder | a5e4b221747bdcae8c32b9f1f59bebf065200285 | d9dff5905bfcfae6113ccfbe710a2dee88906d9f | refs/heads/master | 2021-01-19T03:47:21.139037 | 2017-02-21T09:24:36 | 2017-02-21T09:24:36 | 48,310,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 229 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main() {
int a, b, mo;
cin >> a >> b >> mo;
int num;
if (a < b) {
num = mo / a;
} else {
num = mo / b;
}
cout << num << endl;
return 0;
}
| [
"dev@misogi.info"
] | dev@misogi.info |
634430ac808278d348753fe694518e2b6efb7068 | 2cf838b54b556987cfc49f42935f8aa7563ea1f4 | /aws-cpp-sdk-ivs/include/aws/ivs/model/UpdateChannelRequest.h | 88dfe35dd3bd32d7a765824490d3816354b97eac | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | QPC-database/aws-sdk-cpp | d11e9f0ff6958c64e793c87a49f1e034813dac32 | 9f83105f7e07fe04380232981ab073c247d6fc85 | refs/heads/main | 2023-06-14T17:41:04.817304 | 2021-07-09T20:28:20 | 2021-07-09T20:28:20 | 384,714,703 | 1 | 0 | Apache-2.0 | 2021-07-10T14:16:41 | 2021-07-10T14:16:41 | null | UTF-8 | C++ | false | false | 15,290 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ivs/IVS_EXPORTS.h>
#include <aws/ivs/IVSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ivs/model/ChannelLatencyMode.h>
#include <aws/ivs/model/ChannelType.h>
#include <utility>
namespace Aws
{
namespace IVS
{
namespace Model
{
/**
*/
class AWS_IVS_API UpdateChannelRequest : public IVSRequest
{
public:
UpdateChannelRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "UpdateChannel"; }
Aws::String SerializePayload() const override;
/**
* <p>ARN of the channel to be updated.</p>
*/
inline const Aws::String& GetArn() const{ return m_arn; }
/**
* <p>ARN of the channel to be updated.</p>
*/
inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }
/**
* <p>ARN of the channel to be updated.</p>
*/
inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }
/**
* <p>ARN of the channel to be updated.</p>
*/
inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }
/**
* <p>ARN of the channel to be updated.</p>
*/
inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }
/**
* <p>ARN of the channel to be updated.</p>
*/
inline UpdateChannelRequest& WithArn(const Aws::String& value) { SetArn(value); return *this;}
/**
* <p>ARN of the channel to be updated.</p>
*/
inline UpdateChannelRequest& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}
/**
* <p>ARN of the channel to be updated.</p>
*/
inline UpdateChannelRequest& WithArn(const char* value) { SetArn(value); return *this;}
/**
* <p>Channel name.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>Channel name.</p>
*/
inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }
/**
* <p>Channel name.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>Channel name.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }
/**
* <p>Channel name.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>Channel name.</p>
*/
inline UpdateChannelRequest& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>Channel name.</p>
*/
inline UpdateChannelRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}
/**
* <p>Channel name.</p>
*/
inline UpdateChannelRequest& WithName(const char* value) { SetName(value); return *this;}
/**
* <p>Channel latency mode. Use <code>NORMAL</code> to broadcast and deliver live
* video up to Full HD. Use <code>LOW</code> for near-real-time interaction with
* viewers. (Note: In the Amazon IVS console, <code>LOW</code> and
* <code>NORMAL</code> correspond to Ultra-low and Standard, respectively.)</p>
*/
inline const ChannelLatencyMode& GetLatencyMode() const{ return m_latencyMode; }
/**
* <p>Channel latency mode. Use <code>NORMAL</code> to broadcast and deliver live
* video up to Full HD. Use <code>LOW</code> for near-real-time interaction with
* viewers. (Note: In the Amazon IVS console, <code>LOW</code> and
* <code>NORMAL</code> correspond to Ultra-low and Standard, respectively.)</p>
*/
inline bool LatencyModeHasBeenSet() const { return m_latencyModeHasBeenSet; }
/**
* <p>Channel latency mode. Use <code>NORMAL</code> to broadcast and deliver live
* video up to Full HD. Use <code>LOW</code> for near-real-time interaction with
* viewers. (Note: In the Amazon IVS console, <code>LOW</code> and
* <code>NORMAL</code> correspond to Ultra-low and Standard, respectively.)</p>
*/
inline void SetLatencyMode(const ChannelLatencyMode& value) { m_latencyModeHasBeenSet = true; m_latencyMode = value; }
/**
* <p>Channel latency mode. Use <code>NORMAL</code> to broadcast and deliver live
* video up to Full HD. Use <code>LOW</code> for near-real-time interaction with
* viewers. (Note: In the Amazon IVS console, <code>LOW</code> and
* <code>NORMAL</code> correspond to Ultra-low and Standard, respectively.)</p>
*/
inline void SetLatencyMode(ChannelLatencyMode&& value) { m_latencyModeHasBeenSet = true; m_latencyMode = std::move(value); }
/**
* <p>Channel latency mode. Use <code>NORMAL</code> to broadcast and deliver live
* video up to Full HD. Use <code>LOW</code> for near-real-time interaction with
* viewers. (Note: In the Amazon IVS console, <code>LOW</code> and
* <code>NORMAL</code> correspond to Ultra-low and Standard, respectively.)</p>
*/
inline UpdateChannelRequest& WithLatencyMode(const ChannelLatencyMode& value) { SetLatencyMode(value); return *this;}
/**
* <p>Channel latency mode. Use <code>NORMAL</code> to broadcast and deliver live
* video up to Full HD. Use <code>LOW</code> for near-real-time interaction with
* viewers. (Note: In the Amazon IVS console, <code>LOW</code> and
* <code>NORMAL</code> correspond to Ultra-low and Standard, respectively.)</p>
*/
inline UpdateChannelRequest& WithLatencyMode(ChannelLatencyMode&& value) { SetLatencyMode(std::move(value)); return *this;}
/**
* <p>Channel type, which determines the allowable resolution and bitrate. <i>If
* you exceed the allowable resolution or bitrate, the stream probably will
* disconnect immediately</i>. Valid values:</p> <ul> <li> <p>
* <code>STANDARD</code>: Multiple qualities are generated from the original input,
* to automatically give viewers the best experience for their devices and network
* conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5
* Mbps.</p> </li> <li> <p> <code>BASIC</code>: Amazon IVS delivers the original
* input to viewers. The viewer’s video-quality choice is limited to the original
* input. Vertical resolution can be up to 480 and bitrate can be up to 1.5
* Mbps.</p> </li> </ul>
*/
inline const ChannelType& GetType() const{ return m_type; }
/**
* <p>Channel type, which determines the allowable resolution and bitrate. <i>If
* you exceed the allowable resolution or bitrate, the stream probably will
* disconnect immediately</i>. Valid values:</p> <ul> <li> <p>
* <code>STANDARD</code>: Multiple qualities are generated from the original input,
* to automatically give viewers the best experience for their devices and network
* conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5
* Mbps.</p> </li> <li> <p> <code>BASIC</code>: Amazon IVS delivers the original
* input to viewers. The viewer’s video-quality choice is limited to the original
* input. Vertical resolution can be up to 480 and bitrate can be up to 1.5
* Mbps.</p> </li> </ul>
*/
inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }
/**
* <p>Channel type, which determines the allowable resolution and bitrate. <i>If
* you exceed the allowable resolution or bitrate, the stream probably will
* disconnect immediately</i>. Valid values:</p> <ul> <li> <p>
* <code>STANDARD</code>: Multiple qualities are generated from the original input,
* to automatically give viewers the best experience for their devices and network
* conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5
* Mbps.</p> </li> <li> <p> <code>BASIC</code>: Amazon IVS delivers the original
* input to viewers. The viewer’s video-quality choice is limited to the original
* input. Vertical resolution can be up to 480 and bitrate can be up to 1.5
* Mbps.</p> </li> </ul>
*/
inline void SetType(const ChannelType& value) { m_typeHasBeenSet = true; m_type = value; }
/**
* <p>Channel type, which determines the allowable resolution and bitrate. <i>If
* you exceed the allowable resolution or bitrate, the stream probably will
* disconnect immediately</i>. Valid values:</p> <ul> <li> <p>
* <code>STANDARD</code>: Multiple qualities are generated from the original input,
* to automatically give viewers the best experience for their devices and network
* conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5
* Mbps.</p> </li> <li> <p> <code>BASIC</code>: Amazon IVS delivers the original
* input to viewers. The viewer’s video-quality choice is limited to the original
* input. Vertical resolution can be up to 480 and bitrate can be up to 1.5
* Mbps.</p> </li> </ul>
*/
inline void SetType(ChannelType&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }
/**
* <p>Channel type, which determines the allowable resolution and bitrate. <i>If
* you exceed the allowable resolution or bitrate, the stream probably will
* disconnect immediately</i>. Valid values:</p> <ul> <li> <p>
* <code>STANDARD</code>: Multiple qualities are generated from the original input,
* to automatically give viewers the best experience for their devices and network
* conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5
* Mbps.</p> </li> <li> <p> <code>BASIC</code>: Amazon IVS delivers the original
* input to viewers. The viewer’s video-quality choice is limited to the original
* input. Vertical resolution can be up to 480 and bitrate can be up to 1.5
* Mbps.</p> </li> </ul>
*/
inline UpdateChannelRequest& WithType(const ChannelType& value) { SetType(value); return *this;}
/**
* <p>Channel type, which determines the allowable resolution and bitrate. <i>If
* you exceed the allowable resolution or bitrate, the stream probably will
* disconnect immediately</i>. Valid values:</p> <ul> <li> <p>
* <code>STANDARD</code>: Multiple qualities are generated from the original input,
* to automatically give viewers the best experience for their devices and network
* conditions. Vertical resolution can be up to 1080 and bitrate can be up to 8.5
* Mbps.</p> </li> <li> <p> <code>BASIC</code>: Amazon IVS delivers the original
* input to viewers. The viewer’s video-quality choice is limited to the original
* input. Vertical resolution can be up to 480 and bitrate can be up to 1.5
* Mbps.</p> </li> </ul>
*/
inline UpdateChannelRequest& WithType(ChannelType&& value) { SetType(std::move(value)); return *this;}
/**
* <p>Whether the channel is private (enabled for playback authorization).</p>
*/
inline bool GetAuthorized() const{ return m_authorized; }
/**
* <p>Whether the channel is private (enabled for playback authorization).</p>
*/
inline bool AuthorizedHasBeenSet() const { return m_authorizedHasBeenSet; }
/**
* <p>Whether the channel is private (enabled for playback authorization).</p>
*/
inline void SetAuthorized(bool value) { m_authorizedHasBeenSet = true; m_authorized = value; }
/**
* <p>Whether the channel is private (enabled for playback authorization).</p>
*/
inline UpdateChannelRequest& WithAuthorized(bool value) { SetAuthorized(value); return *this;}
/**
* <p>Recording-configuration ARN. If this is set to an empty string, recording is
* disabled. A value other than an empty string indicates that recording is
* enabled</p>
*/
inline const Aws::String& GetRecordingConfigurationArn() const{ return m_recordingConfigurationArn; }
/**
* <p>Recording-configuration ARN. If this is set to an empty string, recording is
* disabled. A value other than an empty string indicates that recording is
* enabled</p>
*/
inline bool RecordingConfigurationArnHasBeenSet() const { return m_recordingConfigurationArnHasBeenSet; }
/**
* <p>Recording-configuration ARN. If this is set to an empty string, recording is
* disabled. A value other than an empty string indicates that recording is
* enabled</p>
*/
inline void SetRecordingConfigurationArn(const Aws::String& value) { m_recordingConfigurationArnHasBeenSet = true; m_recordingConfigurationArn = value; }
/**
* <p>Recording-configuration ARN. If this is set to an empty string, recording is
* disabled. A value other than an empty string indicates that recording is
* enabled</p>
*/
inline void SetRecordingConfigurationArn(Aws::String&& value) { m_recordingConfigurationArnHasBeenSet = true; m_recordingConfigurationArn = std::move(value); }
/**
* <p>Recording-configuration ARN. If this is set to an empty string, recording is
* disabled. A value other than an empty string indicates that recording is
* enabled</p>
*/
inline void SetRecordingConfigurationArn(const char* value) { m_recordingConfigurationArnHasBeenSet = true; m_recordingConfigurationArn.assign(value); }
/**
* <p>Recording-configuration ARN. If this is set to an empty string, recording is
* disabled. A value other than an empty string indicates that recording is
* enabled</p>
*/
inline UpdateChannelRequest& WithRecordingConfigurationArn(const Aws::String& value) { SetRecordingConfigurationArn(value); return *this;}
/**
* <p>Recording-configuration ARN. If this is set to an empty string, recording is
* disabled. A value other than an empty string indicates that recording is
* enabled</p>
*/
inline UpdateChannelRequest& WithRecordingConfigurationArn(Aws::String&& value) { SetRecordingConfigurationArn(std::move(value)); return *this;}
/**
* <p>Recording-configuration ARN. If this is set to an empty string, recording is
* disabled. A value other than an empty string indicates that recording is
* enabled</p>
*/
inline UpdateChannelRequest& WithRecordingConfigurationArn(const char* value) { SetRecordingConfigurationArn(value); return *this;}
private:
Aws::String m_arn;
bool m_arnHasBeenSet;
Aws::String m_name;
bool m_nameHasBeenSet;
ChannelLatencyMode m_latencyMode;
bool m_latencyModeHasBeenSet;
ChannelType m_type;
bool m_typeHasBeenSet;
bool m_authorized;
bool m_authorizedHasBeenSet;
Aws::String m_recordingConfigurationArn;
bool m_recordingConfigurationArnHasBeenSet;
};
} // namespace Model
} // namespace IVS
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
3273c04a0879ed79906355ca1c57d94978013b59 | 94415be920d27a4e875e6f34a730edef398c8e24 | /Chapter6/Chapter6/Game.h | 1594c6527c04215dcc229b0fff4b843868ce54be | [
"BSD-3-Clause"
] | permissive | maato-origin/OpenGLPractice | d55a205fef582ebeebaf9e9eb7794350c2854e66 | 9769570f2d23ffbd857681752b5bd7dd10879507 | refs/heads/master | 2022-01-10T18:06:15.252712 | 2019-06-17T07:15:56 | 2019-06-17T07:15:56 | 188,250,436 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 879 | h | #pragma once
#include "SDL/SDL.h"
#include <unordered_map>
#include <string>
#include <vector>
#include "Math.h"
class Game
{
public:
Game();
bool Initialize();
void RunLoop();
void Shutdown();
void AddActor(class Actor* actor);
void RemoveActor(class Actor* actor);
void AddSprite(class SpriteComponent* sprite);
void RemoveSprite(class SpriteComponent* sprite);
class Renderer* GetRenderer() { return mRenderer; }
private:
void ProcessInput();
void UpdateGame();
void GenerateOutput();
void LoadData();
void UnloadData();
//ゲーム内の全てのアクター
std::vector<class Actor*> mActors;
//待ち状態のアクター
std::vector<class Actor*> mPendingActors;
class Renderer* mRenderer;
Uint32 mTicksCount;
bool mIsRunning;
//アクターを更新中か追跡
bool mUpdatingActors;
//ゲーム仕様
class CameraActor* mCameraActor;
}; | [
"t-khms@live.jp"
] | t-khms@live.jp |
7c1a8fd4b87291dacd3c2d9f51ad8a892d881ac8 | e3f9ab83c0e3c8722920f8850fb295551682a969 | /src/display/old/draw_grid/draw_grid.ino | 92435cdf292e599460c0313c3c10e50fed2cd885 | [] | no_license | wizard97/3400_team5electricboogaloo | 8e80f05fa81dce8f05c1c598345e914887d000ea | a0d507ce57b8b13943eb6ec80e2ceb3d13774cbd | refs/heads/master | 2021-01-20T12:11:07.339947 | 2018-06-05T22:12:50 | 2018-06-05T22:12:50 | 101,703,482 | 1 | 5 | null | 2017-09-26T03:43:54 | 2017-08-29T01:15:12 | Arduino | UTF-8 | C++ | false | false | 2,567 | ino | #include <SPI.h>
#include <VGAGraphics.h>
#define VGA_SS 10
#define XRES 240
#define YRES 240
// define pins for buttons to move block arround
#define BUTTON_UP 3
#define BUTTON_DOWN 4
#define BUTTON_LEFT 5
#define BUTTON_RIGHT 6
#define BLOCK_COLOR (genColor(7,0,0))
void clearScreen(uint8_t color=0);
uint8_t genColor(uint8_t r, uint8_t g, uint8_t b);
void writePixel(uint8_t x, uint8_t y, uint8_t color);
void setup()
{
Serial.begin(115200);
// set the slaveSelectPin as an output:
//pinMode(VGA_SS, OUTPUT);
DDRB |= B00000100; //set slave select output
//digitalWrite(VGA_SS, HIGH);
PORTB |= B00000100; // Set it high
// initialize SPI:
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV2); //faster 8mhz
//init buttons, configure pull up
/*
digitalWrite(BUTTON_UP, HIGH);
digitalWrite(BUTTON_DOWN, HIGH);
digitalWrite(BUTTON_LEFT, HIGH);
digitalWrite(BUTTON_RIGHT, HIGH);
*/
pinMode(BUTTON_UP, INPUT);
pinMode(BUTTON_DOWN, INPUT);
pinMode(BUTTON_LEFT, INPUT);
pinMode(BUTTON_RIGHT, INPUT);
clearScreen();
}
//64-36-
//64-48=16
void loop()
{
/*
for (uint8_t i=0; i <= 5; i++) {
for (uint8_t j=10; j < 120; j++)
writePixel(10+20*i, j, 0xff);
}
for (uint8_t i=0; i <= 4; i++) {
for (uint8_t j=0; j < 120; j++)
writePixel(j, 20+20*i, 0xff);
}
*/
/*
for (uint8_t i=0; i <= 5; i++) {
for (uint8_t j=0; j < 120; j++)
writePixel(10+20*i, j, 0xff);
}
*/
/*
writePixel(0, 0, 0xff);
writePixel(119, 0, 0xff);
writePixel(0, 119, 0xff);
writePixel(119, 119, 0xff);
*/
randScreen();
//clearScreen();
delay(2000);
clearScreen();
delay(2000);
}
/* Use this to write to FPGA vga driver
* x cord: [0:63]
* y cord: [0:63]
* color: Red: color[7:5], Green: color[4:2], Blue: blue[1:0]
*/
void writePixel(uint8_t x, uint8_t y, uint8_t color)
{
if (x >= XRES || y >= YRES)
return;
//digitalWrite(VGA_SS, LOW);
PORTB &= ~B00000100; // This is faster!
uint8_t data[] = {x, y, color};
SPI.transfer(data, 3);
//digitalWrite(VGA_SS, HIGH);
PORTB |= B00000100;
}
void clearScreen(uint8_t color)
{
for (uint8_t i=0; i < XRES; i++) {
for (uint8_t j=0; j < YRES; j++) {
writePixel(i, j, color);
}
}
}
void randScreen()
{
for (uint8_t i=0; i < XRES; i++) {
for (uint8_t j=0; j < YRES; j++) {
writePixel(i, j, random(0, 255));
}
}
}
// r: [0,7], g: [0,7], b: [0,3]
uint8_t genColor(uint8_t r, uint8_t g, uint8_t b)
{
r &= 0b111;
g &= 0b111;
b &= 0b11;
return (r << 5) | (g << 2) | b;
}
| [
"daw268@cornell.edu"
] | daw268@cornell.edu |
60e7c05aae2ea42de0784b4a01bf6f963068cd7f | 5370b9e27da3064f35a59610b7746a263204e621 | /CodeChef/PINS.cpp | 8817a49e77831117b79a1d689a5377d353916007 | [] | no_license | Paryul10/Competetive-Coding | 4619d84b282d58303dc5db9cb8bdad769fc3176d | 3cc06f80dfffe4dc742fd5d8a4b427a9de778d85 | refs/heads/master | 2020-04-02T11:12:49.838056 | 2018-08-02T11:36:04 | 2018-08-02T11:36:04 | 154,376,787 | 0 | 1 | null | 2019-10-19T12:00:45 | 2018-10-23T18:22:09 | C++ | UTF-8 | C++ | false | false | 276 | cpp | #include "bits/stdc++.h"
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
cout << "1 ";
cout << "1";
for (int i=1; i<=(n/2); i++) cout << "0";
cout << endl;
}
return 0;
} | [
"eeshadutta99@gmail.com"
] | eeshadutta99@gmail.com |
4ee9971c1889457b7af52d00f74d25fe3d3dbebe | bba8ad0d783119c7d9a413b4ead7654ed074fc2a | /Volume116/11624 - Fire.cpp | 0da7714b75d9c8c01677c9a2addd5d69115b72d9 | [] | no_license | m00p1ng/UVa-problem | 08d1298225a7d2bffef3e99ff33fd2f940d7924c | 9517304685e6681e7027335dbbea20f643d5fc37 | refs/heads/master | 2023-04-04T10:51:12.141260 | 2021-04-16T23:08:27 | 2021-04-16T23:08:27 | 81,700,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,535 | cpp | #include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int r, c;
int si, sj;
char board[1010][1010];
bool visited[1010][1010];
int fire[1010][1010];
int dr[] = {1, -1, 0, 0};
int dc[] = {0, 0, -1, 1};
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
bool is_valid(int i, int j, int d) {
return i >= 0 && j >= 0 && i < r && j < c && board[i][j] != '#' && fire[i][j] > d+1;
}
bool is_bound(int i, int j) {
return i == 0 || j == 0 || i == r-1 || j == c-1;
}
void fire_connected() {
queue<iii> q;
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
if(fire[i][j] == 0) {
q.push(iii(0, ii(i, j)));
}
}
}
int ni, nj;
while(!q.empty()) {
iii v = q.front(); q.pop();
ii p = v.second;
for(int d = 0; d < 4; d++) {
ni = p.first + dr[d];
nj = p.second + dc[d];
if(is_valid(ni, nj, v.first)) {
fire[ni][nj] = v.first+1;
q.push(iii(v.first+1, ii(ni, nj)));
}
}
}
}
int bfs_joe(int i, int j) {
queue<iii> q;
q.push(iii(0, ii(i, j)));
int cnt = 0, ni, nj;
while(!q.empty()) {
iii v = q.front(); q.pop();
ii p = v.second;
if(is_bound(p.first, p.second)) {
return v.first+1;
}
visited[p.first][p.second] = true;
for(int d = 0; d < 4; d++) {
ni = p.first + dr[d];
nj = p.second + dc[d];
if(is_valid(ni, nj, v.first) && !visited[ni][nj]) {
q.push(iii(v.first+1, ii(ni, nj)));
}
}
}
return -1;
}
void input_board() {
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
fire[i][j] = 1<<20;
}
}
for(int i = 0; i < r; i++) {
scanf("%s", board[i]);
for(int j = 0; j < c; j++) {
if(board[i][j] == 'J') {
si = i;
sj = j;
board[i][j] = '.';
}
if(board[i][j] == 'F') {
fire[i][j] = 0;
board[i][j] = '.';
}
}
}
}
int main() {
int ts;
scanf("%d", &ts);
while(ts--) {
scanf("%d %d", &r, &c);
memset(visited, 0, sizeof(visited));
memset(fire, 0, sizeof(fire));
input_board();
fire_connected();
int b = bfs_joe(si, sj);
if(b == -1) puts("IMPOSSIBLE");
else printf("%d\n", b);
}
}
| [
"mongkonchai4412@gmail.com"
] | mongkonchai4412@gmail.com |
d23ba01ab67494cdd51cb965e2b734e0da5de03c | 061454fa81774bb548ffb14d81011bd27e6f72ea | /lunar_csgo_recode/sdk/weapon.hh | 203e9b63eecb5cc527dde6d7133e6169c4bfce90 | [] | no_license | Aybrr/lunar_leak | f46eea6b14219bb0408c9dfd17d6f78d36148c26 | fdd9c4c6613701067ccc2936f7b0f311f3ca3736 | refs/heads/main | 2023-05-01T22:51:36.443040 | 2021-05-23T13:33:12 | 2021-05-23T13:33:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,457 | hh | #pragma once
#include "entity.hh"
#include <map>
namespace sdk {
struct strike_weapon_definition_t {
pad ( 8 );
int weapon_id;
};
enum class e_cs_weapon_type : int {
weapontype_knife = 0 ,
weapontype_pistol ,
weapontype_submachinegun ,
weapontype_rifle ,
weapontype_shotgun ,
weapontype_sniper_rifle ,
weapontype_machinegun ,
weapontype_c4 ,
weapontype_placeholder ,
weapontype_grenade ,
weapontype_unknown
};
enum class e_item_definition_index : short {
weapon_none = 0 ,
weapon_deagle ,
weapon_elite ,
weapon_fiveseven ,
weapon_glock ,
weapon_ak47 = 7 ,
weapon_aug ,
weapon_awp ,
weapon_famas ,
weapon_g3sg1 ,
weapon_galilar = 13 ,
weapon_m249 ,
weapon_m4a1 = 16 ,
weapon_mac10 ,
weapon_p90 = 19 ,
weapon_mp5sd = 23 ,
weapon_ump45 ,
weapon_xm1014 ,
weapon_bizon ,
weapon_mag7 ,
weapon_negev ,
weapon_sawedoff ,
weapon_tec9 ,
weapon_taser ,
weapon_hkp2000 ,
weapon_mp7 ,
weapon_mp9 ,
weapon_nova ,
weapon_p250 ,
weapon_shield ,
weapon_scar20 ,
weapon_sg556 ,
weapon_ssg08 ,
weapon_knifegg ,
weapon_knife ,
weapon_flashbang ,
weapon_hegrenade ,
weapon_smokegrenade ,
weapon_molotov ,
weapon_decoy ,
weapon_incgrenade ,
weapon_c4 ,
weapon_healthshot = 57 ,
weapon_knife_t = 59 ,
weapon_m4a1_silencer ,
weapon_usp_silencer ,
weapon_cz75a = 63 ,
weapon_revolver ,
weapon_tagrenade = 68 ,
weapon_fists ,
weapon_breachcharge ,
weapon_tablet = 72 ,
weapon_melee = 74 ,
weapon_axe ,
weapon_hammer ,
weapon_spanner = 78 ,
weapon_knife_ghost = 80 ,
weapon_firebomb ,
weapon_diversion ,
weapon_frag_grenade ,
weapon_snowball ,
weapon_bumpmine ,
weapon_bayonet = 500 ,
weapon_knife_css = 500 ,
weapon_knife_flip = 505 ,
weapon_knife_gut ,
weapon_knife_karambit ,
weapon_knife_m9_bayonet ,
weapon_knife_tactical ,
weapon_knife_falchion = 512 ,
weapon_knife_survival_bowie = 514 ,
weapon_knife_butterfly ,
weapon_knife_push ,
weapon_knife_cord ,
weapon_knife_canis ,
weapon_knife_ursus = 519 ,
weapon_knife_gypsy_jackknife ,
weapon_knife_outdoor ,
weapon_knife_stiletto = 522 ,
weapon_knife_widowmaker ,
weapon_knife_skeleton = 525 ,
glove_studded = 5027 ,
glove_t_side ,
glove_ct_side ,
glove_sporty ,
glove_slick ,
glove_leather ,
glove_motorcycle ,
glove_specialist ,
glove_hydra
};
/* from some random sdk */
class c_weaponinfo {
public:
virtual ~c_weaponinfo ( ) = default;
//char pad_0000[4]; //0x0000
char * consolename; // 0x0004
char pad_0008 [ 8 ]; // 0x0008
void * m_pweapondef; //0x0010
int imaxclip1; // 0x0014
int imaxclip2; // 0x0018
int idefaultclip1; // 0x001c
int idefaultclip2; // 0x0020
char pad_0024 [ 8 ]; // 0x0024
char * szworldmodel; // 0x002c
char * szviewmodel; // 0x0030
char * szdroppedmodel; // 0x0034
char pad_0038 [ 4 ]; // 0x0038
char * n0000023e; // 0x003c
char pad_0040 [ 56 ]; // 0x0040
char * szemptysound; // 0x0078
char pad_007c [ 4 ]; // 0x007c
char * szbullettype; // 0x0080
char pad_0084 [ 4 ]; // 0x0084
char * szhudname; // 0x0088
char * szweaponname; // 0x008c
char pad_0090 [ 60 ]; // 0x0090
int weapontype; // 0x00c8
int iweaponprice; // 0x00cc
int ikillaward; // 0x00d0
char * szanimationprefix; // 0x00d4
float flcycletime; // 0x00d8
float flcycletimealt; // 0x00dc
float fltimetoidle; // 0x00e0
float flidleinterval; // 0x00e4
bool bfullauto; // 0x00e8
char pad_0x00e5 [ 3 ]; // 0x00e9
int idamage; // 0x00ec
float flarmorratio; // 0x00f0
int ibullets; // 0x00f4
float flpenetration; // 0x00f8
float flflinchvelocitymodifierlarge; // 0x00fc
float flflinchvelocitymodifiersmall; // 0x0100
float flrange; // 0x0104
float flrangemodifier; // 0x0108
float flthrowvelocity; // 0x010c
char pad_0x010c [ 16 ]; // 0x0110
bool bhassilencer; // 0x011c
char pad_0x0119 [ 3 ]; // 0x011d
char * psilencermodel; // 0x0120
int icrosshairmindistance; // 0x0124
float flmaxplayerspeed; // 0x0128
float flmaxplayerspeedalt; // 0x012c
char pad_0x0130 [ 4 ]; // 0x0130
float flspread; // 0x0134
float flspreadalt; // 0x0138
float flinaccuracycrouch; // 0x013c
float flinaccuracycrouchalt; // 0x0140
float flinaccuracystand; // 0x0144
float flinaccuracystandalt; // 0x0148
float flinaccuracyjumpinitial; // 0x014c
float flinaccuracyjump; // 0x0150
float flinaccuracyjumpalt; // 0x0154
float flinaccuracyland; // 0x0158
float flinaccuracylandalt; // 0x015c
float flinaccuracyladder; // 0x0160
float flinaccuracyladderalt; // 0x0164
float flinaccuracyfire; // 0x0168
float flinaccuracyfirealt; // 0x016c
float flinaccuracymove; // 0x0170
float flinaccuracymovealt; // 0x0174
float flinaccuracyreload; // 0x0178
int irecoilseed; // 0x017c
float flrecoilangle; // 0x0180
float flrecoilanglealt; // 0x0184
float flrecoilanglevariance; // 0x0188
float flrecoilanglevariancealt; // 0x018c
float flrecoilmagnitude; // 0x0190
float flrecoilmagnitudealt; // 0x0194
float flrecoilmagnitudevariance; // 0x0198
float flrecoilmagnitudevariancealt; // 0x019c
float flrecoverytimecrouch; // 0x01a0
float flrecoverytimestand; // 0x01a4
float flrecoverytimecrouchfinal; // 0x01a8
float flrecoverytimestandfinal; // 0x01ac
int irecoverytransitionstartbullet; // 0x01b0
int irecoverytransitionendbullet; // 0x01b4
bool bunzoomaftershot; // 0x01b8
bool bhideviewmodelzoomed; // 0x01b9
char pad_0x01b5 [ 2 ]; // 0x01ba
char izoomlevels [ 3 ]; // 0x01bc
int izoomfov [ 2 ]; // 0x01c0
float fzoomtime [ 3 ]; // 0x01c4
char * szweaponclass; // 0x01d4
float fladdonscale; // 0x01d8
char pad_0x01dc [ 4 ]; // 0x01dc
char * szejectbrasseffect; // 0x01e0
char * sztracereffect; // 0x01e4
int itracerfrequency; // 0x01e8
int itracerfrequencyalt; // 0x01ec
char * szmuzzleflasheffect_1stperson; // 0x01f0
char pad_0x01f4 [ 4 ]; // 0x01f4
char * szmuzzleflasheffect_3rdperson; // 0x01f8
char pad_0x01fc [ 4 ]; // 0x01fc
char * szmuzzlesmokeeffect; // 0x0200
float flheatpershot; // 0x0204
char * szzoominsound; // 0x0208
char * szzoomoutsound; // 0x020c
float flinaccuracypitchshift; // 0x0210
float flinaccuracysoundthreshold; // 0x0214
float flbotaudiblerange; // 0x0218
char pad_0x0218 [ 8 ]; // 0x0220
char * pwrongteammsg; // 0x0224
bool bhasburstmode; // 0x0228
char pad_0x0225 [ 3 ]; // 0x0229
bool bisrevolver; // 0x022c
bool bcannotshootunderwater; // 0x0230
};
class c_weapon {
public:
/* netvars */
/* local weapon data */
netvar_fn ( float , next_primary_attack , "DT_LocalActiveWeaponData->m_flNextPrimaryAttack" );
netvar_fn ( float , next_secondary_attack , "DT_LocalActiveWeaponData->m_flNextSecondaryAttack" );
netvar_fn ( float , time_weapon_idle , "DT_LocalActiveWeaponData->m_flTimeWeaponIdle" );
/* weapon cs base */
netvar_fn ( float , postpone_fire_ready_time , "DT_WeaponCSBase->m_flPostponeFireReadyTime" );
netvar_fn ( float , last_shot_time , "DT_WeaponCSBase->m_fLastShotTime" );
netvar_fn ( int , clip , "DT_BaseCombatWeapon->m_iClip1" );
netvar_fn ( int , second_clip , "DT_BaseCombatWeapon->m_iClip2" );
/* nades */
netvar_fn ( float , throw_time , "DT_BaseCSGrenade->m_fThrowTime" );
netvar_fn ( bool , pin_pulled , "DT_BaseCSGrenade->m_bPinPulled" );
/* offsets */
// offset ( e_item_definition_index , item_definition_index , 0x2FAA );
offset ( bool , in_reload , 0x32A5 );
/* methods */
/* shit netvar manager forces my hand lolll */
e_item_definition_index item_definition_index ( ) {
if ( !this ) return e_item_definition_index::weapon_none;
static const auto offset = hack::game::netvars::offsets [ fnv1a ( "DT_BaseAttributableItem->m_AttributeManager" ) ] + hack::game::netvars::offsets [ fnv1a ( "DT_AttributeContainer->m_Item" ) ] + hack::game::netvars::offsets [ fnv1a ( "DT_ScriptCreatedItem->m_iItemDefinitionIndex" ) ];
return *( e_item_definition_index * ) ( std::uintptr_t ( this ) + offset );
}
/* this is a meme */
auto weapon_kind ( ) {
switch ( this->item_definition_index ( ) ) {
case sdk::e_item_definition_index::weapon_c4:
return sdk::e_cs_weapon_type::weapontype_c4;
break;
case sdk::e_item_definition_index::weapon_knife:
case sdk::e_item_definition_index::weapon_knifegg:
case sdk::e_item_definition_index::weapon_knife_butterfly:
case sdk::e_item_definition_index::weapon_knife_canis:
case sdk::e_item_definition_index::weapon_knife_cord:
case sdk::e_item_definition_index::weapon_knife_css:
case sdk::e_item_definition_index::weapon_knife_falchion:
case sdk::e_item_definition_index::weapon_knife_flip:
case sdk::e_item_definition_index::weapon_knife_ghost:
case sdk::e_item_definition_index::weapon_knife_gut:
case sdk::e_item_definition_index::weapon_knife_gypsy_jackknife:
case sdk::e_item_definition_index::weapon_knife_karambit:
case sdk::e_item_definition_index::weapon_knife_m9_bayonet:
case sdk::e_item_definition_index::weapon_knife_push:
case sdk::e_item_definition_index::weapon_knife_outdoor:
case sdk::e_item_definition_index::weapon_knife_skeleton:
case sdk::e_item_definition_index::weapon_knife_stiletto:
case sdk::e_item_definition_index::weapon_knife_survival_bowie:
case sdk::e_item_definition_index::weapon_knife_t:
case sdk::e_item_definition_index::weapon_knife_tactical:
case sdk::e_item_definition_index::weapon_knife_ursus:
case sdk::e_item_definition_index::weapon_knife_widowmaker:
return sdk::e_cs_weapon_type::weapontype_knife;
break;
case sdk::e_item_definition_index::weapon_hegrenade:
case sdk::e_item_definition_index::weapon_decoy:
case sdk::e_item_definition_index::weapon_smokegrenade:
case sdk::e_item_definition_index::weapon_molotov:
case sdk::e_item_definition_index::weapon_incgrenade:
case sdk::e_item_definition_index::weapon_firebomb:
case sdk::e_item_definition_index::weapon_flashbang:
case sdk::e_item_definition_index::weapon_frag_grenade:
case sdk::e_item_definition_index::weapon_tagrenade:
case sdk::e_item_definition_index::weapon_snowball:
return sdk::e_cs_weapon_type::weapontype_grenade;
break;
case sdk::e_item_definition_index::weapon_g3sg1:
case sdk::e_item_definition_index::weapon_scar20:
case sdk::e_item_definition_index::weapon_awp:
case sdk::e_item_definition_index::weapon_ssg08:
return sdk::e_cs_weapon_type::weapontype_sniper_rifle;
break;
default:
return sdk::e_cs_weapon_type::weapontype_unknown;
break;
}
return sdk::e_cs_weapon_type::weapontype_unknown;
}
std::pair<std::string , bool> get_weapon_as_string ( ) {
if ( !this || !this->data ( ) )
return std::pair<std::string , bool> ( " " , false );
std::string name = this->data ( )->consolename;
name.erase ( 0 , 7 );
return std::pair<std::string , bool > ( name , false );
}
sdk::c_weaponinfo * data ( );
float inaccuracy ( );
float spread ( );
void update_accuracy ( );
};
} | [
"senpaifuuzy@gmail.com"
] | senpaifuuzy@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.