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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
7f89b3fcb65bc173e543671fa9bde639650dce28
ccf9b152ef277495ad927b51e8c22c675e9f883b
/Interview_Practice/Linked Lists/removeKFromList.cpp
1dc6c0ce8d21ce7d0e9590c4e39de0ac89416509
[]
no_license
Andruxa0125/CodeFights
62025d2e1ff80fc3413d1268c08ebbf395f74aac
c17caaeeebffca262c2a6a9d0b2f28503947a810
refs/heads/master
2021-09-10T21:36:39.091010
2018-04-02T17:52:25
2018-04-02T17:52:25
125,555,998
2
0
null
null
null
null
UTF-8
C++
false
false
654
cpp
// Definition for singly-linked list: // template<typename T> // struct ListNode { // ListNode(const T &v) : value(v), next(nullptr) {} // T value; // ListNode *next; // }; // ListNode<int> * removeKFromList(ListNode<int> * l, int k) { ListNode<int>* start = l; ListNode<int>* prev = new ListNode<int>(); prev->next = start; ListNode<int>* result = prev; while(start != NULL) { if(start->value == k) { prev->next = start->next; start = prev->next; } else { prev = start; start = start->next; } } return result->next; }
[ "andruxa0125@gmail.com" ]
andruxa0125@gmail.com
3f4bfa289bc4b5ef8b579d261e2cc7c62b7a7edf
985cd2acd4e33cfe3a7a3f7a8244fd300165b924
/iterative_preorder.cpp
cc6c5f625e860ab7c21eaf9919e5f86aeddb07cc
[]
no_license
pkroy328/prashant_code_library
2f25b7d75b6cd2f9d5646f15cc6784a1e2b7eb81
c9c3244bbc386b75036079cc4c92df12ae3402b1
refs/heads/main
2023-06-04T21:52:16.842166
2021-06-27T18:50:08
2021-06-27T18:50:08
380,814,617
0
0
null
null
null
null
UTF-8
C++
false
false
4,725
cpp
/* The traversal operation is a frequently used operation on a binary tree. This operation is used to visit each node in the tree exactly once A full traversal on a binary tree gives a linear ordering of data in the tree . This is the iterative preorder tree traversal algorithms */ #include <bits/stdc++.h> using namespace std; //structure for the binary tree node class TreeNode { public: char data; TreeNode *left; TreeNode *right; }; //structure for stack which is used for the iterative traversal algorithms //stack is implemented using linked list class Stack { public: TreeNode *node; Stack *next; }; //push operation for the stack void push(Stack **s, TreeNode *node) { Stack *New = new Stack(); New->node = node; New->next = (*s); (*s) = New; } // pop operation for the stack TreeNode *pop(Stack **s) { if ((*s) != NULL) { TreeNode *ptr = (*s)->node; (*s) = (*s)->next; return ptr; } } //checks whether the stack is empty or not int isEmpty(Stack **s) { if ((*s) == NULL) { return 1; } return 0; } //iterative preorder traversal void preorder(TreeNode *root) { TreeNode *ptr = root; Stack *s = NULL; push(&s, root); while (!isEmpty(&s)) { ptr = pop(&s); if (ptr != NULL) { printf("%c ", ptr->data); push(&s, ptr->right); push(&s, ptr->left); } } } //search function returns the pointer to the node which contains the value key , it is used in the insertion operation TreeNode *search(TreeNode *root, int k) { if (root == NULL) { return NULL; } else if (root->data == k) { return root; } else { TreeNode *x = search(root->left, k); if (x) return x; //if we find in left subtree, return result return search(root->right, k); } } // Insertion operation of the binary tree void insert(TreeNode *root, char key, char c) { TreeNode *ptr = search(root, key); if (ptr == NULL) { cout << "Search Unsuccessfull No Insertion \n"; return; } char option; if (ptr->left == NULL || ptr->right == NULL) { cout << "Enter Where to insert left or right (L/R)\n"; cin >> option; if (option == 'L' || option == 'l') { if (ptr->left == NULL) { TreeNode *New = new TreeNode(); ptr->left = New; New->data = c; cout << "Inserting " << c << " as the left" << endl; New->left = NULL; New->right = NULL; } else { cout << "Insertion not Possible as Left child " << endl; } } else { if (ptr->right == NULL) { TreeNode *New = new TreeNode(); ptr->right = New; New->data = c; cout << "Inserting " << c << " as the right" << endl; New->left = NULL; New->right = NULL; } else { cout << "Insertion not possible as the right child" << endl; } } } else { cout << "The Node Already has child" << endl; } } int main() { cout << "Enter the value for root node" << endl; TreeNode *root = new TreeNode(); char c; scanf("%c", &c); root->data = c; root->right = NULL; root->left = NULL; char choice = 'y'; char data; do { cout << "Enter the Node to be Inserted" << endl; cin >> data; cout << "Enter the Parent node of the node to be inserted" << endl; cin >> c; insert(root, c, data); cout << "Do you want to continue (y/n)" << endl; cin >> choice; } while (choice == 'y' || choice == 'Y'); cout << "Preorder Traversal of the Tree" << endl; preorder(root); return 0; } /* Sample I/O: Enter the value for root node A Enter the Node to be Inserted B Enter the Parent node of the node to be inserted A Enter Where to insert left or right (L/R) L Inserting B as the left Do you want to continue (y/n) y Enter the Node to be Inserted C Enter the Parent node of the node to be inserted A Enter Where to insert left or right (L/R) R Inserting C as the right Do you want to continue (y/n) n Preorder Traversal of the Tree A B C Time Complexity = O( n ) Space Complexity = O( n ) */
[ "noreply@github.com" ]
pkroy328.noreply@github.com
728c2fb264c157b0065a532265f7d046dfe257ce
a02c2866eea844057ea6750d44ecedac8ef53dca
/ClassExamples/IoT-AR/NodeMCU_Board/ButtonLED/ButtonLED.ino
c861d7e3f73238804e5fba6d229a8bdee23438e8
[]
no_license
sarwansingh/IoT
a076f7b6a5fcd6557a59c88712fa3cf032178a9e
290970ea6d5d1c17a5fcffcd804d9d2065273a53
refs/heads/master
2023-07-18T16:44:23.650685
2021-09-24T09:04:36
2021-09-24T09:04:36
125,970,428
1
4
null
null
null
null
UTF-8
C++
false
false
810
ino
// constants won't change. They're used here to set pin numbers: const int buttonPin = 16; // the number of the pushbutton pin const int ledPin = 2; // the number of the LED pin // variables will change: int buttonState = 0; // variable for reading the pushbutton status void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize the pushbutton pin as an input: pinMode(buttonPin, INPUT); } void loop() { // read the state of the pushbutton value: buttonState = digitalRead(buttonPin); // check if the pushbutton is pressed. If it is, the buttonState is HIGH: if (buttonState == HIGH) { // turn LED on: digitalWrite(ledPin, HIGH); } else { // turn LED off: digitalWrite(ledPin, LOW); } }
[ "sarwan_singh@yahoo.com" ]
sarwan_singh@yahoo.com
da8bda37f4028d8803ce565df028d9ec6e5b8c41
176eb09d1895c3e18dc27dc5bac53c1ff2fa9245
/leach/leach.ino
067d1ef2e58b5b3c32c5ae2ea46c988b29eb1b02
[]
no_license
giripranay/Embeddedsystems
bc558037d28571d0ec737b8540731ca1500860d0
af161ddac2d3cdc0042f3a904bc7e0b19599cec0
refs/heads/master
2020-07-30T23:01:50.456227
2019-09-23T15:49:22
2019-09-23T15:49:22
210,389,515
0
0
null
2019-10-22T02:24:12
2019-09-23T15:27:47
C++
UTF-8
C++
false
false
2,809
ino
#include <ESP8266WiFi.h> #include <WiFiUdp.h> #define MASTER // Comment this define to compile sketch on slave device const int8_t ledPin = LED_BUILTIN; const char* const ssid = "green"; // Your network SSID (name) const char* const pass = "12345678"; // Your network password const uint16_t localPort = 54321; // Local port to listen for UDP packets #ifdef MASTER const uint32_t stepDuration = 2000; IPAddress broadcastAddress; #endif WiFiUDP udp; bool sendPacket(const IPAddress& address, const char* buf, uint8_t bufSize); void receivePacket(); void setup() { Serial.begin(115200); Serial.println(); pinMode(ledPin, OUTPUT); Serial.print(F("Connecting to ")); Serial.println(ssid); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { digitalWrite(ledPin, ! digitalRead(ledPin)); delay(500); Serial.print('.'); } digitalWrite(ledPin, HIGH); Serial.println(); Serial.println(F("WiFi connected")); Serial.println(F("IP address: ")); Serial.println(WiFi.localIP()); #ifdef MASTER broadcastAddress = (uint32_t)WiFi.localIP() | ~((uint32_t)WiFi.subnetMask()); Serial.print(F("Broadcast address: ")); Serial.println(broadcastAddress); Serial.print(F("SubnetMAsk address: ")); Serial.println(WiFi.subnetMask()); #endif Serial.println(F("Starting UDP")); udp.begin(localPort); Serial.print(F("Local port: ")); Serial.println(udp.localPort()); } void loop() { #ifdef MASTER static uint32_t nextTime = 0; if (millis() >= nextTime) { const char* const info="broadcasting msg"; // bool led = ! digitalRead(ledPin); //digitalWrite(ledPin, led); //Serial.print(F("Turn led ")); //Serial.println(led ? F("off") : F("on")); if (! sendPacket(broadcastAddress, (char*)info, sizeof(info))) Serial.println(F("Error sending broadcast UDP packet!")); nextTime = millis() + stepDuration; } #endif if (udp.parsePacket()) receivePacket(); delay(1); } bool sendPacket(const IPAddress& address, const char* buf, uint8_t bufSize) { udp.beginPacket(address, localPort); udp.write(buf, bufSize); return (udp.endPacket() == 1); } void receivePacket() { bool led; udp.read((char*)&led, sizeof(led)); udp.flush(); #ifdef MASTER if (udp.destinationIP() != broadcastAddress) { Serial.print(F("Client with IP ")); Serial.print(udp.remoteIP()); // Serial.print(F(" turned led ")); // Serial.println(led ? F("off") : F("on")); } else { // Serial.println(F("Skip broadcast packet")); } #else //digitalWrite(ledPin, led); //led = digitalRead(ledPin); // Serial.print(F("Turn led ")); // Serial.println(led ? F("off") : F("on")); //if (! sendPacket(udp.remoteIP(), (uint8_t*)&led, sizeof(led))) // Serial.println(F("Error sending answering UDP packet!")); #endif }
[ "giripranay.k@dvara.com" ]
giripranay.k@dvara.com
48d56141115acf7df1a9ca41e3c616140aab453f
262d93a5a33237268c90788ff141c4504e7f18d3
/src/functions/div.cpp
6c27fad24785c0b3056b1984068e4227726e5afa
[]
no_license
chadac/cppgp
41240b634181252e525e19332a61aa9931daa37d
24d797d762d3c3b04280970ef83a3518f162069d
refs/heads/master
2021-06-01T03:25:51.157478
2016-04-04T22:12:59
2016-04-04T22:12:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
#include "div.h" gpf_div = new FunctionDiv(); FunctionDiv::FunctionDiv() : Function(2, GPTYPE_REAL) {} int FunctionDiv::get_arg_type(int index) { return GPTYPE_REAL; } GPValue FunctionDiv::evaluate(GPValue* args) { double arg1 = *((double*)(args[0]->value)); double arg2 = *((double*)(args[1]->value)); double* r = new double; *r = arg1 / arg2; return GPValue(GPTYPE_REAL, (int*) r); }
[ "chad-crawford@utulsa.edu" ]
chad-crawford@utulsa.edu
87ad8882e20fa6a698d0eb09f83b95d88fb46b30
da3459735ac22f4dcee124a25d5527bad909fca5
/src/qt/rpcconsole.cpp
eb3b37e981b544aeadb8a14f80c38878597b3d19
[ "MIT" ]
permissive
bitfawkes/sannacoin
0cb15ac6fa3738c797844606b0b3f7d1d0d4d990
94ae22141a183d5ae1442e8589fc55b18136ebb3
refs/heads/master
2021-01-13T05:25:52.997635
2017-02-09T13:47:08
2017-02-09T13:47:08
81,370,249
0
0
null
null
null
null
UTF-8
C++
false
false
10,287
cpp
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "guiutil.h" #include <QTime> #include <QTimer> #include <QThread> #include <QTextEdit> #include <QKeyEvent> #include <QUrl> #include <QScrollBar> #include <boost/tokenizer.hpp> #include <openssl/crypto.h> // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_SCROLLBACK = 50; const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor: public QObject { Q_OBJECT public slots: void start(); void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" void RPCExecutor::start() { // Nothing to do } void RPCExecutor::request(const QString &command) { // Parse shell-like command line into separate arguments std::string strMethod; std::vector<std::string> strParams; try { boost::escaped_list_separator<char> els('\\',' ','\"'); std::string strCommand = command.toStdString(); boost::tokenizer<boost::escaped_list_separator<char> > tok(strCommand, els); int n = 0; for(boost::tokenizer<boost::escaped_list_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg,++n) { if(n == 0) // First parameter is the command strMethod = *beg; else strParams.push_back(*beg); } } catch(boost::escaped_list_error &e) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error")); return; } try { std::string strPrint; json_spirit::Value result = tableRPC.execute(strMethod, RPCConvertValues(strMethod, strParams)); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QDialog(parent), ui(new Ui::RPCConsole), historyPtr(0) { ui->setupUi(this); #ifndef Q_WS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(obj == ui->lineEdit) { if(event->type() == QEvent::KeyPress) { QKeyEvent *key = static_cast<QKeyEvent*>(event); switch(key->key()) { case Qt::Key_Up: browseHistory(-1); return true; case Qt::Key_Down: browseHistory(1); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Subscribe to information, replies, messages, errors connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); setNumConnections(model->getNumConnections()); ui->isTestNet->setChecked(model->isTestNet()); setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " "b { color: #006060; } " ); message(CMD_REPLY, (tr("Welcome to the SannaCoin RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count, int countOfPeers) { ui->numberOfBlocks->setText(QString::number(count)); ui->totalBlocks->setText(QString::number(countOfPeers)); if(clientModel) { // If there is no current number available display N/A instead of 0, which can't ever be true ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers())); ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Truncate history from current position history.erase(history.begin() + historyPtr, history.end()); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread* thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Notify executor when thread started (in executor thread) connect(thread, SIGNAL(started()), executor, SLOT(start())); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); }
[ "bitfawkes@gmail.com" ]
bitfawkes@gmail.com
b736caaf70e4776819b343281a4b9e18b25af284
8fabbfa6ca7763588554073c406f50a2a19a710d
/HelloDave.cpp
0ab1fb40a1cb450937ba856bc76793b57159d843
[]
no_license
SamiSousa/EC327
c8e85d7634fd79d894ac0100af76d9a9d445e705
423151f98aedcac67e46aaf3ef0277b4f1aa4949
refs/heads/master
2016-08-12T13:26:05.806027
2015-10-01T05:38:08
2015-10-01T05:38:08
43,347,103
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
#include <iostream> #include <cstdlib> using namespace std; int main() { //testing Dev-C++ //press F9 to compile and run in one go cout << "Hello Dave" << endl; //this for seeing result system("PAUSE"); return 0; }
[ "dr.wisper@gmail.com" ]
dr.wisper@gmail.com
fa77b9a5ded5b70b26211eb1ccb699d3b9cc1052
e6652252222ce9e4ff0664e539bf450bc9799c50
/d0706/7.6/source/厦门一中黎学丞/ah.cpp
e1a9f4909b5819351ad674fcdd03a1b8e91c57ed
[]
no_license
cjsoft/inasdfz
db0cea1cf19cf6b753353eda38d62f1b783b8f76
3690e76404b9189e4dd52de3770d59716c81a4df
refs/heads/master
2021-01-17T23:13:51.000569
2016-07-12T07:21:19
2016-07-12T07:21:19
62,596,117
0
0
null
null
null
null
UTF-8
C++
false
false
1,664
cpp
#include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> #include<cstring> #define ll long long using namespace std; int i,j,k,m,n,s,t; int read() { int x=0;char ch=getchar(); while (ch<'0'||ch>'9') ch=getchar(); while (ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();} return x; } int sum,m1,a[201000],next[201000],zhi[201000],first[201000],fa[201000],du[200100],d[201000],c[201000]; void insert(int u,int v) { next[++m1]=first[u]; first[u]=m1; zhi[m1]=v; } void dfs(int x) { if (!du[x]) d[x]++; for (int k=first[x];k;k=next[k]) dfs(zhi[k]),d[x]+=d[zhi[k]]; } struct dat{ int s,i; }; bool cmp(dat a,dat b) { return a.s<b.s; } void solve(int x) { dat b[1100]; int b1=0; for (int k=first[x];k;k=next[k]) b[++b1].s=d[zhi[k]],b[b1].i=zhi[k]; sort(b+1,b+b1+1,cmp); for (int i=1;i<=b1;i++) { int s=b[i].i; if (!du[s]) c[s]=i&1?1:-1; else solve(s); c[x]+=c[s]; } if (c[x]>0) c[x]=1; else c[x]=-1; printf("%d %d\n",x,c[x]); } int main() { freopen("ah.in","r",stdin); freopen("ah.out","w",stdout); int T=read(); while (T--) { n=read(); for (i=1;i<=n;i++) du[i]=0,first[i]=0; sum=0; m1=0; for (i=1;i<=n;i++) fa[i]=read(),du[fa[i]]++; for (i=2;i<=n;i++) insert(fa[i],i); for (i=1;i<=n;i++) if (!du[i]) sum++; for (i=1;i<=n;i++) { s=0; t=0; for (k=first[i];k;k=next[k]) { s++; if (!du[zhi[k]]) t++; } // printf("%d %d\n",s,t); } for (i=1;i<=n;i++) a[i]=read(); //rintf("%d\n",sum); puts("0"); // dfs(1); // solve(1); } }
[ "egwcyh@qq.com" ]
egwcyh@qq.com
35a28677b2574911084d32ca974c7d7019cd68a1
00d4aca628e46fc06c597c19ba0d919a580815eb
/core/Processor/ProcessBase.cxx
be2ce1c4971a5aac0dc53c3600d60bdfe0a3fb7b
[]
no_license
yeonjaej/LArCV
a9f1d706c12f1e183378e38268e2a4ee3b9060d9
c92117bffea0c8ec89cff305e3def5385497e805
refs/heads/master
2020-03-25T00:58:25.318085
2016-08-24T20:15:19
2016-08-24T20:15:19
143,215,231
0
0
null
2018-08-01T22:37:08
2018-08-01T22:37:08
null
UTF-8
C++
false
false
881
cxx
#ifndef PROCESSBASE_CXX #define PROCESSBASE_CXX #include "ProcessBase.h" namespace larcv { ProcessBase::ProcessBase(const std::string name) : larcv_base ( name ) , _proc_time ( 0. ) , _proc_count ( 0 ) , _id ( kINVALID_SIZE ) , _profile ( false ) , _fout ( nullptr ) {} void ProcessBase::_configure_(const PSet& cfg) { _profile = cfg.get<bool>("Profile",_profile); set_verbosity((msg::Level_t)(cfg.get<unsigned short>("Verbosity",logger().level()))); _event_creator=cfg.get<bool>("EventCreator",false); configure(cfg); } bool ProcessBase::_process_(IOManager& mgr) { bool status=false; if(_profile) { _watch.Start(); status = this->process(mgr); _proc_time += _watch.WallTime(); ++_proc_count; }else status = this->process(mgr); return status; } } #endif
[ "kazuhiro@nevis.columbia.edu" ]
kazuhiro@nevis.columbia.edu
373c2840a0fc79187797b27ae66990064b109dd6
1ee90596d52554cb4ef51883c79093897f5279a0
/Sisteme/[C++] Global Chat fara bug/src/binary/userinterface/PythonChat.cpp
8f15460057b754dc5dd726adc87c97e73be0d179
[]
no_license
Reizonr1/metin2-adv
bf7ecb26352b13641cd69b982a48a6b20061979a
5c2c096015ef3971a2f1121b54e33358d973c694
refs/heads/master
2022-04-05T20:50:38.176241
2020-03-03T18:20:58
2020-03-03T18:20:58
233,462,795
1
1
null
null
null
null
UTF-8
C++
false
false
3,292
cpp
// search this void CPythonChat::UpdateViewMode(DWORD dwID) // after pChatLine->Instance.Update(); // add this #ifdef ENABLE_GLOBAL_CHAT if(pChatLine->ImageInstance) pChatLine->ImageInstance->SetPosition(pChatSet->m_ix, pChatSet->m_iy + iHeight + 2); #endif // search this void CPythonChat::UpdateEditMode(DWORD dwID) // after this pChatLine->Instance.Update(); // add this #ifdef ENABLE_GLOBAL_CHAT if(pChatLine->ImageInstance) pChatLine->ImageInstance->SetPosition(pChatSet->m_ix, pChatSet->m_iy + iHeight + 2); #endif // search this void CPythonChat::UpdateLogMode(DWORD dwID) // after this pChatLine->Instance.Update(); // add this #ifdef ENABLE_GLOBAL_CHAT if(pChatLine->ImageInstance) pChatLine->ImageInstance->SetPosition(pChatSet->m_ix, pChatSet->m_iy + iHeight + 2); #endif // search this void CPythonChat::Render(DWORD dwID) // after this rInstance.Render(); // add this #ifdef ENABLE_GLOBAL_CHAT CGraphicImageInstance *& imInstance = (*itor)->ImageInstance; if (imInstance) imInstance->Render(); #endif // search this void CPythonChat::AppendChat(int iType, const char * c_szChat) // after this function for (TChatSetMap::iterator itor = m_ChatSetMap.begin(); itor != m_ChatSetMap.end(); ++itor) { - - - } // add this #ifdef ENABLE_GLOBAL_CHAT std::string const s = c_szChat; std::size_t EP1 = 0; std::size_t EP2 = 0; std::size_t EP3 = 0; CGraphicImageInstance *& prFlag = pChatLine->ImageInstance; std::string sub_s = s.substr(0, 1); if (iType == 6) { EP1 = sub_s.find_first_of("1"); EP2 = sub_s.find_first_of("2"); EP3 = sub_s.find_first_of("3"); } else { EP1 = sub_s.find("!§$%&/(845945)=X"); EP2 = sub_s.find("!§$%&/(845945)=X"); EP3 = sub_s.find("!§$%&/(845945)=X"); } if (EP1 != std::string::npos) { if (CResourceManager::Instance().IsFileExist("d:/ymir work/ui/game/flag/shinsoo.tga")) { CGraphicImage * pFlagImage = (CGraphicImage *)CResourceManager::Instance().GetResourcePointer("d:/ymir work/ui/game/flag/shinsoo.tga"); if (pFlagImage) { prFlag = CGraphicImageInstance::New(); prFlag->SetImagePointer(pFlagImage); } } } else if (EP2 != std::string::npos) { if (CResourceManager::Instance().IsFileExist("d:/ymir work/ui/game/flag/chunjo.tga")) { CGraphicImage * pFlagImage = (CGraphicImage *)CResourceManager::Instance().GetResourcePointer("d:/ymir work/ui/game/flag/chunjo.tga"); if (pFlagImage) { prFlag = CGraphicImageInstance::New(); prFlag->SetImagePointer(pFlagImage); } } } else if (EP3 != std::string::npos) { if (CResourceManager::Instance().IsFileExist("d:/ymir work/ui/game/flag/jinno.tga")) { CGraphicImage * pFlagImage = (CGraphicImage *)CResourceManager::Instance().GetResourcePointer("d:/ymir work/ui/game/flag/jinno.tga"); if (pFlagImage) { prFlag = CGraphicImageInstance::New(); prFlag->SetImagePointer(pFlagImage); } } } else { if (CResourceManager::Instance().IsFileExist("d:/ymir work/ui/game/flag/none.tga")) { CGraphicImage * pFlagImage = (CGraphicImage *)CResourceManager::Instance().GetResourcePointer("d:/ymir work/ui/game/flag/none.tga"); if (pFlagImage) { prFlag = CGraphicImageInstance::New(); prFlag->SetImagePointer(pFlagImage); } } } #endif
[ "59807064+Reizonr1@users.noreply.github.com" ]
59807064+Reizonr1@users.noreply.github.com
34fa439c3ed8ed751371c9577f6771545bbc99d3
93b83850891b8445ebab39d81da8fd1abdcd9358
/tablemodel.h
24b575892fb61c6be09c90c30fdb4a906d7a2f1a
[]
no_license
stevexu/casher-app
a00d00afba268ccf5ff794c7eff9fbc2c5fc61dc
f0ff2ed8102eb8968bd88363f7f763ad1dbb798a
refs/heads/master
2021-01-18T16:22:52.983233
2009-10-29T16:40:04
2009-10-29T16:40:04
354,257
1
0
null
null
null
null
UTF-8
C++
false
false
1,217
h
#ifndef DEPTABLEMODEL_H #define DEPTABLEMODEL_H #include <QAbstractTableModel> #include <qlist.h> #include <qvector> class QStringList; typedef QVector<QString> TableRow; typedef QList<TableRow> TableRecords; typedef TableRow TableHeader; class TableModel : public QAbstractTableModel { Q_OBJECT public: TableModel(QObject *parent = 0); TableModel(TableRecords& listOfDep, QWidget* parent = 0); int rowCount(const QModelIndex &parent /* = QModelIndex */) const; int columnCount(const QModelIndex &parent /* = QModelIndex */) const; QVariant data(const QModelIndex &index, int role /* = Qt::DisplayRole */) const; QVariant headerData(int section, Qt::Orientation orientation, int role /* = Qt::DisplayRole */) const; Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole ); bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()); bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex() ); TableRecords getList(); void setHeader(const QStringList& headers); ~TableModel(); private: TableRecords m_listOfDep; TableHeader m_header; }; #endif // DEPTABLEMODEL_H
[ "xy@.(none)" ]
xy@.(none)
7208812ace4f7a2d45f417a66cdee2da1204ddbb
14cc4da540a1bec830aaa5d1f822785195ce632c
/ip2016/image.h
69e836d60fa135e23ece2b6ccc38002a285c6f02
[]
no_license
Dannnno/RealTimeHatching
0cc94d105c9d79ef0c7dc1cc42f1abcd9ee933b7
699cbb80daf971e7388848b17fad0190d07f3a80
refs/heads/master
2016-09-12T20:24:00.132760
2016-05-11T22:30:46
2016-05-11T22:30:46
56,352,838
0
0
null
null
null
null
UTF-8
C++
false
false
3,302
h
class Image; #ifndef IMAGE_H #define IMAGE_H #include <fstream> #include "common.h" using namespace std; /* * definitions for channel values. for example, * image->getPixel(0,0,GREEN); * gets the green value at pixel 0,0 in image. */ #define RED 0 #define GREEN 1 #define BLUE 2 /* * struct to contain an entire pixel's data, up to three channels. if * only one channel then all bur r values in * this struct will be ignored. */ class Pixel { public: Pixel (); Pixel (double r, double g, double b); Pixel (const Pixel& toCopy); Pixel& operator=(const Pixel& toCopy); ~Pixel (); double getColor(int chan); void setColor(int chan, double value); private: double col[3]; }; ostream &operator<<(ostream &out_file, Pixel& thePixel); /* * generic multi channel 8-bit max image class. can read and write * 8 and 24 bit uncompressed BMP files and supports some useful OpenGL * calls. * * get and set pixel methods use doubles from 0.0 to 1.0. these * values are mapped to integer values from 0 to the maximum value * allowed by the number of bits per channel in the image. */ class Image { public: Image (); ~Image (); // create empty image with specified characteristics Image (int width_, int height_); Image (int width_, int height_, int bits_); // create image and read data from filename // use good() or bad() to check success Image (const char* filename); // copy constructor and assignment operator // _deep_ copy! Image (const Image& image); Image& operator= (const Image& image); // accessors int getWidth () { return width; } int getHeight () { return height; } int getBits () { return bits; } // check if the image is valid bool good (); bool bad (); // set all the pixel data to zero void clear (); // retrieve pixel data. methods with _ at the // end of their name return 0.0 if the x and y // coordinates are out of range. the functions // without a _ give an assertion failur for out // of bounds coordinates double getPixel (int x, int y, int channel); double getPixel_ (int x, int y, int channel); Pixel getPixel (int x, int y); Pixel getPixel_ (int x, int y); Pixel& getPixel (int x, int y, Pixel& pixel); Pixel& getPixel_ (int x, int y, Pixel& pixel); // set pixel data. set is ignored by functions with a _ // at the end of the name when the coordinates or the pixel // value are out of bounds. the functions without an _ // after the name give an assertion failure for out of // bounds // void setPixel (int x, int y, int channel, double value); void setPixel_ (int x, int y, int channel, double value); void setPixel (int x, int y, Pixel& pixel); void setPixel_ (int x, int y, Pixel& pixel); void fillImage(Pixel p); double getTone(); // OpenGL call wrappers void glDrawPixelsWrapper (); void glTexImage2DWrapper (); void glReadPixelsWrapper (); // file read and write calls, // determines file type int readBMP (const char* filename); int writeBMP (const char* filename); private: int index(int x, int y, int c); int width; int height; int bits; // number of bits per pixel per channel int maxValue; // max that can be stored in bits unsigned char* pixels; // image data }; #endif // IMAGE_H
[ "samuel.l.warren@gmail.com" ]
samuel.l.warren@gmail.com
80dd3909f27f40b83729bab1b975f2c3e655358c
c863dc53ac78d3634eb9ef164ae4cb5d93726a04
/openFrameworks/game/Bush.h
8fb0cd7dcc6d2ff2b6b3c398279b2c21847bfa91
[]
no_license
atbaird/CSE5390_GraphicsLibraryStuff
543dfe694846e8d9c3595a295a41f4e1fbea3caa
a9bc68ed61f1193e8e850cb3eb84838fd0b8b53b
refs/heads/master
2020-12-30T10:10:49.131407
2014-06-30T17:54:29
2014-06-30T17:54:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
290
h
#include "Animation.h" #ifndef BUSH_H #define BUSH_H class Bush { public: Bush(); ~Bush(); void setLocation(float, float); void draw(); void setScale(float, float); float getYSize(); float getXSize(); float getX(); float getY(); private: Animation anim; float x, y; }; #endif
[ "atbaird@smu.edu" ]
atbaird@smu.edu
3fb74d584e2e162f0fb26b540dfc2ebe390cef65
cecfc49fb9254498c3b885ae947cd0d9339f2f9a
/pro.cpp
bdf1b7b505b2bd70d31d559f7e06b188441fcb24
[ "Unlicense" ]
permissive
t3nsor/SPOJ
f6e4755fe08654c9a166e5aaf16f6dcbb6fc5099
03145e8bf2cefb3e49a0cd0da5ec908e924d4728
refs/heads/master
2023-04-28T19:04:32.529674
2023-04-17T23:49:49
2023-04-17T23:49:49
24,963,181
279
130
Unlicense
2020-10-30T00:33:57
2014-10-08T22:07:33
C++
UTF-8
C++
false
false
419
cpp
// 2009-05-05 #include <iostream> #include <set> using namespace std; int main() { int N,n,x; scanf("%d",&N); long long res=0; multiset<int> S; while (N--) { scanf("%d",&n); while (n--) { scanf("%d",&x); S.insert(x); } multiset<int>::iterator begin=S.begin(); multiset<int>::iterator end=S.end(); end--; res+=*end-*begin; S.erase(begin); S.erase(end); } printf("%lld\n",res); return 0; }
[ "bbi5291@gmail.com" ]
bbi5291@gmail.com
4e4592cbe92f46f7a8fb6f9980b624b599219b83
50a52a038a9ba758dc0b413b182ee402c8cd8b93
/vn-spoj/baove/main.cpp
8ebe235fe5ad89b86a22c799999d82909329a207
[]
no_license
tranvansang/online-judge
233572fc74b8e96e27376e21558cb0122f5419ba
368983a461ee71225d8e41d27d21accf45245566
refs/heads/master
2022-07-06T07:25:38.194765
2022-06-22T01:23:11
2022-06-22T01:23:11
91,287,489
0
0
null
null
null
null
UTF-8
C++
false
false
2,046
cpp
#include <bits/stdc++.h> using namespace std; #define PII pair<int,int> #define VI vector<int> #define For(i,a,b) for(auto i = (a); i < (b); i++) #define rep(i,n) For(i,0,(n)) #define fi first #define se second #define mp make_pair #define pb push_back #define all(a) (a).begin(), (a).end() #define trav(it,x) for(auto it = (x).begin(); it != (x).end(); it++) #define ll long long #define MAXN 5000 #define MAXS 65000 #define MAXM 10000 int start[MAXN], nxt[MAXM * 2], adj[MAXM * 2], c[MAXM * 2], f[MAXM * 2], trace[MAXN], v[MAXM * 2]; bool visited[MAXN]; int n, m(0); int reverseEdge(int k) { return k ^ 1; } void addEdge(int a, int b, int s) { nxt[m] = start[a]; adj[m] = b; v[m] = a; c[m] = s; start[a] = m; m++; } bool bfs(int init) { queue<int> q; q.push(init); visited[init] = true; while (!q.empty()) { int x = q.front(); q.pop(); if (x == 0) return true; for(int k = start[x]; k!= -1; k = nxt[k]) { int y = adj[k]; if (!visited[y]) { int cost = c[k]; if (cost > 0 ? cost > f[k] : f[k]) { trace[y] = k; visited[y] = true; q.push(y); } } } } return false; } int main(){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); scanf("%d", &n); fill_n(start, n, -1); int a, b, s; while (scanf("%d%d%d", &a, &b, &s) == 3) { if (s) { a--;b--; addEdge(a, b, s); addEdge(b, a, -s); } }; fill_n(f, m, 0); fill_n(visited, n, false); while (bfs(n - 1)) { int minCost = -1; for (int y = 0; y != n - 1; y = v[trace[y]]) { int k = trace[y]; int cost = c[k]; int augment = cost > 0 ? cost - f[k] : f[k]; if (minCost == -1 || minCost > augment) minCost = augment; } for (int y = 0; y != n - 1; y = v[trace[y]]) { int k = trace[y]; if (c[k] > 0) { f[k] += minCost; f[reverseEdge(k)] += minCost; } else { f[k] -= minCost; f[reverseEdge(k)] -= minCost; } } fill_n(visited, n, false); } int sum = 0; for (int k = start[n - 1]; k != -1; k = nxt[k]) { if (c[k] > 0) sum += f[k]; } cout << sum; return 0; }
[ "me@transa.ng" ]
me@transa.ng
f85d2007389739f77e74a542550486b8035fda8c
9d6f8dfe3f74390e35d43f2f6d072a71d2237828
/grid_path.cpp
c35bb72a667424cbc94340aceb875bbddfd7c826
[]
no_license
wanghw1003/EBAStar
35bbe1d98c124b72c513d87cb840490ff711f015
814075cd25c2ac4c25f9d59b0d40c3d335abc60e
refs/heads/master
2023-07-17T14:12:55.912465
2021-08-30T11:15:14
2021-08-30T11:15:14
401,306,381
6
1
null
null
null
null
UTF-8
C++
false
false
3,863
cpp
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2008, 2013, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Eitan Marder-Eppstein * David V. Lu!! *********************************************************************/ #include <global_planner/grid_path.h> #include <algorithm> #include <stdio.h> namespace global_planner { bool GridPath::getPath(float* potential, double start_x, double start_y, double end_x, double end_y, std::vector<std::pair<float, float> >& path) { std::pair<float, float> current; current.first = end_x; current.second = end_y; int start_index = getIndex(start_x, start_y); path.push_back(current); int c = 0; int ns = xs_ * ys_; while (getIndex(current.first, current.second) != start_index) { float min_val = 1e10; int min_x = 0, min_y = 0; for (int xd = -1; xd <= 1; xd++) { for (int yd = -1; yd <= 1; yd++) { if (xd == 0 && yd == 0) continue; //8个方向 int x = current.first + xd, y = current.second + yd; int index = getIndex(x, y); //判断潜力值最小的 if (potential[index] < min_val) { min_val = potential[index]; min_x = x; min_y = y; } } } if (min_x == 0 && min_y == 0) return false; //在此处对生成路径进行平滑化处理// if ( (path[1].first == min_x) || (( path[1].second == (min_y+2) ) && ( path[1].second == (min_y-2) )) ){ path.pop_back(); current.first = min_x; path.push_back(current); } if ( (path[1].second == min_y) || (( path[1].first == (min_x+2) ) && ( path[1].first == (min_x-2) )) ){ path.pop_back(); current.second = min_y; path.push_back(current); } //***************************// current.first = min_x; current.second = min_y; path.push_back(current); if(c++>ns*4){ return false; } } return true; } } //end namespace global_planner
[ "210271138@qq.com" ]
210271138@qq.com
89fb4e6fe00e5a5ebc6c51a5df1a5b1c08d61ebe
09d881298342dbb1be3f83e5f314e2d5946969b9
/cc3k/character.h
ce0972ed5903d25373296ffe77f0471d5da0d73f
[]
no_license
BryanSun-24/cc3k
cf88eb930d675c33f4fa3c2dbe22ac34557e0288
cc0e67e0ffb7ac4de9fc00d283eaa321f913755b
refs/heads/master
2022-12-04T02:49:43.804765
2020-08-16T03:28:55
2020-08-16T03:28:55
285,062,167
0
0
null
null
null
null
UTF-8
C++
false
false
587
h
#ifndef CHARACTER_H #define CHARACTER_H #include <string> #include "state.h" class Character: public State { int health; int attack; int defense; int gold; bool Alive; std::string race; public: Character(int x, int y, int health, int attack, int defense, int gold, std::string race); virtual ~Character() {}; void addHealth(int health); void setMaxHealth(int health); void addGold(int gold); int getGold(); int getAttack(); int getHealth(); int getDefense(); bool isAlive(); std::string getRaceType(); }; #endif
[ "bryant.kai1227@gmail.com" ]
bryant.kai1227@gmail.com
9f0c3f208f91128db39318228a838f3b0f09c77e
dd39c678bfb14fc437a0469f95c37183bdbb19a4
/src/src/vocation.h
6874f2b0060fed16415e916adb1630148c84edfe
[]
no_license
LeandroPerrotta/DarghosTFS04_v4
ea14d06066f5fc1480ccc8007019bbd6b33bd58f
173d9ec26011b17dd4102b3539de65ab3ea15017
refs/heads/master
2023-06-17T03:24:02.913872
2021-07-17T21:10:19
2021-07-17T21:10:19
387,035,938
0
0
null
null
null
null
UTF-8
C++
false
false
5,252
h
//////////////////////////////////////////////////////////////////////// // OpenTibia - an opensource roleplaying game //////////////////////////////////////////////////////////////////////// // 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 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU 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/>. //////////////////////////////////////////////////////////////////////// #ifndef __OTSERV_VOCATION__ #define __OTSERV_VOCATION__ #include "otsystem.h" #include "enums.h" enum multiplier_t { MULTIPLIER_FIRST = 0, MULTIPLIER_MELEE = MULTIPLIER_FIRST, MULTIPLIER_DISTANCE = 1, MULTIPLIER_DEFENSE = 2, MULTIPLIER_MAGICDEFENSE = 3, MULTIPLIER_ARMOR = 4, MULTIPLIER_MAGIC = 5, MULTIPLIER_HEALING = 6, MULTIPLIER_WAND = 7, MULTIPLIER_MANA = 8, MULTIPLIER_LAST = MULTIPLIER_MANA }; enum gain_t { GAIN_FIRST = 0, GAIN_HEALTH = GAIN_FIRST, GAIN_MANA = 1, GAIN_SOUL = 2, GAIN_LAST = GAIN_SOUL }; class Vocation { public: virtual ~Vocation(); Vocation() {reset();} Vocation(uint32_t _id): id(_id) {reset();} void reset(); uint32_t getId() const {return id;} void setId(int32_t v) {id = v;} uint32_t getFromVocation() const {return fromVocation;} void setFromVocation(int32_t v) {fromVocation = v;} const std::string& getName() const {return name;} void setName(const std::string& v) {name = v;} const std::string& getDescription() const {return description;} void setDescription(const std::string& v) {description = v;} bool isAttackable() const {return attackable;} void setAttackable(bool v) {attackable = v;} bool isPremiumNeeded() const {return needPremium;} void setNeedPremium(bool v) {needPremium = v;} uint32_t getAttackSpeed() const {return attackSpeed;} void setAttackSpeed(uint32_t v) {attackSpeed = v;} uint32_t getBaseSpeed() const {return baseSpeed;} void setBaseSpeed(uint32_t v) {baseSpeed = v;} int32_t getLessLoss() const {return lessLoss;} void setLessLoss(int32_t v) {lessLoss = v;} int32_t getGainCap() const {return capGain;} void setGainCap(int32_t v) {capGain = v;} uint32_t getGain(gain_t type) const {return gain[type];} void setGain(gain_t type, uint32_t v) {gain[type] = v;} uint32_t getGainTicks(gain_t type) const {return gainTicks[type];} void setGainTicks(gain_t type, uint32_t v) {gainTicks[type] = v;} uint32_t getGainAmount(gain_t type) const {return gainAmount[type];} void setGainAmount(gain_t type, uint32_t v) {gainAmount[type] = v;} float getMultiplier(multiplier_t type) const {return formulaMultipliers[type];} void setMultiplier(multiplier_t type, float v) {formulaMultipliers[type] = v;} #ifdef __DARGHOS_CUSTOM__ uint32_t getCriticalChance() const {return m_criticalChance;} void setCriticalChance(uint32_t chance) {m_criticalChance = chance;} #endif int16_t getAbsorb(CombatType_t combat) const {return absorb[combat];} void increaseAbsorb(CombatType_t combat, int16_t v) {absorb[combat] += v;} int16_t getReflect(CombatType_t combat) const; void increaseReflect(Reflect_t type, CombatType_t combat, int16_t v) {reflect[type][combat] += v;} double getExperienceMultiplier() const {return skillMultipliers[SKILL__LEVEL];} void setSkillMultiplier(skills_t s, float v) {skillMultipliers[s] = v;} void setSkillBase(skills_t s, uint32_t v) {skillBase[s] = v;} uint32_t getReqSkillTries(int32_t skill, int32_t level); uint64_t getReqMana(uint32_t magLevel); private: typedef std::map<uint32_t, uint32_t> cacheMap; cacheMap cacheSkill[SKILL_LAST + 1]; cacheMap cacheMana; bool attackable, needPremium; int32_t lessLoss, capGain; uint32_t id, fromVocation, baseSpeed, attackSpeed; std::string name, description; #ifdef __DARGHOS_CUSTOM__ uint32_t m_criticalChance; #endif int16_t absorb[COMBAT_LAST + 1], reflect[REFLECT_LAST + 1][COMBAT_LAST + 1]; uint32_t gain[GAIN_LAST + 1], gainTicks[GAIN_LAST + 1], gainAmount[GAIN_LAST + 1], skillBase[SKILL_LAST + 1]; float skillMultipliers[SKILL__LAST + 1], formulaMultipliers[MULTIPLIER_LAST + 1]; }; typedef std::map<uint32_t, Vocation*> VocationsMap; class Vocations { public: virtual ~Vocations() {clear();} static Vocations* getInstance() { static Vocations instance; return &instance; } bool reload(); bool loadFromXml(); bool parseVocationNode(xmlNodePtr p); Vocation* getVocation(uint32_t vocId); int32_t getVocationId(const std::string& name); int32_t getPromotedVocation(uint32_t vocationId); VocationsMap::iterator getFirstVocation() {return vocationsMap.begin();} VocationsMap::iterator getLastVocation() {return vocationsMap.end();} private: static Vocation defVoc; VocationsMap vocationsMap; Vocations() {} void clear(); }; #endif
[ "leandro_perrotta@hotmail.com" ]
leandro_perrotta@hotmail.com
38acf433c29df03feb7eeabe81a2044663c3ed70
290b4c7ca63a975b38e55018cc38bd2766e14639
/ORC_app/jni-build/jni/include/external/eigen_archive/eigen-eigen-4c94692de3e5/Eigen/src/Core/ProductEvaluators.h
d9fd888cfd801291b8ea9af6cccbaa1a87c89b62
[ "MIT", "Minpack", "MPL-2.0", "LGPL-2.1-only", "GPL-3.0-only", "BSD-3-Clause", "LGPL-2.0-or-later", "LGPL-2.1-or-later" ]
permissive
luoabd/EMNIST-ORC
1233c373abcc3ed237c2ec86491b29c0b9223894
8c2d633a9b4d5214e908550812f6a2489ba9eb72
refs/heads/master
2022-12-27T14:03:55.046933
2020-01-16T15:20:04
2020-01-16T15:20:04
234,325,497
0
1
MIT
2022-12-11T13:32:42
2020-01-16T13:25:23
C++
UTF-8
C++
false
false
46,234
h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com> // Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr> // Copyright (C) 2011 Jitse Niesen <jitse@maths.leeds.ac.uk> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_PRODUCTEVALUATORS_H #define EIGEN_PRODUCTEVALUATORS_H namespace Eigen { namespace internal { /** \internal * Evaluator of a product expression. * Since products require special treatments to handle all possible cases, * we simply deffer the evaluation logic to a product_evaluator class * which offers more partial specialization possibilities. * * \sa class product_evaluator */ template<typename Lhs, typename Rhs, int Options> struct evaluator<Product<Lhs, Rhs, Options> > : public product_evaluator<Product<Lhs, Rhs, Options> > { typedef Product<Lhs, Rhs, Options> XprType; typedef product_evaluator<XprType> Base; EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : Base(xpr) {} }; // Catch scalar * ( A * B ) and transform it to (A*scalar) * B // TODO we should apply that rule only if that's really helpful template<typename Lhs, typename Rhs, typename Scalar> struct evaluator_assume_aliasing<CwiseUnaryOp<internal::scalar_multiple_op<Scalar>, const Product<Lhs, Rhs, DefaultProduct> > > { static const bool value = true; }; template<typename Lhs, typename Rhs, typename Scalar> struct evaluator<CwiseUnaryOp<internal::scalar_multiple_op<Scalar>, const Product<Lhs, Rhs, DefaultProduct> > > : public evaluator<Product<CwiseUnaryOp<internal::scalar_multiple_op<Scalar>,const Lhs>, Rhs, DefaultProduct> > { typedef CwiseUnaryOp<internal::scalar_multiple_op<Scalar>, const Product<Lhs, Rhs, DefaultProduct> > XprType; typedef evaluator<Product<CwiseUnaryOp<internal::scalar_multiple_op<Scalar>,const Lhs>, Rhs, DefaultProduct> > Base; EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : Base(xpr.functor().m_other * xpr.nestedExpression().lhs() * xpr.nestedExpression().rhs()) {} }; template<typename Lhs, typename Rhs, int DiagIndex> struct evaluator<Diagonal<const Product<Lhs, Rhs, DefaultProduct>, DiagIndex> > : public evaluator<Diagonal<const Product<Lhs, Rhs, LazyProduct>, DiagIndex> > { typedef Diagonal<const Product<Lhs, Rhs, DefaultProduct>, DiagIndex> XprType; typedef evaluator<Diagonal<const Product<Lhs, Rhs, LazyProduct>, DiagIndex> > Base; EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : Base(Diagonal<const Product<Lhs, Rhs, LazyProduct>, DiagIndex>( Product<Lhs, Rhs, LazyProduct>(xpr.nestedExpression().lhs(), xpr.nestedExpression().rhs()), xpr.index() )) {} }; // Helper class to perform a matrix product with the destination at hand. // Depending on the sizes of the factors, there are different evaluation strategies // as controlled by internal::product_type. template< typename Lhs, typename Rhs, typename LhsShape = typename evaluator_traits<Lhs>::Shape, typename RhsShape = typename evaluator_traits<Rhs>::Shape, int ProductType = internal::product_type<Lhs,Rhs>::value> struct generic_product_impl; template<typename Lhs, typename Rhs> struct evaluator_assume_aliasing<Product<Lhs, Rhs, DefaultProduct> > { static const bool value = true; }; // This is the default evaluator implementation for products: // It creates a temporary and call generic_product_impl template<typename Lhs, typename Rhs, int Options, int ProductTag, typename LhsShape, typename RhsShape> struct product_evaluator<Product<Lhs, Rhs, Options>, ProductTag, LhsShape, RhsShape> : public evaluator<typename Product<Lhs, Rhs, Options>::PlainObject> { typedef Product<Lhs, Rhs, Options> XprType; typedef typename XprType::PlainObject PlainObject; typedef evaluator<PlainObject> Base; enum { Flags = Base::Flags | EvalBeforeNestingBit }; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit product_evaluator(const XprType& xpr) : m_result(xpr.rows(), xpr.cols()) { ::new (static_cast<Base*>(this)) Base(m_result); // FIXME shall we handle nested_eval here?, // if so, then we must take care at removing the call to nested_eval in the specializations (e.g., in permutation_matrix_product, transposition_matrix_product, etc.) // typedef typename internal::nested_eval<Lhs,Rhs::ColsAtCompileTime>::type LhsNested; // typedef typename internal::nested_eval<Rhs,Lhs::RowsAtCompileTime>::type RhsNested; // typedef typename internal::remove_all<LhsNested>::type LhsNestedCleaned; // typedef typename internal::remove_all<RhsNested>::type RhsNestedCleaned; // // const LhsNested lhs(xpr.lhs()); // const RhsNested rhs(xpr.rhs()); // // generic_product_impl<LhsNestedCleaned, RhsNestedCleaned>::evalTo(m_result, lhs, rhs); generic_product_impl<Lhs, Rhs, LhsShape, RhsShape, ProductTag>::evalTo(m_result, xpr.lhs(), xpr.rhs()); } protected: PlainObject m_result; }; // Dense = Product template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar> struct Assignment<DstXprType, Product<Lhs,Rhs,Options>, internal::assign_op<Scalar>, Dense2Dense, typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct),Scalar>::type> { typedef Product<Lhs,Rhs,Options> SrcXprType; static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op<Scalar> &) { // FIXME shall we handle nested_eval here? generic_product_impl<Lhs, Rhs>::evalTo(dst, src.lhs(), src.rhs()); } }; // Dense += Product template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar> struct Assignment<DstXprType, Product<Lhs,Rhs,Options>, internal::add_assign_op<Scalar>, Dense2Dense, typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct),Scalar>::type> { typedef Product<Lhs,Rhs,Options> SrcXprType; static void run(DstXprType &dst, const SrcXprType &src, const internal::add_assign_op<Scalar> &) { // FIXME shall we handle nested_eval here? generic_product_impl<Lhs, Rhs>::addTo(dst, src.lhs(), src.rhs()); } }; // Dense -= Product template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar> struct Assignment<DstXprType, Product<Lhs,Rhs,Options>, internal::sub_assign_op<Scalar>, Dense2Dense, typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct),Scalar>::type> { typedef Product<Lhs,Rhs,Options> SrcXprType; static void run(DstXprType &dst, const SrcXprType &src, const internal::sub_assign_op<Scalar> &) { // FIXME shall we handle nested_eval here? generic_product_impl<Lhs, Rhs>::subTo(dst, src.lhs(), src.rhs()); } }; // Dense ?= scalar * Product // TODO we should apply that rule if that's really helpful // for instance, this is not good for inner products template< typename DstXprType, typename Lhs, typename Rhs, typename AssignFunc, typename Scalar, typename ScalarBis> struct Assignment<DstXprType, CwiseUnaryOp<internal::scalar_multiple_op<ScalarBis>, const Product<Lhs,Rhs,DefaultProduct> >, AssignFunc, Dense2Dense, Scalar> { typedef CwiseUnaryOp<internal::scalar_multiple_op<ScalarBis>, const Product<Lhs,Rhs,DefaultProduct> > SrcXprType; static void run(DstXprType &dst, const SrcXprType &src, const AssignFunc& func) { call_assignment_no_alias(dst, (src.functor().m_other * src.nestedExpression().lhs())*src.nestedExpression().rhs(), func); } }; //---------------------------------------- // Catch "Dense ?= xpr + Product<>" expression to save one temporary // FIXME we could probably enable these rules for any product, i.e., not only Dense and DefaultProduct // TODO enable it for "Dense ?= xpr - Product<>" as well. template<typename OtherXpr, typename Lhs, typename Rhs> struct evaluator_assume_aliasing<CwiseBinaryOp<internal::scalar_sum_op<typename OtherXpr::Scalar>, const OtherXpr, const Product<Lhs,Rhs,DefaultProduct> >, DenseShape > { static const bool value = true; }; template<typename DstXprType, typename OtherXpr, typename ProductType, typename Scalar, typename Func1, typename Func2> struct assignment_from_xpr_plus_product { typedef CwiseBinaryOp<internal::scalar_sum_op<Scalar>, const OtherXpr, const ProductType> SrcXprType; static void run(DstXprType &dst, const SrcXprType &src, const Func1& func) { call_assignment_no_alias(dst, src.lhs(), func); call_assignment_no_alias(dst, src.rhs(), Func2()); } }; template< typename DstXprType, typename OtherXpr, typename Lhs, typename Rhs, typename Scalar> struct Assignment<DstXprType, CwiseBinaryOp<internal::scalar_sum_op<Scalar>, const OtherXpr, const Product<Lhs,Rhs,DefaultProduct> >, internal::assign_op<Scalar>, Dense2Dense> : assignment_from_xpr_plus_product<DstXprType, OtherXpr, Product<Lhs,Rhs,DefaultProduct>, Scalar, internal::assign_op<Scalar>, internal::add_assign_op<Scalar> > {}; template< typename DstXprType, typename OtherXpr, typename Lhs, typename Rhs, typename Scalar> struct Assignment<DstXprType, CwiseBinaryOp<internal::scalar_sum_op<Scalar>, const OtherXpr, const Product<Lhs,Rhs,DefaultProduct> >, internal::add_assign_op<Scalar>, Dense2Dense> : assignment_from_xpr_plus_product<DstXprType, OtherXpr, Product<Lhs,Rhs,DefaultProduct>, Scalar, internal::add_assign_op<Scalar>, internal::add_assign_op<Scalar> > {}; template< typename DstXprType, typename OtherXpr, typename Lhs, typename Rhs, typename Scalar> struct Assignment<DstXprType, CwiseBinaryOp<internal::scalar_sum_op<Scalar>, const OtherXpr, const Product<Lhs,Rhs,DefaultProduct> >, internal::sub_assign_op<Scalar>, Dense2Dense> : assignment_from_xpr_plus_product<DstXprType, OtherXpr, Product<Lhs,Rhs,DefaultProduct>, Scalar, internal::sub_assign_op<Scalar>, internal::sub_assign_op<Scalar> > {}; //---------------------------------------- template<typename Lhs, typename Rhs> struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,InnerProduct> { template<typename Dst> static inline void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { dst.coeffRef(0,0) = (lhs.transpose().cwiseProduct(rhs)).sum(); } template<typename Dst> static inline void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { dst.coeffRef(0,0) += (lhs.transpose().cwiseProduct(rhs)).sum(); } template<typename Dst> static void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { dst.coeffRef(0,0) -= (lhs.transpose().cwiseProduct(rhs)).sum(); } }; /*********************************************************************** * Implementation of outer dense * dense vector product ***********************************************************************/ // Column major result template<typename Dst, typename Lhs, typename Rhs, typename Func> EIGEN_DONT_INLINE void outer_product_selector_run(Dst& dst, const Lhs &lhs, const Rhs &rhs, const Func& func, const false_type&) { evaluator<Rhs> rhsEval(rhs); typename nested_eval<Lhs,Rhs::SizeAtCompileTime>::type actual_lhs(lhs); // FIXME if cols is large enough, then it might be useful to make sure that lhs is sequentially stored // FIXME not very good if rhs is real and lhs complex while alpha is real too const Index cols = dst.cols(); for (Index j=0; j<cols; ++j) func(dst.col(j), rhsEval.coeff(0,j) * actual_lhs); } // Row major result template<typename Dst, typename Lhs, typename Rhs, typename Func> EIGEN_DONT_INLINE void outer_product_selector_run(Dst& dst, const Lhs &lhs, const Rhs &rhs, const Func& func, const true_type&) { evaluator<Lhs> lhsEval(lhs); typename nested_eval<Rhs,Lhs::SizeAtCompileTime>::type actual_rhs(rhs); // FIXME if rows is large enough, then it might be useful to make sure that rhs is sequentially stored // FIXME not very good if lhs is real and rhs complex while alpha is real too const Index rows = dst.rows(); for (Index i=0; i<rows; ++i) func(dst.row(i), lhsEval.coeff(i,0) * actual_rhs); } template<typename Lhs, typename Rhs> struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,OuterProduct> { template<typename T> struct is_row_major : internal::conditional<(int(T::Flags)&RowMajorBit), internal::true_type, internal::false_type>::type {}; typedef typename Product<Lhs,Rhs>::Scalar Scalar; // TODO it would be nice to be able to exploit our *_assign_op functors for that purpose struct set { template<typename Dst, typename Src> void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() = src; } }; struct add { template<typename Dst, typename Src> void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() += src; } }; struct sub { template<typename Dst, typename Src> void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() -= src; } }; struct adds { Scalar m_scale; explicit adds(const Scalar& s) : m_scale(s) {} template<typename Dst, typename Src> void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() += m_scale * src; } }; template<typename Dst> static inline void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { internal::outer_product_selector_run(dst, lhs, rhs, set(), is_row_major<Dst>()); } template<typename Dst> static inline void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { internal::outer_product_selector_run(dst, lhs, rhs, add(), is_row_major<Dst>()); } template<typename Dst> static inline void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { internal::outer_product_selector_run(dst, lhs, rhs, sub(), is_row_major<Dst>()); } template<typename Dst> static inline void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { internal::outer_product_selector_run(dst, lhs, rhs, adds(alpha), is_row_major<Dst>()); } }; // This base class provides default implementations for evalTo, addTo, subTo, in terms of scaleAndAddTo template<typename Lhs, typename Rhs, typename Derived> struct generic_product_impl_base { typedef typename Product<Lhs,Rhs>::Scalar Scalar; template<typename Dst> static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { dst.setZero(); scaleAndAddTo(dst, lhs, rhs, Scalar(1)); } template<typename Dst> static void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { scaleAndAddTo(dst,lhs, rhs, Scalar(1)); } template<typename Dst> static void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { scaleAndAddTo(dst, lhs, rhs, Scalar(-1)); } template<typename Dst> static void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { Derived::scaleAndAddTo(dst,lhs,rhs,alpha); } }; template<typename Lhs, typename Rhs> struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemvProduct> : generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemvProduct> > { typedef typename Product<Lhs,Rhs>::Scalar Scalar; enum { Side = Lhs::IsVectorAtCompileTime ? OnTheLeft : OnTheRight }; typedef typename internal::conditional<int(Side)==OnTheRight,Lhs,Rhs>::type MatrixType; template<typename Dest> static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { internal::gemv_dense_selector<Side, (int(MatrixType::Flags)&RowMajorBit) ? RowMajor : ColMajor, bool(internal::blas_traits<MatrixType>::HasUsableDirectAccess) >::run(lhs, rhs, dst, alpha); } }; template<typename Lhs, typename Rhs> struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,CoeffBasedProductMode> { typedef typename Product<Lhs,Rhs>::Scalar Scalar; template<typename Dst> static inline void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { // Same as: dst.noalias() = lhs.lazyProduct(rhs); // but easier on the compiler side call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::assign_op<Scalar>()); } template<typename Dst> static inline void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { // dst.noalias() += lhs.lazyProduct(rhs); call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::add_assign_op<Scalar>()); } template<typename Dst> static inline void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { // dst.noalias() -= lhs.lazyProduct(rhs); call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::sub_assign_op<Scalar>()); } // template<typename Dst> // static inline void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) // { dst.noalias() += alpha * lhs.lazyProduct(rhs); } }; // This specialization enforces the use of a coefficient-based evaluation strategy template<typename Lhs, typename Rhs> struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,LazyCoeffBasedProductMode> : generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,CoeffBasedProductMode> {}; // Case 2: Evaluate coeff by coeff // // This is mostly taken from CoeffBasedProduct.h // The main difference is that we add an extra argument to the etor_product_*_impl::run() function // for the inner dimension of the product, because evaluator object do not know their size. template<int Traversal, int UnrollingIndex, typename Lhs, typename Rhs, typename RetScalar> struct etor_product_coeff_impl; template<int StorageOrder, int UnrollingIndex, typename Lhs, typename Rhs, typename Packet, int LoadMode> struct etor_product_packet_impl; template<typename Lhs, typename Rhs, int ProductTag> struct product_evaluator<Product<Lhs, Rhs, LazyProduct>, ProductTag, DenseShape, DenseShape> : evaluator_base<Product<Lhs, Rhs, LazyProduct> > { typedef Product<Lhs, Rhs, LazyProduct> XprType; typedef typename XprType::Scalar Scalar; typedef typename XprType::CoeffReturnType CoeffReturnType; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit product_evaluator(const XprType& xpr) : m_lhs(xpr.lhs()), m_rhs(xpr.rhs()), m_lhsImpl(m_lhs), // FIXME the creation of the evaluator objects should result in a no-op, but check that! m_rhsImpl(m_rhs), // Moreover, they are only useful for the packet path, so we could completely disable them when not needed, // or perhaps declare them on the fly on the packet method... We have experiment to check what's best. m_innerDim(xpr.lhs().cols()) { EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits<Scalar>::MulCost); EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits<Scalar>::AddCost); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } // Everything below here is taken from CoeffBasedProduct.h typedef typename internal::nested_eval<Lhs,Rhs::ColsAtCompileTime>::type LhsNested; typedef typename internal::nested_eval<Rhs,Lhs::RowsAtCompileTime>::type RhsNested; typedef typename internal::remove_all<LhsNested>::type LhsNestedCleaned; typedef typename internal::remove_all<RhsNested>::type RhsNestedCleaned; typedef evaluator<LhsNestedCleaned> LhsEtorType; typedef evaluator<RhsNestedCleaned> RhsEtorType; enum { RowsAtCompileTime = LhsNestedCleaned::RowsAtCompileTime, ColsAtCompileTime = RhsNestedCleaned::ColsAtCompileTime, InnerSize = EIGEN_SIZE_MIN_PREFER_FIXED(LhsNestedCleaned::ColsAtCompileTime, RhsNestedCleaned::RowsAtCompileTime), MaxRowsAtCompileTime = LhsNestedCleaned::MaxRowsAtCompileTime, MaxColsAtCompileTime = RhsNestedCleaned::MaxColsAtCompileTime }; typedef typename find_best_packet<Scalar,RowsAtCompileTime>::type LhsVecPacketType; typedef typename find_best_packet<Scalar,ColsAtCompileTime>::type RhsVecPacketType; enum { LhsCoeffReadCost = LhsEtorType::CoeffReadCost, RhsCoeffReadCost = RhsEtorType::CoeffReadCost, CoeffReadCost = InnerSize==0 ? NumTraits<Scalar>::ReadCost : InnerSize == Dynamic ? HugeCost : InnerSize * (NumTraits<Scalar>::MulCost + LhsCoeffReadCost + RhsCoeffReadCost) + (InnerSize - 1) * NumTraits<Scalar>::AddCost, Unroll = CoeffReadCost <= EIGEN_UNROLLING_LIMIT, LhsFlags = LhsEtorType::Flags, RhsFlags = RhsEtorType::Flags, LhsRowMajor = LhsFlags & RowMajorBit, RhsRowMajor = RhsFlags & RowMajorBit, LhsVecPacketSize = unpacket_traits<LhsVecPacketType>::size, RhsVecPacketSize = unpacket_traits<RhsVecPacketType>::size, // Here, we don't care about alignment larger than the usable packet size. LhsAlignment = EIGEN_PLAIN_ENUM_MIN(LhsEtorType::Alignment,LhsVecPacketSize*int(sizeof(typename LhsNestedCleaned::Scalar))), RhsAlignment = EIGEN_PLAIN_ENUM_MIN(RhsEtorType::Alignment,RhsVecPacketSize*int(sizeof(typename RhsNestedCleaned::Scalar))), SameType = is_same<typename LhsNestedCleaned::Scalar,typename RhsNestedCleaned::Scalar>::value, CanVectorizeRhs = RhsRowMajor && (RhsFlags & PacketAccessBit) && (ColsAtCompileTime == Dynamic || ((ColsAtCompileTime % RhsVecPacketSize) == 0) ), CanVectorizeLhs = (!LhsRowMajor) && (LhsFlags & PacketAccessBit) && (RowsAtCompileTime == Dynamic || ((RowsAtCompileTime % LhsVecPacketSize) == 0) ), EvalToRowMajor = (MaxRowsAtCompileTime==1&&MaxColsAtCompileTime!=1) ? 1 : (MaxColsAtCompileTime==1&&MaxRowsAtCompileTime!=1) ? 0 : (RhsRowMajor && !CanVectorizeLhs), Flags = ((unsigned int)(LhsFlags | RhsFlags) & HereditaryBits & ~RowMajorBit) | (EvalToRowMajor ? RowMajorBit : 0) // TODO enable vectorization for mixed types | (SameType && (CanVectorizeLhs || CanVectorizeRhs) ? PacketAccessBit : 0) | (XprType::IsVectorAtCompileTime ? LinearAccessBit : 0), LhsOuterStrideBytes = int(LhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename LhsNestedCleaned::Scalar)), RhsOuterStrideBytes = int(RhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename RhsNestedCleaned::Scalar)), Alignment = CanVectorizeLhs ? (LhsOuterStrideBytes<0 || (int(LhsOuterStrideBytes) % EIGEN_PLAIN_ENUM_MAX(1,LhsAlignment))!=0 ? 0 : LhsAlignment) : CanVectorizeRhs ? (RhsOuterStrideBytes<0 || (int(RhsOuterStrideBytes) % EIGEN_PLAIN_ENUM_MAX(1,RhsAlignment))!=0 ? 0 : RhsAlignment) : 0, /* CanVectorizeInner deserves special explanation. It does not affect the product flags. It is not used outside * of Product. If the Product itself is not a packet-access expression, there is still a chance that the inner * loop of the product might be vectorized. This is the meaning of CanVectorizeInner. Since it doesn't affect * the Flags, it is safe to make this value depend on ActualPacketAccessBit, that doesn't affect the ABI. */ CanVectorizeInner = SameType && LhsRowMajor && (!RhsRowMajor) && (LhsFlags & RhsFlags & ActualPacketAccessBit) && (InnerSize % packet_traits<Scalar>::size == 0) }; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index row, Index col) const { return (m_lhs.row(row).transpose().cwiseProduct( m_rhs.col(col) )).sum(); } /* Allow index-based non-packet access. It is impossible though to allow index-based packed access, * which is why we don't set the LinearAccessBit. * TODO: this seems possible when the result is a vector */ EIGEN_DEVICE_FUNC const CoeffReturnType coeff(Index index) const { const Index row = RowsAtCompileTime == 1 ? 0 : index; const Index col = RowsAtCompileTime == 1 ? index : 0; return (m_lhs.row(row).transpose().cwiseProduct( m_rhs.col(col) )).sum(); } template<int LoadMode, typename PacketType> const PacketType packet(Index row, Index col) const { PacketType res; typedef etor_product_packet_impl<bool(int(Flags)&RowMajorBit) ? RowMajor : ColMajor, Unroll ? int(InnerSize) : Dynamic, LhsEtorType, RhsEtorType, PacketType, LoadMode> PacketImpl; PacketImpl::run(row, col, m_lhsImpl, m_rhsImpl, m_innerDim, res); return res; } template<int LoadMode, typename PacketType> const PacketType packet(Index index) const { const Index row = RowsAtCompileTime == 1 ? 0 : index; const Index col = RowsAtCompileTime == 1 ? index : 0; return packet<LoadMode,PacketType>(row,col); } protected: const LhsNested m_lhs; const RhsNested m_rhs; LhsEtorType m_lhsImpl; RhsEtorType m_rhsImpl; // TODO: Get rid of m_innerDim if known at compile time Index m_innerDim; }; template<typename Lhs, typename Rhs> struct product_evaluator<Product<Lhs, Rhs, DefaultProduct>, LazyCoeffBasedProductMode, DenseShape, DenseShape> : product_evaluator<Product<Lhs, Rhs, LazyProduct>, CoeffBasedProductMode, DenseShape, DenseShape> { typedef Product<Lhs, Rhs, DefaultProduct> XprType; typedef Product<Lhs, Rhs, LazyProduct> BaseProduct; typedef product_evaluator<BaseProduct, CoeffBasedProductMode, DenseShape, DenseShape> Base; enum { Flags = Base::Flags | EvalBeforeNestingBit }; EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) : Base(BaseProduct(xpr.lhs(),xpr.rhs())) {} }; /**************************************** *** Coeff based product, Packet path *** ****************************************/ template<int UnrollingIndex, typename Lhs, typename Rhs, typename Packet, int LoadMode> struct etor_product_packet_impl<RowMajor, UnrollingIndex, Lhs, Rhs, Packet, LoadMode> { static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet &res) { etor_product_packet_impl<RowMajor, UnrollingIndex-1, Lhs, Rhs, Packet, LoadMode>::run(row, col, lhs, rhs, innerDim, res); res = pmadd(pset1<Packet>(lhs.coeff(row, UnrollingIndex-1)), rhs.template packet<LoadMode,Packet>(UnrollingIndex-1, col), res); } }; template<int UnrollingIndex, typename Lhs, typename Rhs, typename Packet, int LoadMode> struct etor_product_packet_impl<ColMajor, UnrollingIndex, Lhs, Rhs, Packet, LoadMode> { static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet &res) { etor_product_packet_impl<ColMajor, UnrollingIndex-1, Lhs, Rhs, Packet, LoadMode>::run(row, col, lhs, rhs, innerDim, res); res = pmadd(lhs.template packet<LoadMode,Packet>(row, UnrollingIndex-1), pset1<Packet>(rhs.coeff(UnrollingIndex-1, col)), res); } }; template<typename Lhs, typename Rhs, typename Packet, int LoadMode> struct etor_product_packet_impl<RowMajor, 1, Lhs, Rhs, Packet, LoadMode> { static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index /*innerDim*/, Packet &res) { res = pmul(pset1<Packet>(lhs.coeff(row, 0)),rhs.template packet<LoadMode,Packet>(0, col)); } }; template<typename Lhs, typename Rhs, typename Packet, int LoadMode> struct etor_product_packet_impl<ColMajor, 1, Lhs, Rhs, Packet, LoadMode> { static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index /*innerDim*/, Packet &res) { res = pmul(lhs.template packet<LoadMode,Packet>(row, 0), pset1<Packet>(rhs.coeff(0, col))); } }; template<typename Lhs, typename Rhs, typename Packet, int LoadMode> struct etor_product_packet_impl<RowMajor, 0, Lhs, Rhs, Packet, LoadMode> { static EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, const Rhs& /*rhs*/, Index /*innerDim*/, Packet &res) { res = pset1<Packet>(0); } }; template<typename Lhs, typename Rhs, typename Packet, int LoadMode> struct etor_product_packet_impl<ColMajor, 0, Lhs, Rhs, Packet, LoadMode> { static EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, const Rhs& /*rhs*/, Index /*innerDim*/, Packet &res) { res = pset1<Packet>(0); } }; template<typename Lhs, typename Rhs, typename Packet, int LoadMode> struct etor_product_packet_impl<RowMajor, Dynamic, Lhs, Rhs, Packet, LoadMode> { static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet& res) { res = pset1<Packet>(0); for(Index i = 0; i < innerDim; ++i) res = pmadd(pset1<Packet>(lhs.coeff(row, i)), rhs.template packet<LoadMode,Packet>(i, col), res); } }; template<typename Lhs, typename Rhs, typename Packet, int LoadMode> struct etor_product_packet_impl<ColMajor, Dynamic, Lhs, Rhs, Packet, LoadMode> { static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet& res) { res = pset1<Packet>(0); for(Index i = 0; i < innerDim; ++i) res = pmadd(lhs.template packet<LoadMode,Packet>(row, i), pset1<Packet>(rhs.coeff(i, col)), res); } }; /*************************************************************************** * Triangular products ***************************************************************************/ template<int Mode, bool LhsIsTriangular, typename Lhs, bool LhsIsVector, typename Rhs, bool RhsIsVector> struct triangular_product_impl; template<typename Lhs, typename Rhs, int ProductTag> struct generic_product_impl<Lhs,Rhs,TriangularShape,DenseShape,ProductTag> : generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,TriangularShape,DenseShape,ProductTag> > { typedef typename Product<Lhs,Rhs>::Scalar Scalar; template<typename Dest> static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { triangular_product_impl<Lhs::Mode,true,typename Lhs::MatrixType,false,Rhs, Rhs::ColsAtCompileTime==1> ::run(dst, lhs.nestedExpression(), rhs, alpha); } }; template<typename Lhs, typename Rhs, int ProductTag> struct generic_product_impl<Lhs,Rhs,DenseShape,TriangularShape,ProductTag> : generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,TriangularShape,ProductTag> > { typedef typename Product<Lhs,Rhs>::Scalar Scalar; template<typename Dest> static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { triangular_product_impl<Rhs::Mode,false,Lhs,Lhs::RowsAtCompileTime==1, typename Rhs::MatrixType, false>::run(dst, lhs, rhs.nestedExpression(), alpha); } }; /*************************************************************************** * SelfAdjoint products ***************************************************************************/ template <typename Lhs, int LhsMode, bool LhsIsVector, typename Rhs, int RhsMode, bool RhsIsVector> struct selfadjoint_product_impl; template<typename Lhs, typename Rhs, int ProductTag> struct generic_product_impl<Lhs,Rhs,SelfAdjointShape,DenseShape,ProductTag> : generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,SelfAdjointShape,DenseShape,ProductTag> > { typedef typename Product<Lhs,Rhs>::Scalar Scalar; template<typename Dest> static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { selfadjoint_product_impl<typename Lhs::MatrixType,Lhs::Mode,false,Rhs,0,Rhs::IsVectorAtCompileTime>::run(dst, lhs.nestedExpression(), rhs, alpha); } }; template<typename Lhs, typename Rhs, int ProductTag> struct generic_product_impl<Lhs,Rhs,DenseShape,SelfAdjointShape,ProductTag> : generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,SelfAdjointShape,ProductTag> > { typedef typename Product<Lhs,Rhs>::Scalar Scalar; template<typename Dest> static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) { selfadjoint_product_impl<Lhs,0,Lhs::IsVectorAtCompileTime,typename Rhs::MatrixType,Rhs::Mode,false>::run(dst, lhs, rhs.nestedExpression(), alpha); } }; /*************************************************************************** * Diagonal products ***************************************************************************/ template<typename MatrixType, typename DiagonalType, typename Derived, int ProductOrder> struct diagonal_product_evaluator_base : evaluator_base<Derived> { typedef typename scalar_product_traits<typename MatrixType::Scalar, typename DiagonalType::Scalar>::ReturnType Scalar; public: enum { CoeffReadCost = NumTraits<Scalar>::MulCost + evaluator<MatrixType>::CoeffReadCost + evaluator<DiagonalType>::CoeffReadCost, MatrixFlags = evaluator<MatrixType>::Flags, DiagFlags = evaluator<DiagonalType>::Flags, _StorageOrder = MatrixFlags & RowMajorBit ? RowMajor : ColMajor, _ScalarAccessOnDiag = !((int(_StorageOrder) == ColMajor && int(ProductOrder) == OnTheLeft) ||(int(_StorageOrder) == RowMajor && int(ProductOrder) == OnTheRight)), _SameTypes = is_same<typename MatrixType::Scalar, typename DiagonalType::Scalar>::value, // FIXME currently we need same types, but in the future the next rule should be the one //_Vectorizable = bool(int(MatrixFlags)&PacketAccessBit) && ((!_PacketOnDiag) || (_SameTypes && bool(int(DiagFlags)&PacketAccessBit))), _Vectorizable = bool(int(MatrixFlags)&PacketAccessBit) && _SameTypes && (_ScalarAccessOnDiag || (bool(int(DiagFlags)&PacketAccessBit))), _LinearAccessMask = (MatrixType::RowsAtCompileTime==1 || MatrixType::ColsAtCompileTime==1) ? LinearAccessBit : 0, Flags = ((HereditaryBits|_LinearAccessMask) & (unsigned int)(MatrixFlags)) | (_Vectorizable ? PacketAccessBit : 0), Alignment = evaluator<MatrixType>::Alignment }; diagonal_product_evaluator_base(const MatrixType &mat, const DiagonalType &diag) : m_diagImpl(diag), m_matImpl(mat) { EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits<Scalar>::MulCost); EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index idx) const { return m_diagImpl.coeff(idx) * m_matImpl.coeff(idx); } protected: template<int LoadMode,typename PacketType> EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::true_type) const { return internal::pmul(m_matImpl.template packet<LoadMode,PacketType>(row, col), internal::pset1<PacketType>(m_diagImpl.coeff(id))); } template<int LoadMode,typename PacketType> EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::false_type) const { enum { InnerSize = (MatrixType::Flags & RowMajorBit) ? MatrixType::ColsAtCompileTime : MatrixType::RowsAtCompileTime, DiagonalPacketLoadMode = EIGEN_PLAIN_ENUM_MIN(LoadMode,((InnerSize%16) == 0) ? int(Aligned16) : int(evaluator<DiagonalType>::Alignment)) // FIXME hardcoded 16!! }; return internal::pmul(m_matImpl.template packet<LoadMode,PacketType>(row, col), m_diagImpl.template packet<DiagonalPacketLoadMode,PacketType>(id)); } evaluator<DiagonalType> m_diagImpl; evaluator<MatrixType> m_matImpl; }; // diagonal * dense template<typename Lhs, typename Rhs, int ProductKind, int ProductTag> struct product_evaluator<Product<Lhs, Rhs, ProductKind>, ProductTag, DiagonalShape, DenseShape> : diagonal_product_evaluator_base<Rhs, typename Lhs::DiagonalVectorType, Product<Lhs, Rhs, LazyProduct>, OnTheLeft> { typedef diagonal_product_evaluator_base<Rhs, typename Lhs::DiagonalVectorType, Product<Lhs, Rhs, LazyProduct>, OnTheLeft> Base; using Base::m_diagImpl; using Base::m_matImpl; using Base::coeff; typedef typename Base::Scalar Scalar; typedef Product<Lhs, Rhs, ProductKind> XprType; typedef typename XprType::PlainObject PlainObject; enum { StorageOrder = int(Rhs::Flags) & RowMajorBit ? RowMajor : ColMajor }; EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) : Base(xpr.rhs(), xpr.lhs().diagonal()) { } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const { return m_diagImpl.coeff(row) * m_matImpl.coeff(row, col); } #ifndef __CUDACC__ template<int LoadMode,typename PacketType> EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { // FIXME: NVCC used to complain about the template keyword, but we have to check whether this is still the case. // See also similar calls below. return this->template packet_impl<LoadMode,PacketType>(row,col, row, typename internal::conditional<int(StorageOrder)==RowMajor, internal::true_type, internal::false_type>::type()); } template<int LoadMode,typename PacketType> EIGEN_STRONG_INLINE PacketType packet(Index idx) const { return packet<LoadMode,PacketType>(int(StorageOrder)==ColMajor?idx:0,int(StorageOrder)==ColMajor?0:idx); } #endif }; // dense * diagonal template<typename Lhs, typename Rhs, int ProductKind, int ProductTag> struct product_evaluator<Product<Lhs, Rhs, ProductKind>, ProductTag, DenseShape, DiagonalShape> : diagonal_product_evaluator_base<Lhs, typename Rhs::DiagonalVectorType, Product<Lhs, Rhs, LazyProduct>, OnTheRight> { typedef diagonal_product_evaluator_base<Lhs, typename Rhs::DiagonalVectorType, Product<Lhs, Rhs, LazyProduct>, OnTheRight> Base; using Base::m_diagImpl; using Base::m_matImpl; using Base::coeff; typedef typename Base::Scalar Scalar; typedef Product<Lhs, Rhs, ProductKind> XprType; typedef typename XprType::PlainObject PlainObject; enum { StorageOrder = int(Lhs::Flags) & RowMajorBit ? RowMajor : ColMajor }; EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) : Base(xpr.lhs(), xpr.rhs().diagonal()) { } EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const { return m_matImpl.coeff(row, col) * m_diagImpl.coeff(col); } #ifndef __CUDACC__ template<int LoadMode,typename PacketType> EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const { return this->template packet_impl<LoadMode,PacketType>(row,col, col, typename internal::conditional<int(StorageOrder)==ColMajor, internal::true_type, internal::false_type>::type()); } template<int LoadMode,typename PacketType> EIGEN_STRONG_INLINE PacketType packet(Index idx) const { return packet<LoadMode,PacketType>(int(StorageOrder)==ColMajor?idx:0,int(StorageOrder)==ColMajor?0:idx); } #endif }; /*************************************************************************** * Products with permutation matrices ***************************************************************************/ /** \internal * \class permutation_matrix_product * Internal helper class implementing the product between a permutation matrix and a matrix. * This class is specialized for DenseShape below and for SparseShape in SparseCore/SparsePermutation.h */ template<typename ExpressionType, int Side, bool Transposed, typename ExpressionShape> struct permutation_matrix_product; template<typename ExpressionType, int Side, bool Transposed> struct permutation_matrix_product<ExpressionType, Side, Transposed, DenseShape> { typedef typename nested_eval<ExpressionType, 1>::type MatrixType; typedef typename remove_all<MatrixType>::type MatrixTypeCleaned; template<typename Dest, typename PermutationType> static inline void run(Dest& dst, const PermutationType& perm, const ExpressionType& xpr) { MatrixType mat(xpr); const Index n = Side==OnTheLeft ? mat.rows() : mat.cols(); // FIXME we need an is_same for expression that is not sensitive to constness. For instance // is_same_xpr<Block<const Matrix>, Block<Matrix> >::value should be true. //if(is_same<MatrixTypeCleaned,Dest>::value && extract_data(dst) == extract_data(mat)) if(is_same_dense(dst, mat)) { // apply the permutation inplace Matrix<bool,PermutationType::RowsAtCompileTime,1,0,PermutationType::MaxRowsAtCompileTime> mask(perm.size()); mask.fill(false); Index r = 0; while(r < perm.size()) { // search for the next seed while(r<perm.size() && mask[r]) r++; if(r>=perm.size()) break; // we got one, let's follow it until we are back to the seed Index k0 = r++; Index kPrev = k0; mask.coeffRef(k0) = true; for(Index k=perm.indices().coeff(k0); k!=k0; k=perm.indices().coeff(k)) { Block<Dest, Side==OnTheLeft ? 1 : Dest::RowsAtCompileTime, Side==OnTheRight ? 1 : Dest::ColsAtCompileTime>(dst, k) .swap(Block<Dest, Side==OnTheLeft ? 1 : Dest::RowsAtCompileTime, Side==OnTheRight ? 1 : Dest::ColsAtCompileTime> (dst,((Side==OnTheLeft) ^ Transposed) ? k0 : kPrev)); mask.coeffRef(k) = true; kPrev = k; } } } else { for(Index i = 0; i < n; ++i) { Block<Dest, Side==OnTheLeft ? 1 : Dest::RowsAtCompileTime, Side==OnTheRight ? 1 : Dest::ColsAtCompileTime> (dst, ((Side==OnTheLeft) ^ Transposed) ? perm.indices().coeff(i) : i) = Block<const MatrixTypeCleaned,Side==OnTheLeft ? 1 : MatrixTypeCleaned::RowsAtCompileTime,Side==OnTheRight ? 1 : MatrixTypeCleaned::ColsAtCompileTime> (mat, ((Side==OnTheRight) ^ Transposed) ? perm.indices().coeff(i) : i); } } } }; template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape> struct generic_product_impl<Lhs, Rhs, PermutationShape, MatrixShape, ProductTag> { template<typename Dest> static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { permutation_matrix_product<Rhs, OnTheLeft, false, MatrixShape>::run(dst, lhs, rhs); } }; template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape> struct generic_product_impl<Lhs, Rhs, MatrixShape, PermutationShape, ProductTag> { template<typename Dest> static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { permutation_matrix_product<Lhs, OnTheRight, false, MatrixShape>::run(dst, rhs, lhs); } }; template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape> struct generic_product_impl<Inverse<Lhs>, Rhs, PermutationShape, MatrixShape, ProductTag> { template<typename Dest> static void evalTo(Dest& dst, const Inverse<Lhs>& lhs, const Rhs& rhs) { permutation_matrix_product<Rhs, OnTheLeft, true, MatrixShape>::run(dst, lhs.nestedExpression(), rhs); } }; template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape> struct generic_product_impl<Lhs, Inverse<Rhs>, MatrixShape, PermutationShape, ProductTag> { template<typename Dest> static void evalTo(Dest& dst, const Lhs& lhs, const Inverse<Rhs>& rhs) { permutation_matrix_product<Lhs, OnTheRight, true, MatrixShape>::run(dst, rhs.nestedExpression(), lhs); } }; /*************************************************************************** * Products with transpositions matrices ***************************************************************************/ // FIXME could we unify Transpositions and Permutation into a single "shape"?? /** \internal * \class transposition_matrix_product * Internal helper class implementing the product between a permutation matrix and a matrix. */ template<typename ExpressionType, int Side, bool Transposed, typename ExpressionShape> struct transposition_matrix_product { typedef typename nested_eval<ExpressionType, 1>::type MatrixType; typedef typename remove_all<MatrixType>::type MatrixTypeCleaned; template<typename Dest, typename TranspositionType> static inline void run(Dest& dst, const TranspositionType& tr, const ExpressionType& xpr) { MatrixType mat(xpr); typedef typename TranspositionType::StorageIndex StorageIndex; const Index size = tr.size(); StorageIndex j = 0; if(!is_same_dense(dst,mat)) dst = mat; for(Index k=(Transposed?size-1:0) ; Transposed?k>=0:k<size ; Transposed?--k:++k) if(Index(j=tr.coeff(k))!=k) { if(Side==OnTheLeft) dst.row(k).swap(dst.row(j)); else if(Side==OnTheRight) dst.col(k).swap(dst.col(j)); } } }; template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape> struct generic_product_impl<Lhs, Rhs, TranspositionsShape, MatrixShape, ProductTag> { template<typename Dest> static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { transposition_matrix_product<Rhs, OnTheLeft, false, MatrixShape>::run(dst, lhs, rhs); } }; template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape> struct generic_product_impl<Lhs, Rhs, MatrixShape, TranspositionsShape, ProductTag> { template<typename Dest> static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) { transposition_matrix_product<Lhs, OnTheRight, false, MatrixShape>::run(dst, rhs, lhs); } }; template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape> struct generic_product_impl<Transpose<Lhs>, Rhs, TranspositionsShape, MatrixShape, ProductTag> { template<typename Dest> static void evalTo(Dest& dst, const Transpose<Lhs>& lhs, const Rhs& rhs) { transposition_matrix_product<Rhs, OnTheLeft, true, MatrixShape>::run(dst, lhs.nestedExpression(), rhs); } }; template<typename Lhs, typename Rhs, int ProductTag, typename MatrixShape> struct generic_product_impl<Lhs, Transpose<Rhs>, MatrixShape, TranspositionsShape, ProductTag> { template<typename Dest> static void evalTo(Dest& dst, const Lhs& lhs, const Transpose<Rhs>& rhs) { transposition_matrix_product<Lhs, OnTheRight, true, MatrixShape>::run(dst, rhs.nestedExpression(), lhs); } }; } // end namespace internal } // end namespace Eigen #endif // EIGEN_PRODUCT_EVALUATORS_H
[ "abdellah.lahnaoui@gmail.com" ]
abdellah.lahnaoui@gmail.com
6dd924f8ba9d5a4799ae262172e744a4f11861f3
35be95e5e4ef306a1203a173bed12599f62db7b6
/SlimDXc_Jun2010(VC++2008)/source/direct2d/RadialGradientBrushProperties.cpp
0f10650a2fba0d82ceb731e87438d688c1740db5
[ "MIT" ]
permissive
Orz5566/RandomTest
dd0ec2eb7a0db3993409c2a647658a175a3b4027
2884f99d29dda603c646d464a60d7bce3346b74d
refs/heads/master
2021-09-06T01:10:29.460192
2018-02-01T06:56:53
2018-02-01T06:56:53
118,869,777
0
0
null
null
null
null
UTF-8
C++
false
false
1,313
cpp
/* * Copyright (c) 2007-2012 SlimDX Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "stdafx.h" #include <d2d1.h> #include <d2d1helper.h> #include "Direct2DException.h" #include "RadialGradientBrushProperties.h" using namespace System; namespace SlimDX { namespace Direct2D { } }
[ "32087037+Orz5566@users.noreply.github.com" ]
32087037+Orz5566@users.noreply.github.com
fa1cfa689e6819698c70c315799e7a5ff5d017f4
08b7ded786a247113dca43938f253b2568a935d3
/gui/widget/notification_info_widget.h
ff633ad98993e9c62efdc0c789d9e83b96b5ffa7
[]
no_license
QtWorks/SmartHome
8be750595f2b94a8306439adba6a76983b9d8125
f83cc5516cc2fe9933d7b50266be41e6aad00afa
refs/heads/master
2021-01-24T02:47:48.703728
2017-11-17T15:01:12
2017-11-17T15:01:12
122,862,654
1
1
null
2018-02-25T18:16:22
2018-02-25T18:16:22
null
UTF-8
C++
false
false
772
h
#ifndef NOTIFICATION_INFO_WIDGET_H #define NOTIFICATION_INFO_WIDGET_H #include "scalable_widget.h" #include <QTimer> class NotificationInfoWidget : public ScalableWidget { Q_OBJECT QPixmap m_icon; QString m_date_time; QString m_information; int m_border_roudness{10}; QTimer* m_blink_timer; bool m_toggled{true}; bool m_severe{false}; private slots: void toggleBlink(); public: explicit NotificationInfoWidget(QWidget* parent, QSize base_size); void setIcon(const QPixmap& icon); void setDateTime(const QString& date_time); void setInformation(const QString& information); void setBorderRoundess(int border_roundess); void setSevere(bool severe); protected: void paintEvent(QPaintEvent*); }; #endif
[ "rskrobo1@etf.unsa.ba" ]
rskrobo1@etf.unsa.ba
c7dee16e5425a029d2ac10b403d1369c19193875
0af9965de7527f4ca341833a5831dacd3fb8373f
/LeetCode/range-sum-query-immutable.cpp
296d8efce91b7909bfab1d9e042fb131c9f94faa
[]
no_license
pcw109550/problem-solving
e69c6b1896cedf40ec50d24c061541035ba30dfc
333d850a5261b49f32350b6a723c731156b24b8a
refs/heads/master
2022-09-18T08:25:16.940647
2022-09-12T10:29:55
2022-09-12T10:29:55
237,185,788
11
1
null
2022-09-12T10:18:49
2020-01-30T10:05:42
C++
UTF-8
C++
false
false
931
cpp
// 303. Range Sum Query - Immutable #include <iostream> #include <vector> class NumArray { public: std::vector<int> D; NumArray(std::vector<int>& nums) { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); // O(N) D.emplace_back(0); for (int i = 0; i < nums.size(); i++) { D.emplace_back(D.back() + nums[i]); } } int sumRange(int i, int j) { // O(1) return D[j + 1] - D[i]; } }; int main(void) { std::vector<int> nums {-2, 0, 3, -5, 2, -1}; NumArray *obj = new NumArray(nums); int param_1 = obj->sumRange(0, 2); std::cout << param_1 << std::endl; int param_2 = obj->sumRange(2, 5); std::cout << param_2 << std::endl; int param_3 = obj->sumRange(0, 5); std::cout << param_3 << std::endl; }
[ "pcw109550@gmail.com" ]
pcw109550@gmail.com
1639fba156624763923f997702a4555793619058
a8e5517df264ca12e84c377270574a3cc378f0c1
/LAVIDA/1183/solution.cpp
fb49bba0cf5e2cb051f01ed3674bf1c09c56a67a
[]
no_license
wowoto9772/Hungry-Algorithm
cb94edc0d8a4a3518dd1996feafada9774767ff0
4be3d0e2f07d01e55653c277870d93b73ec917de
refs/heads/master
2021-05-04T23:28:12.443915
2019-08-11T08:11:39
2019-08-11T08:11:39
64,544,872
1
1
null
null
null
null
UTF-8
C++
false
false
858
cpp
#include <stdio.h> #include <limits.h> #include <algorithm> #define ll long long using namespace std; int I[5003]; ll A(ll a){ return a < -a ? -a : a; } ll mm(ll a, ll b){ return a < b ? a : b; } int main() { int n; while (scanf("%d", &n) == 1){ for (int i = 1; i <= n; i++)scanf("%d", &I[i]); sort(I + 1, I + 1 + n); int L = 1, R = n; ll ans = INT_MAX * 3LL; int x = -1, y = -1, z = -1; for (int L = 1; ans && L <= n - 2; L++){ for (int R = L + 2; ans && R <= n; R++){ int l = L + 1, r = R - 1, m; ll cmp = I[L] + I[R]; while (l <= r && ans){ m = (l + r) / 2; ll cnt = cmp + I[m]; ll k = A(cnt); if (cnt < 0)l = m + 1; else if (cnt > 0){ r = m - 1; } if (k < ans){ ans = k; x = L, y = m, z = R; } } } } printf("%d %d %d\n", I[x], I[y], I[z]); } }
[ "csjaj9772@gmail.com" ]
csjaj9772@gmail.com
6a79f41f4b124d1db10416ebcec8d0c5ba2f032a
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chrome/browser/extensions/chrome_kiosk_delegate.cc
1ddbeaa91644e9b6c430bf7dfea7c6008aa073f6
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
473
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 "chrome/browser/extensions/chrome_kiosk_delegate.h" namespace extensions { ChromeKioskDelegate::ChromeKioskDelegate() {} ChromeKioskDelegate::~ChromeKioskDelegate() {} bool ChromeKioskDelegate::IsAutoLaunchedKioskApp(const ExtensionId& id) const { return false; } } // namespace extensions
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
81a9177dc8bfc7319280eb81b48041f970414c2d
edda021b328841d86973f09e7b7278f7629d0380
/IM/IM_TV/imm_baseline/im_benchmarking-master/sidm029_im_benchmark/Codes/TIM_test/src/tim.cpp
568e6d28fac3d34929709f0bf1fe53483b4f85a4
[]
no_license
wenyixue/GCOMB
b5ad36dd9e55131169c1ef10a18f2323c4732001
ee2ed06b8db8fa66bab52f6c7026b3cc4bd0a289
refs/heads/master
2023-05-13T23:54:57.123031
2021-05-18T03:20:36
2021-05-18T03:20:36
368,171,392
0
0
null
2021-05-17T12:07:58
2021-05-17T12:07:57
null
UTF-8
C++
false
false
3,917
cpp
//#define HEAD_TRACE #define HEAD_INFO #define HEAD_INFO //#define HEAD_TRACE #include "sfmt/SFMT.h" #include "head.h" #include "memoryusage.h" #include "graph.h" #include <string> void run(TimGraph & m, string dataset, string outdir, int k, double epsilon, string model ){ ofstream seedFile, outputFile, statFile; string outputFilename, statFilename, seedFilename; //double epsilonPrint = floor(epsilon *100.)/100.; char epsilonConvert[64]; double epsilonPrint; sprintf(epsilonConvert, "%.*g", 2, epsilon); epsilonPrint = strtod(epsilonConvert, 0); outputFilename = outdir + "/" + "output_TIM_" + model + "_" + to_string(k)+"_"+epsilonConvert + ".txt"; outputFile.open (outputFilename.c_str()); outputFile << "dataste:" << dataset << " k:" << k << " epsilon:"<< epsilonPrint << " model:" << model << endl; m.k=k; if(model=="IC") m.setInfuModel(InfGraph::IC); else if(model=="LT") m.setInfuModel(InfGraph::LT); else ASSERT(false); outputFile<<"Finish Read Graph, Start Influecne Maximization"<<endl; clock_t time_start = clock(); m.EstimateOPT(epsilon); clock_t time_end = clock(); outputFile<<"Time used: " << Timer::timeUsed[100]/TIMES_PER_SEC << "s" <<endl; outputFile<<"Selected k SeedSet: "; for(auto item:m.seedSet) outputFile<< item << " "; cout<<endl; outputFile<<"Estimated Influence: " << m.InfluenceHyperGraph() << endl; Counter::show(); //Added by Sigdata statFilename = outdir + "/" + "stat_TIM_" + model + "_" + to_string(k)+"_"+epsilonConvert + ".txt"; seedFilename = outdir + "/" + "seeds_TIM_" + model + "_" + to_string(k)+"_"+epsilonConvert + ".txt"; statFile.open (statFilename.c_str()); seedFile.open (seedFilename.c_str()); for(auto item:m.seedSet) seedFile<< item << endl; //statFile<<m.InfluenceHyperGraph()<<" "<<Timer::timeUsed[100]/TIMES_PER_SEC<<" "<< disp_mem_usage("")<<endl;//Add memory usage and check time statFile<<m.InfluenceHyperGraph()<<" "<<(float)(time_end - time_start) / CLOCKS_PER_SEC<<" "<< disp_mem_usage("")<<endl;//Add memory usage and check time statFile.close(); seedFile.close(); outputFile.close(); } void parseArg(int argn, char ** argv) { string dataset=""; double epsilon=0; string model=""; int k=0; string outdir=""; for(int i=0; i<argn; i++) { if(argv[i]==string("-dataset")) dataset=string(argv[i+1]);//Modified by Sigdata +"/"; if(argv[i]==string("-outdir")) outdir=string(argv[i+1]);//Added by Sigdata +"/"; if(argv[i]==string("-epsilon")) epsilon=atof(argv[i+1]); if(argv[i]==string("-k")) k=atoi(argv[i+1]); if(argv[i]==string("-model")) { if(argv[i+1]==string("LT")) { model=argv[i+1]; } else if(argv[i+1]==string("IC")) { model=argv[i+1]; } else ExitMessage("model should be IC or LT"); } } if (dataset=="") ExitMessage("argument dataset missing"); if (k==0) ExitMessage("argument k missing"); if (epsilon==0) ExitMessage("argument epsilon missing"); if (model=="") ExitMessage("argument model missing"); string graph_file; /*if(model=="IC") graph_file=dataset + "graph_ic.inf"; else if(model=="LT") graph_file=dataset + "graph_lt.inf"; */ graph_file =dataset; //Extract folder from dataset to get the folder std::size_t found = dataset.find_last_of("/"); dataset = dataset.substr(0,found+1); //cout<<"folder is "<<dataset<<" "<<found<<endl; TimGraph m(dataset, graph_file); run(m, dataset, outdir, k , epsilon, model ); } int main(int argn, char ** argv) { OutputInfo info(argn, argv); parseArg( argn, argv ); }
[ "sahilm1992@gmail.com" ]
sahilm1992@gmail.com
15aaef364c6c3e40fcb202b95a10b7d953dc7e07
2d361696ad060b82065ee116685aa4bb93d0b701
/src/util/test/test_thread_pool_old.cpp
f12decefa401a73d906ecb9ad76e8011857a247b
[ "LicenseRef-scancode-public-domain" ]
permissive
AaronNGray/GenomeWorkbench
5151714257ce73bdfb57aec47ea3c02f941602e0
7156b83ec589e0de8f7b0a85699d2a657f3e1c47
refs/heads/master
2022-11-16T12:45:40.377330
2020-07-10T00:54:19
2020-07-10T00:54:19
278,501,064
1
1
null
null
null
null
UTF-8
C++
false
false
5,199
cpp
/* $Id: test_thread_pool_old.cpp 605875 2020-04-16 11:24:47Z ivanov $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aaron Ucko * * File Description: * thread pool test * * =========================================================================== */ #include <ncbi_pch.hpp> #include <util/thread_pool.hpp> #include <corelib/ncbi_process.hpp> #include <corelib/ncbi_system.hpp> #include <corelib/ncbiapp.hpp> #include <util/random_gen.hpp> #include <corelib/ncbimtx.hpp> #include <common/test_assert.h> // This header must go last USING_NCBI_SCOPE; CRandom s_RNG; DEFINE_STATIC_MUTEX(s_RNG_Mutex); #define RNG_LOCK CMutexGuard LOCK(s_RNG_Mutex) class CThreadPoolTester : public CNcbiApplication { protected: void Init(void); int Run (void); }; void CThreadPoolTester::Init(void) { unique_ptr<CArgDescriptions> arg_desc(new CArgDescriptions); arg_desc->SetUsageContext(GetArguments().GetProgramBasename(), "test of thread pool correctness"); arg_desc->AddDefaultKey("init_threads", "N", "how many worker threads to spawn initially", CArgDescriptions::eInteger, "3"); arg_desc->AddDefaultKey("max_threads", "N", "how many worker threads to allow total", CArgDescriptions::eInteger, "5"); arg_desc->AddDefaultKey("requests", "N", "how many jobs to submit", CArgDescriptions::eInteger, "10"); arg_desc->AddDefaultKey("queue_size", "N", "how many jobs to allow in the queue", CArgDescriptions::eInteger, "2"); arg_desc->AddDefaultKey("thread_pool_timeout", "N", "WaitForRoom() timeout argument (in ms)", CArgDescriptions::eInteger, "30"); arg_desc->AddDefaultKey("max_processing_time", "N", "maximum request processing time in ms", CArgDescriptions::eInteger, "5"); SetupArgDescriptions(arg_desc.release()); RNG_LOCK; s_RNG.SetSeed(CCurrentProcess::GetPid()); } class CTestRequest : public CStdRequest { public: CTestRequest(int serial, int max_processing_time) : m_Serial(serial), m_MaxProcessingTime(max_processing_time) { } protected: void Process(void); private: int m_Serial; int m_MaxProcessingTime; }; void CTestRequest::Process(void) { int duration; {{ RNG_LOCK; duration = s_RNG.GetRand(0, m_MaxProcessingTime); }} //LOG_POST("Request " << m_Serial << ": " << duration); SleepMilliSec(duration); //LOG_POST("Request " << m_Serial << " complete"); } int CThreadPoolTester::Run(void) { int status = 0; const CArgs& args = GetArgs(); CStdPoolOfThreads pool(args["max_threads"].AsInteger(), args["queue_size"].AsInteger()); pool.Spawn(args["init_threads"].AsInteger()); unsigned wait_timeout_ms = (unsigned) args["thread_pool_timeout"].AsInteger(); unsigned wait_timeout_s = wait_timeout_ms / 1000; unsigned wait_timeout_ns = (wait_timeout_ms % 1000) * 1000 * 1000; int max_processing_time = args["max_processing_time"].AsInteger(); try { for (int i = 0; i < args["requests"].AsInteger(); ++i) { try { pool.WaitForRoom(wait_timeout_s, wait_timeout_ns); } catch (CBlockingQueueException&) { continue; } //LOG_POST("Request " << (i + 1) << " to be queued"); pool.AcceptRequest(CRef<CStdRequest>(new CTestRequest(i + 1, max_processing_time))); } } STD_CATCH_ALL("CThreadPoolTester: status " << (status = 1)) pool.KillAllThreads(CStdPoolOfThreads::fKill_Wait); return status; } int main(int argc, const char* argv[]) { return CThreadPoolTester().AppMain(argc, argv); }
[ "aaronngray@gmail.com" ]
aaronngray@gmail.com
bbcb465f4ce93caf1d1773f2b6c39b4bd78714de
3579de0a3ef53456ebd2d7692c8a085ba67117a9
/google/cloud/storage/internal/grpc_resumable_upload_session_url.cc
5cf720d4d0e0528d24627f91d4992916ea29aa6a
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
NorthDragonRider/google-cloud-cpp
82fceed039e19ed4d131843139333a82e08a64a6
f9d9b2498d30f83a84f206e71c3dcb721ee00d3f
refs/heads/master
2023-01-12T05:31:34.036803
2020-11-03T20:20:03
2020-11-03T20:20:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,663
cc
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/grpc_resumable_upload_session_url.h" #include "google/cloud/storage/internal/grpc_resumable_upload_session_url.pb.h" #include "google/cloud/storage/internal/openssl_util.h" #include "absl/strings/match.h" #include <cstring> namespace google { namespace cloud { namespace storage { inline namespace STORAGE_CLIENT_NS { namespace internal { auto constexpr kUriScheme = "grpc://"; std::string EncodeGrpcResumableUploadSessionUrl( ResumableUploadSessionGrpcParams const& upload_session_params) { GrpcResumableUploadSessionUrl proto; proto.set_bucket_name(upload_session_params.bucket_name); proto.set_object_name(upload_session_params.object_name); proto.set_upload_id(upload_session_params.upload_id); std::string proto_rep; proto.SerializeToString(&proto_rep); return kUriScheme + UrlsafeBase64Encode(proto_rep); } StatusOr<ResumableUploadSessionGrpcParams> DecodeGrpcResumableUploadSessionUrl( std::string const& upload_session_url) { if (!IsGrpcResumableSessionUrl(upload_session_url)) { return Status( StatusCode::kInvalidArgument, "gRPC implementation of GCS client cannot interpret a resumable upload " "session from a different implementation (e.g. cURL based). Check your " "configuration"); } auto const payload = upload_session_url.substr(std::strlen(kUriScheme)); auto const decoded_vec = UrlsafeBase64Decode(payload); std::string decoded(decoded_vec.begin(), decoded_vec.end()); GrpcResumableUploadSessionUrl proto; if (!proto.ParseFromString(decoded)) { return Status(StatusCode::kInvalidArgument, "Malformed gRPC resumable upload session URL"); } return ResumableUploadSessionGrpcParams{ proto.bucket_name(), proto.object_name(), proto.upload_id()}; } bool IsGrpcResumableSessionUrl(std::string const& upload_session_url) { return absl::StartsWith(upload_session_url, kUriScheme); } } // namespace internal } // namespace STORAGE_CLIENT_NS } // namespace storage } // namespace cloud } // namespace google
[ "noreply@github.com" ]
NorthDragonRider.noreply@github.com
30f3e2d3f3bac3314f7a89799e0b4ea345902acb
5a19e6dfde1ddd1ffa98c341e4f5b412d710c42c
/mve/mistl/mistl/include/mistl/Quality.h
d39db93a4331adf895030333753339579ab735c0
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
jtpils/MVE_3D_SemanticSegmentation
dfb10f361f39995d5b36be90194bf639b2a19eb8
77fcaecd7f4b8e8ab7695b67596fd4e0858cc995
refs/heads/master
2020-08-29T07:19:33.845907
2019-10-08T14:27:24
2019-10-08T14:27:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,840
h
// // INTEL CORPORATION PROPRIETARY INFORMATION // // This software is supplied under the terms of a license agreement or // nondisclosure agreement with Intel Corporation and may not be copied // or disclosed except in accordance with the terms of that agreement. // Copyright (C) 2014 Intel Corporation. All Rights Reserved. // // ## specifics // // Mistl - Multi-camera Image STructure Library // Author: Oliver Grau // #ifndef Quality_incl_ #define Quality_incl_ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "mistl/Error.h" #include "opencv2/core/core.hpp" namespace mistl { /*! \class Quality Quality.h \brief Base class for quality and confidence \author O.Grau */ class Quality { public: Quality() {} ~Quality(){} public: //! Compute quality and confidence // virtual void Compute() =0; void Info() const; float GetQuality() const { if(quality<0.0f) return 0.0f; if(quality>1.0f) return 1.0f; return quality;} float GetConfidence() const { if(confidence<0.0f) return 0.0f; if(confidence>1.0f) return 1.0f; return confidence;} float quality; float confidence; private: }; /*! \class TrackQuality Quality.h \brief Class for quality and confidence of tracking results \author O.Grau */ class TrackQuality : public Quality { public: TrackQuality(){} ~TrackQuality(){} void Info() const; // virtual void Compute(); public: float match; unsigned n; //!< number of total correspondences unsigned ncam; //!< number of cameras unsigned min_n; //!< lowest number of correspondences in one camera private: }; } #endif
[ "syed.qutub@intel.com" ]
syed.qutub@intel.com
b1097ce0ce9b4ff70b37baf4d2a76425e145ed79
76261aae39cfc15a2b3444665ebcb23a657db361
/Production/Source/Ripley/DNAArray.h
58236b8572497cb63b938838c697add9f02739b9
[]
no_license
rocketeerbkw/DNA
d208c72690ccfae261beb531fb52d1c2647783e3
de5993d6d0f8dd735085ebca4c86f4363c498615
refs/heads/master
2021-01-21T13:29:52.930616
2015-10-01T17:05:40
2015-10-01T17:05:40
43,528,993
1
0
null
2015-10-02T00:43:08
2015-10-02T00:43:08
null
UTF-8
C++
false
false
1,277
h
// // DNAArray.h // #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 /********************************************************************************* class CDNAIntArray Author: Mark Howitt Created: 10/03/2004 Purpose: New Int Array class with minimum functionality *********************************************************************************/ class CDNAIntArray { public: CDNAIntArray(); CDNAIntArray(int iInitialSize, int iGrowBy = -1); virtual ~CDNAIntArray(void); public: bool IsEmpty(void) { return m_iSize <= 0; } // Removes all elements from the array void RemoveAll(void); bool RemoveAt(int iIndex); void RemoveEnd(void); // Returns the number of elements in the array int GetSize(void) { return m_iSize; } // Sets the overall allocated memory for the arry int SetSize(int iSize,int iGrowBy = -1); void SetGrowBy(int iGrowBy); int FreeExtra(void); // Get Functions int operator[](int iIndex) const; int GetAt(int iIndex); // Add Function bool Add(int iValue); // Set Function bool SetAt(int iIndex, int iValue); int& operator[](int iIndex); private: int* m_pData; int m_iSize; int m_iMaxSize; int m_iGrowBy; int m_iInvalid; };
[ "VP-DEV-DNA-1\\NevesM31" ]
VP-DEV-DNA-1\NevesM31
d69ab602fa7ed52671584b5120e073cf75c06d36
3358e2982603a8fc0db41b1a10ecf227fab13303
/3rd/n3/code/extlibs/bullet/fw/include/win32/FWWin32Input.h
b0d6076b3947670ee9819879a1ea59a6f2be980a
[]
no_license
JerryZhou/opensc
118a1dc0595490c0f218d9a2e4325002be7fe254
28e685feaa302f174fbb2c0f6a60f597f497fdd9
refs/heads/master
2020-06-08T04:09:55.527373
2013-09-22T03:28:44
2013-09-22T03:28:44
11,479,319
1
0
null
null
null
null
UTF-8
C++
false
false
4,911
h
/* SCE CONFIDENTIAL * $PSLibId$ * Copyright (C) 2006 Sony Computer Entertainment Inc. * All Rights Reserved. */ //----------------------------------------------------------------------------- // Sample Framework // // Win32 Input // // $File: //nextgendev/Framework_080/include/win32/FWWin32Input.h $ // $Author: asidwell $ // $Date: 2006/01/06 $ // $Revision: #1 $ // // Copyright (C) 2006 Sony Computer Entertainment. // All Rights Reserved. // //----------------------------------------------------------------------------- #ifndef __FW_WIN32INPUT_H__ #define __FW_WIN32INPUT_H__ #define DIRECTINPUT_VERSION 0x0800 #include <windows.h> #include <dinput.h> // platform specific mouse info class FWWin32MouseInfo { public: bool mIsWithinClientArea; // mouse inside client area LPDIRECTINPUTDEVICE8 mpDevice; // pointer to dinput device }; // keyboard mapping to direct input key offsets static unsigned char sKeyboardMap[256] = { DIK_A, //Channel_Key_A, DIK_B, //Channel_Key_B, DIK_C, //Channel_Key_C, DIK_D, //Channel_Key_D, DIK_E, //Channel_Key_E, DIK_F, //Channel_Key_F, DIK_G, //Channel_Key_G, DIK_H, //Channel_Key_H, DIK_I, //Channel_Key_I, DIK_J, //Channel_Key_J, DIK_K, //Channel_Key_K, DIK_L, //Channel_Key_L, DIK_M, //Channel_Key_M, DIK_N, //Channel_Key_N, DIK_O, //Channel_Key_O, DIK_P, //Channel_Key_P, DIK_Q, //Channel_Key_Q, DIK_R, //Channel_Key_R, DIK_S, //Channel_Key_S, DIK_T, //Channel_Key_T, DIK_U, //Channel_Key_U, DIK_V, //Channel_Key_V, DIK_W, //Channel_Key_W, DIK_X, //Channel_Key_X, DIK_Y, //Channel_Key_Y, DIK_Z, //Channel_Key_Z, DIK_1, //Channel_Key_1, DIK_2, //Channel_Key_2, DIK_3, //Channel_Key_3, DIK_4, //Channel_Key_4, DIK_5, //Channel_Key_5, DIK_6, //Channel_Key_6, DIK_7, //Channel_Key_7, DIK_8, //Channel_Key_8, DIK_9, //Channel_Key_9, DIK_0, //Channel_Key_0, DIK_ESCAPE, //Channel_Key_Escape, DIK_F1, //Channel_Key_F1, DIK_F2, //Channel_Key_F2, DIK_F3, //Channel_Key_F3, DIK_F4, //Channel_Key_F4, DIK_F5, //Channel_Key_F5, DIK_F6, //Channel_Key_F6, DIK_F7, //Channel_Key_F7, DIK_F8, //Channel_Key_F8, DIK_F9, //Channel_Key_F9, DIK_F10, //Channel_Key_F10, DIK_F11, //Channel_Key_F11, DIK_F12, //Channel_Key_F12, DIK_RETURN, //Channel_Key_Enter, DIK_BACK, //Channel_Key_Backspace, DIK_TAB, //Channel_Key_Tab, DIK_SPACE, //Channel_Key_Space, DIK_MINUS, //Channel_Key_Minus, DIK_EQUALS, //Channel_Key_Equals, DIK_LBRACKET, //Channel_Key_LeftBracket, DIK_RBRACKET, //Channel_Key_RightBracket, DIK_BACKSLASH, //Channel_Key_Backslash, DIK_SEMICOLON, //Channel_Key_Semicolon DIK_APOSTROPHE, //Channel_Key_Apostrophe DIK_COMMA, //Channel_Key_Comma, DIK_PERIOD, //Channel_Key_Period, DIK_SLASH, //Channel_Key_Slash, DIK_LEFT, //Channel_Key_Left, DIK_RIGHT, //Channel_Key_Right, DIK_UP, //Channel_Key_Up, DIK_DOWN, //Channel_Key_Down, DIK_HOME, //Channel_Key_Home, DIK_END, //Channel_Key_End, DIK_PRIOR, //Channel_Key_PageUp, DIK_NEXT, //Channel_Key_PageDown, DIK_INSERT, //Channel_Key_Insert, DIK_DELETE, //Channel_Key_Delete, DIK_NUMPAD1, //Channel_Key_Numpad_1, DIK_NUMPAD2, //Channel_Key_Numpad_2, DIK_NUMPAD3, //Channel_Key_Numpad_3, DIK_NUMPAD4, //Channel_Key_Numpad_4, DIK_NUMPAD5, //Channel_Key_Numpad_5, DIK_NUMPAD6, //Channel_Key_Numpad_6, DIK_NUMPAD7, //Channel_Key_Numpad_7, DIK_NUMPAD8, //Channel_Key_Numpad_8, DIK_NUMPAD9, //Channel_Key_Numpad_9, DIK_NUMPAD0, //Channel_Key_Numpad_0, DIK_DIVIDE, //Channel_Key_Numpad_Slash, DIK_MULTIPLY, //Channel_Key_Numpad_Asterisk, DIK_SUBTRACT, //Channel_Key_Numpad_Minus, DIK_ADD, //Channel_Key_Numpad_Plus, DIK_NUMPADENTER,//Channel_Key_Numpad_Enter, DIK_DECIMAL, //Channel_Key_Numpad_Period, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; #endif//__FW_WIN32INPUT_H__ // Local variables: // indent-tabs-mode: t // tab-width: 4 // End: // vim:ts=4:sw=4
[ "JerryZhou@outlook.com" ]
JerryZhou@outlook.com
c6956d0c9ca2bff1fea7c523303d4ded57219f9b
27c2e5277bac7ba627f461d52e6c59dd23731e86
/sugar/engine/su_sg_scenegraph.h
d00f6e7aadec45b7710d0b5a17a06931328abe8d
[]
no_license
magicfoo/atonce
4c70fbc753fbc9bc1e32b14317ddf4bc61cafd66
7561af1c477e107ee9cdd1bcb82a8f7b753bc6ab
refs/heads/master
2022-12-23T10:10:42.602545
2020-09-23T20:18:42
2020-09-23T20:18:42
298,083,714
0
0
null
null
null
null
UTF-8
C++
false
false
3,854
h
/*LIC-HDR******************************************************************** ** ** Copyright (C) 2005-2011 AtOnce Technologies ** ** This file is part of the Sugar core-system framework. ** ** This file and the associated product may be used and distributed ** under the terms of a current License as defined by AtOnce Technologies ** and appearing in the file LICENSE.TXT included in the packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.atonce-technologies.com or email info@atonce-technologies.com ** for informations about Sugar Framework and AtOnce Technologies others products ** License Agreements. ** ** Contact info@atonce-technologies.com if any conditions of this license ** are not clear to you. ** *****************************************************************LIC-HDR*/ #ifndef _su_sg_scenegraph_h_ #define _su_sg_scenegraph_h_ #include "su_sg_scenegraph_enum.h" namespace su{ struct IDirectDraw; } namespace su { namespace sg { struct SceneGraph { public: static SceneGraph* Create ( Pool* inPool, IDirectDraw* inDD ); void Release ( ); void SetView ( uint inViewPbi, const Vec2& inViewSize ); uint GetView ( ); bool Draw ( ); Pool* GetPool ( ); Handle* GetRoot ( ); byte GetLayerId ( ); IDirectDraw* GetDirectDraw ( ); Matrix* BuildWorldTR ( Matrix* outTR, Handle* inHandle ); Box3* BuildBBox ( Box3* outBox, Handle* inHandle ); Handle* Pick ( Viewport* inViewport, const Vec2& inCoord ); void Pick ( vector<Handle*>* ioHandleA, Viewport* inViewport, const Vec2& inCoord, const Vec2& inSize ); void SetRenderMode ( RenderMode inRenderMode ); RenderMode GetRenderMode ( ); enum PostFxValue { PFV_BlurRadius, PFV_BlurBlendFactor, }; void EnablePostFx ( bool inOnOff ); void SetPostFxValuef ( PostFxValue inOpt, float inVal ); void SetPostFxCode ( pcstr inPixelCode ); bool SetCameraVideoMode ( bool inOnOff ); struct PostProcessUtil { Pool* pool; IDirectDraw* dd; uint w, h; struct Mip // start to w/2, h/2 { int rt; uint w, h; }; Mip* mipA; uint mipCount; }; struct BackQuad { uint w, h; uint quad; }; protected: virtual void OnEvent ( Handle* inHandle, EventReason inReason ); virtual void OnEvent ( Core* inCore, EventReason inReason ); Pool* pool; Root* root; byte layerid; IDirectDraw* ddraw; uint viewPbi; Vec2 viewSize; RenderMode renderMode; vector<uint> opCodeA; vector<Viewport*> viewportA; // // --- resources ( warp, grid, cube... ) uint noisePbi; uint gridSrf; uint warpSrf; uint abSrfA[2]; uint abVboRect; int abRectHL; uint cubeSrf; uint cubePbi; uint cubeHLSrfA[3]; uint cubeHLVboA[3]; uint pickRT; uint handleCount; bool pFxEnable; uint pFxProgId; float pFxBlurBlendFactor; float pFxBlurRadius; bool pFxBlurOpCodeDirty; uint pFxBlurOpCodeA[256]; float pFxBlurMipBlend_int; uint pFxBlurPbi_int; int mainRT; uint quadSS; uint quadFS; vector<BackQuad> backQuadA; PostProcessUtil ppu; bool onCameraVideoMode; friend struct Handle; friend struct Root; friend struct Core; }; } } #endif // _su_sg_scenegraph_h_
[ "ggainant@roblox.com" ]
ggainant@roblox.com
d20eabc867c77ad8b9215fa00a544b4624cc5ec5
83195bb76eb33ed93ab36c3782295e4a2df6f005
/Source/AtomicWebView/WebKeyboardWindows.cpp
8ff812b7e75d87d3601aed27e33cb0564927d1ee
[ "MIT", "BSD-3-Clause", "Zlib", "LicenseRef-scancode-openssl", "LicenseRef-scancode-khronos", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "NTP" ]
permissive
MrRefactoring/AtomicGameEngine
ff227c054d3758bc1fbd5e502c382d7de81b0d47
9cd1bf1d4ae7503794cc3b84b980e4da17ad30bb
refs/heads/master
2020-12-09T07:24:48.735251
2020-01-11T14:03:29
2020-01-11T14:03:29
233,235,105
0
0
NOASSERTION
2020-01-11T13:21:19
2020-01-11T13:21:18
null
UTF-8
C++
false
false
4,452
cpp
// // Copyright (c) 2014-2016, THUNDERBEAST GAMES LLC All rights reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifdef ATOMIC_PLATFORM_WINDOWS #include <include/cef_client.h> #include <ThirdParty/SDL/include/SDL.h> #include <ThirdParty/SDL/include/SDL_syswm.h> #include <ThirdParty/SDL/src/events/scancodes_windows.h> #include <Atomic/Core/Variant.h> #include <Atomic/Input/InputEvents.h> #include <Atomic/Input/Input.h> #include <Atomic/IO/Log.h> #include "WebKeyboard.h" namespace Atomic { static bool SDLScanCodeToWindowsScanCode(SDL_Scancode code, LPARAM& lParam, WPARAM& wParam ) { wParam = 0; lParam = 0; int numCodes = sizeof(windows_scancode_table)/sizeof(SDL_Scancode); int windowsScanCode = -1; for (int i = 0; i < numCodes; i++) { if (windows_scancode_table[i] == code) { windowsScanCode = i; break; } } if (windowsScanCode != -1) { wParam = MapVirtualKey(windowsScanCode, MAPVK_VSC_TO_VK); lParam = windowsScanCode << 16; } switch (code) { case SDL_SCANCODE_RIGHT: wParam = VK_RIGHT; break; case SDL_SCANCODE_LEFT: wParam = VK_LEFT; break; case SDL_SCANCODE_UP: wParam = VK_UP; break; case SDL_SCANCODE_DOWN: wParam = VK_DOWN; break; case SDL_SCANCODE_DELETE: wParam = VK_DELETE; break; case SDL_SCANCODE_BACKSPACE: wParam = VK_BACK; break; } return wParam != 0 || lParam != 0; } bool ConvertKeyEvent(Input* input, const StringHash eventType, VariantMap& eventData, CefKeyEvent& keyEvent) { if (eventType != "KeyDown" && eventType != "KeyUp") { ATOMIC_LOGERROR("ConvertKeyEvent - Unknown event type"); return false; } WebKeyEvent wk(eventType, eventData); if (wk.scanCode == SDL_SCANCODE_RETURN) { if (!wk.keyDown) return false; keyEvent.windows_key_code = VK_RETURN; keyEvent.native_key_code = (int) 0; keyEvent.type = KEYEVENT_RAWKEYDOWN; return true; } LPARAM lParam; WPARAM wParam; keyEvent.modifiers = EVENTFLAG_NONE; if (wk.qual & QUAL_SHIFT) keyEvent.modifiers |= EVENTFLAG_SHIFT_DOWN; if (wk.qual & QUAL_ALT) keyEvent.modifiers |= EVENTFLAG_ALT_DOWN; if (wk.qual & QUAL_CTRL) keyEvent.modifiers |= EVENTFLAG_CONTROL_DOWN; if (SDLScanCodeToWindowsScanCode((SDL_Scancode) wk.scanCode, lParam, wParam)) { keyEvent.windows_key_code = (int) wParam; keyEvent.native_key_code = (int) lParam; keyEvent.type = wk.keyDown ? KEYEVENT_RAWKEYDOWN : KEYEVENT_KEYUP; } return true; } bool ConvertTextInputEvent(StringHash eventType, VariantMap& eventData, CefKeyEvent& keyEvent) { if (eventType != "TextInput") { ATOMIC_LOGERROR("ConvertTextInputEvent - Unknown event type"); return false; } String text = eventData[TextInput::P_TEXT].GetString(); SDL_Keycode keyCode = SDL_GetKeyFromName(text.CString()); if (SDL_strlen(text.CString()) == 1) { if (text[0] >= 'A' && text[0] <= 'Z') { keyCode -= 32; } } keyEvent.windows_key_code = (int) keyCode; keyEvent.native_key_code = 0;// (int) lParam; keyEvent.type = KEYEVENT_CHAR; return true; } } #endif
[ "josh@galaxyfarfaraway.com" ]
josh@galaxyfarfaraway.com
4c48b64b11fc148c0139c9b50c957bec8da1ae3a
44564fafb4624d7c3d3f96d243eb7702f80f5c1e
/tests/YGNodeChildTest.cpp
cce9f33b5150f497ad04dc6988feea97f32d037a
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
Finger-Ink/yoga
14cb62d8cd5216eb58fa4d1432d0f2bcc16abdfc
0daf361c60fef66c75992a06db6a86c227d2407c
refs/heads/master
2023-03-17T01:14:10.426201
2022-12-12T11:58:35
2022-12-12T11:58:35
203,693,690
0
0
MIT
2022-12-05T20:32:09
2019-08-22T01:47:17
C++
UTF-8
C++
false
false
1,093
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <gtest/gtest.h> #include <yoga/Yoga.h> TEST(YogaTest, reset_layout_when_child_removed) { const YGNodeRef root = YGNodeNew(); const YGNodeRef root_child0 = YGNodeNew(); YGNodeStyleSetWidth(root_child0, 100); YGNodeStyleSetHeight(root_child0, 100); YGNodeInsertChild(root, root_child0, 0); YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR); ASSERT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_EQ(100, YGNodeLayoutGetWidth(root_child0)); ASSERT_EQ(100, YGNodeLayoutGetHeight(root_child0)); YGNodeRemoveChild(root, root_child0); ASSERT_EQ(0, YGNodeLayoutGetLeft(root_child0)); ASSERT_EQ(0, YGNodeLayoutGetTop(root_child0)); ASSERT_TRUE(YGFloatIsUndefined(YGNodeLayoutGetWidth(root_child0))); ASSERT_TRUE(YGFloatIsUndefined(YGNodeLayoutGetHeight(root_child0))); YGNodeFreeRecursive(root); }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
b1a533bf84b3bd6d3be145b6e07867e28e7aac56
3f8c632fe1b97d85a754b6ed031d154ef5dbfa2f
/llvm_profile_reader.h
13e44a97facae625b245cea86e731a54d93199f2
[]
no_license
grajer/autofdo
9464338dc1cc085950c562724a1c1a2da360e38a
5ec7b699dfe2ebc58d608afff8c668ab358a2da9
refs/heads/master
2023-06-04T10:41:33.973535
2021-06-21T22:46:43
2021-06-21T22:46:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,238
h
// Read symbol_map from the llvm sample profile. #ifndef AUTOFDO_LLVM_PROFILE_READER_H_ #define AUTOFDO_LLVM_PROFILE_READER_H_ #include "base_profile_reader.h" #include "source_info.h" #include "third_party/abseil/absl/container/node_hash_set.h" #include "llvm/ProfileData/SampleProf.h" namespace llvm { class StringRef; namespace sampleprof { class FunctionSamples; } } // namespace llvm namespace devtools_crosstool_autofdo { class SymbolMap; struct SpecialSyms { SpecialSyms(const char *strip_all_p[], unsigned strip_all_len, const char *keep_sole_p[], unsigned keep_sole_len, const char *keep_cold_p[], unsigned keep_cold_len) { for (int i = 0; i < strip_all_len; i++) strip_all.insert(strip_all_p[i]); for (int i = 0; i < keep_sole_len; i++) keep_sole.insert(keep_sole_p[i]); for (int i = 0; i < keep_cold_len; i++) keep_cold.insert(keep_cold_p[i]); } absl::node_hash_set<std::string> strip_all; absl::node_hash_set<std::string> keep_sole; absl::node_hash_set<std::string> keep_cold; absl::node_hash_set<std::string> skip_set; }; class LLVMProfileReader : public ProfileReader { public: explicit LLVMProfileReader(SymbolMap *symbol_map, absl::node_hash_set<std::string>& names, SpecialSyms *special_syms = nullptr) : symbol_map_(symbol_map), names_(names), special_syms_(special_syms) {} bool ReadFromFile(const std::string &output_file) override; bool shouldMergeProfileForSym(const std::string name); void SetProfileSymbolList( std::unique_ptr<llvm::sampleprof::ProfileSymbolList> list) { prof_sym_list_ = std::move(list); } llvm::sampleprof::ProfileSymbolList *GetProfileSymbolList() { return prof_sym_list_.get(); } private: const char *GetName(const llvm::StringRef &N); void ReadFromFunctionSamples(const SourceStack &stack, const llvm::sampleprof::FunctionSamples &fs); SymbolMap *symbol_map_; absl::node_hash_set<std::string>& names_; SpecialSyms *special_syms_; std::unique_ptr<llvm::sampleprof::ProfileSymbolList> prof_sym_list_; }; } // namespace devtools_crosstool_autofdo #endif // AUTOFDO_LLVM_PROFILE_READER_H_
[ "wmi@google.com" ]
wmi@google.com
04ebc2070e7ac69bd5099eee9cd8a6911eb4c179
22fa5261c962bdfb7bb0ae0a03d8ea984bcb71d5
/nov/1/859C.cpp
ae436f40bdcf5939f676b69a18faa2aaa8628f37
[]
no_license
Ashish-uzumaki/cp
21f03ddf6971cde10278af296734907a3a4d5996
2798de8429f934393b927f8beea3ac37d7a2a0aa
refs/heads/master
2020-04-11T17:40:56.645606
2018-12-27T04:04:27
2018-12-27T04:04:27
161,970,092
0
0
null
null
null
null
UTF-8
C++
false
false
890
cpp
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define lli long long int #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); ordered_set<lli>root,nom;//nom.order_of_key(x); lli visit[100001]; vector<pair<lli,lli> >v1,v2; // vector<lli>v1,v2; vector<lli>v; map<lli,lli>m; lli n; const lli MOD = 1e9+7; const lli k=16; const lli N=1e5; lli dp[51][N+1]; int main(){ cin>>n; lli sum=0; for(lli i=0;i<n;i++){ cin>>x; v.pb(x); sum+=x; } lli w=sum/2; for(lli i=1;i<n;i++){ dp[i][0]=max(dp[i-1][0],dp[i-1][1]); dp[i][1]=max(v[i]+dp[i-1][0],v[i]+dp[i-1][1]); } }
[ "1998ashishsingh@gmail.com" ]
1998ashishsingh@gmail.com
fbdb362116e4288d3946e034ecb4698574ad8d07
1a9002206db75270137e8dc896113d49ae3f8cf9
/GeeksForGeeks/Check if Linked List is Palindrome(Using vectors).cpp
10df3297e796de02b8ffc3f3fbb9df2742db1115
[]
no_license
manthankhorwal/Competitive-programming
8d2baaeb1ef049175f309756f5f30bb4015b7e41
95aa35b3dfe487249de13c04c275be7440590bd2
refs/heads/master
2020-05-27T17:23:50.666813
2019-06-14T17:30:52
2019-06-14T17:30:52
188,718,937
0
0
null
null
null
null
UTF-8
C++
false
false
396
cpp
#include<bits/stdc++.h> bool isPalindrome(Node *head) { Node* temp=head; vector<int> v; while(temp!=NULL) { v.push_back(temp->data); temp=temp->next; } Node *temp1=head; while(temp1!=NULL) { if(temp1->data!=v.back()) { return false; } temp1=temp1->next; v.pop_back(); } return true; }
[ "manthankhorwal502@gmail.com" ]
manthankhorwal502@gmail.com
653ec4328714b9a4e5c1cd43c4cf834720804a12
194840d144b77f3b662db6e3663c820db0807a46
/ProductLuaIdeCAPI/main.cpp
8877ad4c30da183f40e8d0e3579e4346f42ba8ef
[]
no_license
ToTPeople/my_own_tools
7cac7d84854b58d92f2ef4a538aea4ec06f5992c
d2509e7b399e076234162b8d757910627beec4b6
refs/heads/master
2020-03-24T03:46:05.723395
2018-07-26T12:15:49
2018-07-26T12:15:49
142,432,314
0
0
null
null
null
null
UTF-8
C++
false
false
377
cpp
#include <stdio.h> #include <string> #include <stdlib.h> #include "product_lua_ide_api.h" int main(int argc, char **argv) { // if (argc != 3) { // printf("----- please input ./a.out need_to_trans_dir out_dir ----\n"); // return 0; // } return parser_dir("./need_trans", "./after_trans"); // return parser_dir(argv[1], argv[2]); return 0; }
[ "lfs1@meitu.com" ]
lfs1@meitu.com
b7b55d384ff29a74b978cd57436cc8f961a3e946
400fd356eb75d95ab35e8dcce2f5b03b3d272e83
/Smjy/src/server/process/test.cpp
bb8ef94cad7ae81a5454282307bab51c9e3c685c
[]
no_license
shandaming/Martial_arts
4eba4c3856d0fbbcddc460790b4a06ba79a9c3ed
896f10a7c457a9f166e7991e54943d46b6a953b5
refs/heads/master
2022-11-11T08:05:21.439745
2022-10-22T05:55:23
2022-10-22T05:55:23
116,259,077
0
0
null
null
null
null
UTF-8
C++
false
false
3,258
cpp
#include <algorithm> #include <vector> #include <tuple> #include <utility> #include <tuple> template<typename F, typename T, typename... Args> void for_each(F&& f, T&& t, Args&&... args) { f(t); for_each(f, args...); } template<typename F, typename T> void for_each(F&& f, T&& t) { f(t); } struct child { explicit child(int p) : pid(p) {} int pid; }; struct initializer_base { template<typename T> void on_fork_setup(T&) const {} template<typename T> void on_fork_error(T&) const {} template<typename T> void on_fork_success(T&) const {} template<typename T> void on_exec_setup(T&) const {} template<typename T> void on_exec_error(T&) const {} }; class bind_stdin : public initializer_base { public: explicit bind_stdin(const int fd) : fd_(fd) {} template<typename T> void on_exec_setup(T&) const { //::dup2(fd_, STDIN_FILENO); } private: const int fd_; }; class bind_stdout : public initializer_base { public: explicit bind_stdout(const int fd) : fd_(fd) {} template<typename T> void on_exec_setup(T&) const { //::dunp2(fd_, STDOUT_FILENO); } private: int fd_; }; class bind_stderr : public initializer_base { public: explicit bind_stderr(const int fd) : fd_(fd) {} template<typename T> void on_exec_setup(T&) const { //::dup2(fd_, STDERR_FILENO); } private: const int fd_; }; struct executor { executor() : exe(0), cmd_line(0), env(0) {} struct call_on_fork_setup { call_on_fork_setup(executor& e) : e(e) {} template<typename T> void operator()(const T& arg) const { arg.on_fork_setup(e); } executor& e; }; struct call_on_fork_error { call_on_fork_error(executor& e) : e(e) {} template<typename T> void operator()(T& arg) const { arg.on_fork_error(e); } executor& e; }; struct call_on_fork_success { call_on_fork_success(executor& e) : e(e) {} template<typename T> void operator()(const T& arg) const { arg.on_fork_success(e); } executor& e; }; struct call_on_exec_setup { call_on_exec_setup(executor& e) : e(e) {} template<typename T> void operator()(T& arg) const { arg.on_exec_setup(e); } executor& e; }; struct call_on_exec_error { call_on_exec_error(executor& e) : e(e) {} template<typename T> void operator()(T& arg) const { arg.on_exec_error(e); } executor& e; }; template<typename... Args> child operator()(Args&&... seq) { for_each(call_on_fork_setup(*this), std::forward<Args>(seq)...); // inherit_env有 pid_t pid = 1;// = ::fork(); #if 0 if(pid == -1) { for_each(seq..., call_on_fork_error(*this)); // 都没有 } else if(pid == 0) { for_each(seq..., call_on_exec_setup(*this)); // 除inherit_env其他都有 //::execve(exe, cmd_line, env); for_each(seq..., call_on_exec_error(*this)); // 都没有 //_exit(EXIT_FAILURE); } for_each(seq..., call_on_fork_success(*this)); // 都没有 #endif return child(pid); } const char* exe; char** cmd_line; char** env; }; template<typename... Args> child execute(Args&&... args) { return executor()(std::forward<Args>(args)...); } int main() { child c = execute(bind_stdin(1), bind_stdout(2), bind_stderr(3)); //child c = executor()(bind_stdin(1), bind_stdout(2), bind_stderr(3)); return 0; }
[ "shandaming@hotmail.com" ]
shandaming@hotmail.com
8d3a2d224576cdcc0b763e02c7c1239612d0f9ad
f6876d46645bcb235f93a4263254a35657083990
/LED_SOUND/v0.1/v0.1.ino
2ab31a9f28d5d7d2d91df26e2b013ba729a076c9
[]
no_license
ckhurana/arduino-codes
8f950cf11ba3420de6b61a6e379f59b18beed45d
ede6b8ecda9ff52035ca1fb8e16499f4e2b061be
refs/heads/master
2020-03-25T22:07:08.986158
2018-09-10T00:10:37
2018-09-10T00:10:37
144,206,573
0
0
null
null
null
null
UTF-8
C++
false
false
3,390
ino
#include <FastLED.h> #define NUM_LEDS 16 // Data pin that led data will be written out over #define DATA_PIN 6 #define SOUND_PIN A0 CRGB leds[NUM_LEDS]; int soundVal = 0; void setup() { Serial.begin(9600); // sanity check delay - allows reprogramming if accidently blowing power w/leds pinMode(SOUND_PIN, INPUT); delay(2000); FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS); } void loop() { soundVal = analogRead(SOUND_PIN); // Serial.println(soundVal); // audio_1(soundVal); int wait=random(10,30); int dim=random(4,6); int max_cycles=8; int cycles=random(1,max_cycles+1); rainbowCycle(wait, cycles, dim); // for (int i = 0; i < NUM_LEDS; i++) { // leds[i] = CRGB(255,0,0); // FastLED.show(); // delay(500); // } // // for (int i = NUM_LEDS - 1; i >= 0; i--) { // leds[i] = CRGB(0,255,0); // FastLED.show(); // delay(500); // } // lightning(CRGB::White,20,50,250); } void audio_1(int sVal) { Serial.println(sVal); if (sVal < 250) { for (int i = 0; i < NUM_LEDS; i++) { leds[i] = CRGB(0, 0, 0); } } else if (sVal >= 250 && sVal < 450) { for (int i = 0; i < NUM_LEDS; i++) { if (i < 1) leds[i] = CRGB(0, 255, 255); else leds[i] = CRGB(0, 0, 0); } } else if (sVal >= 450 && sVal < 650) { for (int i = 0; i < NUM_LEDS; i++) { if (i < 2) leds[i] = CRGB(255, 0, 255); else leds[i] = CRGB(0, 0, 0); } } else { for (int i = 0; i < NUM_LEDS; i++) { leds[i] = CRGB(255, 255, 0); } } FastLED.show(); delay(10); } void lightning(CRGB c, int simultaneous, int cycles, int speed){ int flashes[simultaneous]; for(int i=0; i<cycles; i++){ for(int j=0; j<simultaneous; j++){ int idx = random(NUM_LEDS); flashes[j] = idx; leds[idx] = c ? c : randomColor(); } FastLED.show(); delay(speed); for(int s=0; s<simultaneous; s++){ leds[flashes[s]] = CRGB::Black; } delay(speed); } } void rainbowCycle(int wait, int cycles, int dim) { //loop several times with same configurations and same delay for(int cycle=0; cycle < cycles; cycle++){ byte dir=random(0,2); int k=255; //loop through all colors in the wheel for (int j=0; j < 256; j++,k--) { if(k<0) { k=255; } //Set RGB color of each LED for(int i=0; i<NUM_LEDS; i++) { CRGB ledColor = wheel(((i * 256 / NUM_LEDS) + (dir==0?j:k)) % 256,dim); leds[i]=ledColor; } FastLED.show(); FastLED.delay(wait); } } } CRGB wheel(int WheelPos, int dim) { CRGB color; if (85 > WheelPos) { color.r=0; color.g=WheelPos * 3/dim; color.b=(255 - WheelPos * 3)/dim;; } else if (170 > WheelPos) { color.r=WheelPos * 3/dim; color.g=(255 - WheelPos * 3)/dim; color.b=0; } else { color.r=(255 - WheelPos * 3)/dim; color.g=0; color.b=WheelPos * 3/dim; } return color; } CRGB Wheel(byte WheelPos) { if(WheelPos < 85) { return CRGB(WheelPos * 3, 255 - WheelPos * 3, 0); } else if(WheelPos < 170) { WheelPos -= 85; return CRGB(255 - WheelPos * 3, 0, WheelPos * 3); } else { WheelPos -= 170; return CRGB(0, WheelPos * 3, 255 - WheelPos * 3); } } CRGB randomColor(){ return Wheel(random(256)); }
[ "khuranachirag95@gmail.com" ]
khuranachirag95@gmail.com
aea875abef8aef583be65916a7490b525717446e
30874a1295d700427f7775d89a74ff5c4836dbe9
/libraries/ChLCD_MCP230xx/MCP230xxLCD.h
7a021eacee68dac5c9d0547354615285c0256fdc
[]
no_license
una1veritas/Arduino-public
f9b445bffe493e1c5b72f6587946b3fa3c5335ac
381cbd5193961534b910f1cfeb3a83bc273889a0
refs/heads/master
2021-01-19T15:20:21.300335
2020-10-15T12:08:24
2020-10-15T12:08:24
100,960,464
0
0
null
null
null
null
UTF-8
C++
false
false
2,338
h
/* * MCP2300xLCD.h * * Created on: 2012/04/18 * Author: sin */ #ifndef MCP2300xLCD_H_ #define MCP2300xLCD_H_ #if ARDUINO >= 100 #include "Arduino.h" #else #include "WPrograms.h" #endif //#include "Print.h" #include "IOExpander.h" #include "MCP230xx.h" #include "CharacterLCD.h" // from LiquidCrystal.h // commands #define LCD_CLEARDISPLAY 0x01 #define LCD_RETURNHOME 0x02 #define LCD_ENTRYMODESET 0x04 #define LCD_DISPLAYCONTROL 0x08 #define LCD_CURSORSHIFT 0x10 #define LCD_FUNCTIONSET 0x20 #define LCD_SETCGRAMADDR 0x40 #define LCD_SETDDRAMADDR 0x80 // flags for display entry mode #define LCD_ENTRYRIGHT 0x00 #define LCD_ENTRYLEFT 0x02 #define LCD_ENTRYSHIFTINCREMENT 0x01 #define LCD_ENTRYSHIFTDECREMENT 0x00 // flags for display on/off control #define LCD_DISPLAYON 0x04 #define LCD_DISPLAYOFF 0x00 #define LCD_CURSORON 0x02 #define LCD_CURSOROFF 0x00 #define LCD_BLINKON 0x01 #define LCD_BLINKOFF 0x00 // flags for display/cursor shift #define LCD_DISPLAYMOVE 0x08 #define LCD_CURSORMOVE 0x00 #define LCD_MOVERIGHT 0x04 #define LCD_MOVELEFT 0x00 // flags for function set #define LCD_8BITMODE 0x10 #define LCD_4BITMODE 0x00 #define LCD_2LINE 0x08 #define LCD_1LINE 0x00 #define LCD_5x10DOTS 0x04 #define LCD_5x8DOTS 0x00 class MCP230xxLCD: public CharacterLCD { MCP230xx xpander; uint8_t _rs_pin, _rw_pin, _enable_pin; uint8_t _data_pins[4]; uint8_t _bklight_pin; uint8_t _numcolumns; uint8_t _numlines; /* uint8_t cursorRow, cursorColumn; */ void write4bits(uint8_t); void pulseEnable(uint8_t); void pulseEnable(void); void init_xtender(); public: MCP230xxLCD(uint8_t addr, uint8_t rs, uint8_t wr, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t bklight = -1); // ~xLCD() {} void reset() { init_xtender(); } void begin(uint8_t cols = 16, uint8_t rows = 2, uint8_t dotsize = LCD_5x8DOTS); void init() { begin(); } void send(byte value, byte dcswitch); // void command(uint8_t); //#if ARDUINO >= 100 size_t write(uint8_t); //#else // void write(uint8_t); //#endif const byte displayRows() { return _numlines; } const byte displayColumns() { return _numcolumns; } void backlightOn(); void backlightOff(); }; #endif /* XLCD_H_ */
[ "una.veritas@me.com" ]
una.veritas@me.com
540e39b740d4d64be046bee523848379304e7ff7
9eb2eb4de471b6c522ecb6e11bd1d10ee3bf1c29
/src/gigablast/Spider.h
3459c12c54bea3b550d1c481f5ac80ae2ab15245
[ "Apache-2.0" ]
permissive
fossabot/kblast
6df5a5c6d4ae708a6813963f0dac990d94710a91
37b89fd6ba5ce429be5a69e2c6160da8a6aa21e6
refs/heads/main
2023-07-25T04:06:20.527449
2021-09-08T04:15:07
2021-09-08T04:15:07
404,208,031
1
0
Apache-2.0
2021-09-08T04:15:02
2021-09-08T04:15:01
null
UTF-8
C++
false
false
52,973
h
// SPDX-License-Identifier: Apache-2.0 // // Copyright 2000-2014 Matt Wells // Copyright 2004-2013 Gigablast, Inc. // Copyright 2013 Web Research Properties, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _SPIDER_H_ #define _SPIDER_H_ #define MAX_SPIDER_PRIORITIES 128 #define MAX_DAYS 365 #include "Rdb.h" #include "Conf.h" #include "Titledb.h" #include "Hostdb.h" #include "RdbList.h" #include "RdbTree.h" #include "HashTableX.h" #include <time.h> #include "Msg5.h" // local getList() #include "Msg4.h" #include "Msg1.h" #include "hash.h" #include "RdbCache.h" // for diffbot, this is for xmldoc.cpp to update CollectionRec::m_crawlInfo // which has m_pagesCrawled and m_pagesProcessed. //bool updateCrawlInfo ( CollectionRec *cr , // void *state , // void (* callback)(void *state) , // bool useCache = true ) ; // . values for CollectionRec::m_spiderStatus // . reasons why crawl is not happening #define SP_INITIALIZING 0 #define SP_MAXROUNDS 1 // hit max rounds limit #define SP_MAXTOCRAWL 2 // hit max to crawl limit #define SP_MAXTOPROCESS 3 // hit max to process limit #define SP_ROUNDDONE 4 // spider round is done #define SP_NOURLS 5 // initializing #define SP_PAUSED 6 // user paused spider #define SP_INPROGRESS 7 // it is going on! #define SP_ADMIN_PAUSED 8 // g_conf.m_spideringEnabled = false #define SP_COMPLETED 9 // crawl is done, and no repeatCrawl is scheduled bool tryToDeleteSpiderColl ( SpiderColl *sc ) ; void spiderRoundIncremented ( class CollectionRec *cr ) ; bool testPatterns ( ) ; bool doesStringContainPattern ( char *content , char *pattern ) ; bool getSpiderStatusMsg ( class CollectionRec *cx , class SafeBuf *msg , long *status ) ; long getFakeIpForUrl1 ( char *url1 ) ; long getFakeIpForUrl2 ( Url *url2 ) ; // Overview of Spider // // this new spider algorithm ensures that urls get spidered even if a host // is dead. and even if the url was being spidered by a host that suddenly went // dead. // // . Spider.h/.cpp contains all the code related to spider scheduling // . Spiderdb holds the SpiderRecs which indicate the time to spider a url // . there are 2 types of SpiderRecs: SpiderRequest and SpiderReply recs // // // There are 3 main components to the spidering process: // 1) spiderdb // 2) the "waiting tree" // 3) doledb // // spiderdb holds all the spiderrequests/spiderreplies sorted by // their IP // // the waiting tree holds at most one entry for an IP indicating that // we should scan all the spiderrequests/spiderreplies for that IP in // spiderdb, find the "best" one(s) and add it (them) to doledb. // // doledb holds the best spiderrequests from spiderdb sorted by // "priority". priorities range from 0 to 127, the highest priority. // basically doledb holds the urls that are ready for spidering now. // Spiderdb // // the spiderdb holds all the SpiderRequests and SpiderReplies, each of which // are sorted by their "firstIP" and then by their 48-bit url hash, // "uh48". the parentDocId is also kept in the key to prevent collisions. // Each group (shard) of hosts is responsible for spidering a fixed set of // IPs. // Dividing Workload by IP Address // // Each host is responsible for its own set of IP addresses. Each SpiderRequest // contains an IP address called m_firstIP. It alone is responsible for adding // SpiderRequests from this set of IPs to doledb. // the doled out // SpiderRequests are added to doledb using Msg4. Once in doledb, a // SpiderRequest is ready to be spidered by any host in the group (shard), // provided that that host gets all the locks. // "firstIP" // // when we lookup the ip address of the subdomain of an outlink for the first // time we store that ip address into tagdb using the tag named "firstip". // that way anytime we add outlinks from the same subdomain in the future they // are guaranteed to get the same "firstip" even if the actual ip changed. this // allows us to consistently throttle urls from the same subdomain, even if // the subdomain gets a new ip. this also increaseses performance when looking // up the "ips" of every outlink on a page because we are often just hitting // tagdb, which is much faster than doing dns lookups, that might miss the // dns cache! // Adding a SpiderRequest // // When a SpiderRequest is added to spiderdb in Rdb.cpp it calls // SpiderColl::addSpiderRequest(). If our host is responsible for doling // that firstIP, we check m_doleIPTable to see if that IP address is // already in doledb. if it is then we bail. Next we compute the url filter // number of the url in order to compute its spider time, then we add // it to the waiting tree. It will not get added to the waiting tree if // the current entry in the waiting tree has an earlier spider time. // then when the waiting tree is scanned it will read SpiderRequests from // spiderdb for just that firstIP and add the best one to doledb when it is // due to be spidered. // Waiting Tree // // The waiting tree is a b-tree where the keys are a spiderTime/IPaddress tuple // of the corresponding SpiderRequest. Think of its keys as requests to // spider something from that IP address at the given time, spiderTime. // The entries are sorted by spiderTime first then IP address. // It let's us know the earliest time we can spider a SpiderRequest // from an IP address. We have exactly one entry in the waiting tree from // every IP address that is in Spiderdb. "m_waitingTable" maps an IP // address to its entry in the waiting tree. If an IP should not be spidered // until the future then its spiderTime in the waiting tree will be in the // future. // Adding a SpiderReply // // We intercept SpiderReplies being added to Spiderdb in Rdb.cpp as well by // calling SpiderColl::addSpiderReply(). Then we get the firstIP // from that and we look in spiderdb to find a replacement SpiderRequest // to add to doledb. To make this part easy we just add the firstIP to the // waiting tree with a spiderTime of 0. so when the waiting tree scan happens // it will pick that up and look in spiderdb for the best SpiderRequest with // that same firstIP that can be spidered now, and then it adds that to // doledb. (To prevent from having to scan long spiderdb lists and speed // things up we might want to keep a little cache that maps a firstIP to // a few SpiderRequests ready to be spidered). // Deleting Dups // // we now remove spiderdb rec duplicates in the spiderdb merge. we also call // getUrlFilterNum() on each spiderdb rec during the merge to see if it is // filtered and not indexed, and if so, we delete it. we also delete all but // the latest SpiderReply for a given uh48/url. And we remove redundant // SpiderRequests like we used to do in addSpiderRequest(), which means that // the merge op needs to keep a small little table to scan in order to // compare all the SpiderRequests in the list for the same uh48. all of this // deduping takes place on the final merged list which is then further // filtered by this by calling Spiderdb.cpp::filterSpiderdbRecs(RdbList *list). // because the list is just a random piece of spiderdb, boundary issues will // cause some records to leak through, but with enough file merge operations // they should eventually be zapped. // DoleDB // // This holds SpiderRequests that are ready to be spidered right now. A host // in our group (shard) will call getLocks() to get the locks for a // SpiderRequest in doledb that it wants to spider. it must receive grants // from every alive machine in the group in order to properly get the lock. // If it receives a rejection from one host it release the lock on all the // other hosts. It is kind of random to get a lock, similar to ethernet // collision detection. // Dole IP Table // // m_doleIpTable (HashTableX, 96 bit keys, no data) // Purpose: let's us know how many SpiderRequests have been doled out for // a given firstIP // Key is simply a 4-byte IP. // Data is the number of doled out SpiderRequests from that IP. // we use m_doleIpTable for keeping counts based on ip of what is doled out. // // g_doledb // // Purpose: holds the spider request your group (shard) is supposed to spider // according to getGroupIdToSpider(). 96-bit keys, data is the spider rec with // key. ranked according to when things should be spidered. // <~priority> 8bits // <spiderTime> 32bits // <urlHash48> 48bits (to avoid collisions) // <reserved> 7bits (used 7 bits from urlhash48 to avoid collisio) // <delBit> 1bit // DATA: // <spiderRec> Xbits (spiderdb record to spider, includes key) // everyone in group (shard) tries to spider this shit in order. // you call SpiderLoop::getLocks(sr,hostId) to get the lock for it before // you can spider it. everyone in the group (shard) gets the lock request. // if you do not get granted lock by all alive hosts in the group (shard) then // you call Msg12::removeAllLocks(sr,hostId). nobody tries to spider // a doledb spider rec if the lock is granted to someone else, just skip it. // if a doling host goes dead, then its twins will dole for it after their // SpiderColl::m_nextReloadTime is reached and they reset their cache and // re-scan spiderdb. XmlDoc adds the negative key to RDB_DOLEDB so that // should remove it from doledb when the spidering is complete, and when // Rdb.cpp receives a "fake" negative TITLEDB key it removes the doledbKey lock // from m_lockTable. See XmlDoc.cpp "fake titledb key". // Furthermore, if Rdb.cpp receives a positive doledbKey // it might update SpiderColl::m_nextKeys[priority] so that the next read of // doledb starts there when SpiderLoop::spiderDoledUrls() calls // msg5 to read doledb records from disk. // TODO: when a host dies, consider speeding up the reload. might be 3 hrs! // PROBLEM: what if a host dies with outstanding locks??? // SpiderLoop::m_lockTable (HashTableX(6,8)) // Purpose: allows a host to lock a doledb key for spidering. used by Msg12 // and SpiderLoop. a host must get the lock for all its alive twins in its // group (shard) before it can spider the SpiderRequest, otherwise, it will // removeall the locks from the hosts that did grant it by calling // Msg12::removeAllLocks(sr,hostId). // GETTING A URL TO SPIDER // // To actually spider something, we do a read of doledb to get the next // SpiderRequest. Because there are so many negative/positive key annihilations // in doledb, we keep a "cursor key" for each spider priority in doledb. // We get a "lock" on the url so no other hosts in our group (shard) can // spider it from doledb. We get the lock if all hosts in the shard // successfully grant it to us, otherwise, we inform all the hosts that // we were unable to get the lock, so they can unlock it. // // SpiderLoop::spiderDoledUrls() will scan doledb for each collection that // has spidering enabled, and get the SpiderRequests in doledb that are // in need of spidering. The keys in doledb are sorted by highest spider // priority first and then by the "spider time". If one spider priority is // empty or only has spiderRequests in it that can be spidered in the future, // then the next priority is read. // // any host in our group (shard) can spider a request in doledb, but they must // lock it by calling getLocks() first and all hosts in the group (shard) must // grant them the lock for that url otherwise they remove all the locks and // try again on another spiderRequest in doledb. // // Each group (shard) is responsible for spidering a set of IPs in spiderdb. // and each host in the group (shard) has its own subset of those IPs for which // it is responsible for adding to doledb. but any host in the group (shard) // can spider any request/url in doledb provided they get the lock. // evalIpLoop() // // The waiting tree is populated at startup by scanning spiderdb (see // SpiderColl::evalIpLoop()), which might take a while to complete, // so it is running in the background while the gb server is up. it will // log "10836674298 spiderdb bytes scanned for waiting tree re-population" // periodically in the log as it tries to do a complete spiderdb scan // every 24 hours. It should not be necessary to scan spiderdb more than // once, but it seems we are leaking ips somehow so we do the follow-up // scans for now. (see populateWaitingTreeFromSpiderdb() in Spider.cpp) // It will also perform a background scan if the admin changes the url // filters table, which dictates that we recompute everything. // // evalIpLoop() will recompute the "url filter number" (matching row) // in the url filters table for each url in each SpiderRequest it reads. // it will ignore spider requests whose urls // are "filtered" or "banned". otherwise they will have a spider priority >= 0. // So it calls ::getUrlFilterNum() for each url it scans which is where // most of the cpu it uses will probably be spent. It picks the best // url to spider for each IP address. It only picks one per IP right now. // If the best url has a scheduled spider time in the future, it will add it // to the waiting tree with that future timestamp. The waiting tree only // stores one entry for each unique IP, so it tries to store // the entry with the earliest computed scheduled spider time, but if // some times are all BEFORE the current time, it will resolve conflicts // by preferring those with the highest priority. Tied spider priorities // should be resolved by minimum hopCount probably. // // If the spidertime of the URL is overdue then evalIpLoop() will NOT add // it to waiting tree, but will add it to doledb directly to make it available // for spidering immediately. It calls m_msg4.addMetaList() to add it to // doledb on all hosts in its group (shard). It uses s_ufnTree for keeping // track of the best urls to spider for a given IP/spiderPriority. // // evalIpLoop() can also be called with its m_nextKey/m_endKey limited // to just scan the SpiderRequests for a specific IP address. It does // this after adding a SpiderReply. addSpiderReply() calls addToWaitingTree() // with the "0" time entry, and addToWaitingTree() calls // populateDoledbFromWaitingTree() which will see that "0" entry and call // evalIpLoop(true) after setting m_nextKey/m_endKey for that IP. // POPULATING DOLEB // // SpiderColl::populateDoledbFromWaitingTree() scans the waiting tree for // entries whose spider time is due. so it gets the IP address and spider // priority from the waiting tree. but then it calls evalIpLoop() // restricted to that IP (using m_nextKey,m_endKey) to get the best // SpiderRequest from spiderdb for that IP to add to doledb for immediate // spidering. populateDoledbFromWaitingTree() is called a lot to try to // keep doledb in sync with waiting tree. any time an entry in the waiting // tree becomes available for spidering it should be called right away so // as not to hold back the spiders. in general it should exit quickly because // it calls getNextIpFromWaitingTree() which most of the time will return 0 // indicating there are no IPs in the waiting tree ready to be spidered. // Which is why as we add SpiderRequests to doledb for an IP we also // remove that IP from the waiting tree. This keeps this check fast. // SUPPORTING MULTIPLE SPIDERS PER IP // // In order to allow multiple outstanding spiders per IP address, if, say, // maxSpidersPerIp is > 1, we now promptly add the negative doledb key // as soon as a lock is granted and we also add an entry to the waiting tree // which will result in an addition to doledb of the next unlocked // SpiderRequest. This logic is mostly in Spider.cpp's Msg12::gotLockReply(). // // Rdb.cpp will see that we added a "fakedb" record // A record is only removed from Doledb after the spider adds the negative // doledb record in XmlDoc.cpp when it is done. XmlDoc.cpp also adds a // "fake" negative titledb record to remove the lock on that url at the // same time. // // So, 1) we can allow for multiple doledb entries per IP and the assigned // host can reply with "wait X ms" to honor the spiderIpWait constraint, // or 2) we can delete the doledb entry after the lock is granted, and then // we can immediately add a "currentTime + X ms" entry to the waiting tree to // add the next doledb record for this IP X ms from now. // // I kind of like the 2nd approach because then there is only one entry // per IP in doledb. that is kind of nice. So maybe using the same // logic that is used by Spider.cpp to release a lock, we can say, // "hey, i got the lock, delete it from doledb"... // . what groupId (shardId) should spider/index this spider request? // . CAUTION: NOT the same group (shard) that stores it in spiderdb!!! // . CAUTION: NOT the same group (shard) that doles it out to spider!!! //unsigned long getGroupIdToSpider ( char *spiderRec ); // now used by xmldoc.cpp bool isAggregator ( long siteHash32 , long domHash32 , char *url , long urlLen ) ; // The 128-bit Spiderdb record key128_t for a rec in Spiderdb is as follows: // // <32 bit firstIp> (firstIp of the url to spider) // <48 bit normalized url hash> (of the url to spider) // <1 bit isRequest> (a SpiderRequest or SpiderReply record?) // <38 bit docid of parent> (to avoid collisions!) // <8 bit reserved> (was "spiderLinks"/"forced"/"retryNum") // <1 bit delbit> (0 means this is a *negative* key) // there are two types of SpiderRecs really, a "request" to spider a url // and a "reply" or report on the attempted spidering of a url. in this way // Spiderdb is a perfect log of desired and actual spider activity. // . Spiderdb contains an m_rdb which has SpiderRecs/urls to be spidered // . we split the SpiderRecs up w/ the hosts in our group (shard) by IP of the // url. // . once we've spidered a url it gets added with a negative spiderdb key // in XmlDoc.cpp class Spiderdb { public: // reset rdb void reset(); // set up our private rdb for holding SpiderRecs bool init ( ); // init the rebuild/secondary rdb, used by PageRepair.cpp bool init2 ( long treeMem ); bool verify ( char *coll ); bool addColl ( char *coll, bool doVerify = true ); Rdb *getRdb ( ) { return &m_rdb; }; DiskPageCache *getDiskPageCache() { return &m_pc; }; // this rdb holds urls waiting to be spidered or being spidered Rdb m_rdb; long long getUrlHash48 ( key128_t *k ) { return (((k->n1)<<16) | k->n0>>(64-16)) & 0xffffffffffffLL; }; bool isSpiderRequest ( key128_t *k ) { return (k->n0>>(64-17))&0x01; }; bool isSpiderReply ( key128_t *k ) { return ((k->n0>>(64-17))&0x01)==0x00; }; long long getParentDocId ( key128_t *k ) {return (k->n0>>9)&DOCID_MASK;}; // same as above long long getDocId ( key128_t *k ) {return (k->n0>>9)&DOCID_MASK;}; long getFirstIp ( key128_t *k ) { return (k->n1>>32); } key128_t makeKey ( long firstIp , long long urlHash48 , bool isRequest , long long parentDocId , bool isDel ) ; key128_t makeFirstKey ( long firstIp ) { return makeKey ( firstIp,0LL,false,0LL,true); }; key128_t makeLastKey ( long firstIp ) { return makeKey ( firstIp,0xffffffffffffLL,true, MAX_DOCID,false); }; key128_t makeFirstKey2 ( long firstIp , long long uh48 ) { return makeKey ( firstIp,uh48,false,0LL,true); }; key128_t makeLastKey2 ( long firstIp , long long uh48 ) { return makeKey ( firstIp,uh48,true,MAX_DOCID,false); }; // what groupId (shardid) spiders this url? /* inline unsigned long getShardNum ( long firstIp ) { // must be valid if ( firstIp == 0 || firstIp == -1 ) {char *xx=NULL;*xx=0; } // mix it up unsigned long h = (unsigned long)hash32h ( firstIp, 0x123456 ); // get it return h % g_hostdb.m_numShards; }; */ // print the spider rec long print( char *srec ); private: DiskPageCache m_pc; }; void dedupSpiderdbList ( RdbList *list , long niceness , bool removeNegRecs ); extern class Spiderdb g_spiderdb; extern class Spiderdb g_spiderdb2; class SpiderRequest { public: // we now define the data so we can use this class to cast // a SpiderRec outright key128_t m_key; long m_dataSize; // this ip is taken from the TagRec for the domain of the m_url, // but we do a dns lookup initially if not in tagdb and we put it in // tagdb then. that way, even if the domain gets a new ip, we still // use the original ip for purposes of deciding which groupId (shardId) // is responsible for storing, doling/throttling this domain. if the // ip lookup results in NXDOMAIN or another error then we generally // do not add it to tagdb in msge*.cpp. this ensures that any given // domain will always be spidered by the same group (shard) of hosts // even if the ip changes later on. this also increases performance // since we do a lot fewer dns lookups on the outlinks. long m_firstIp; //long getFirstIp ( ) { return g_spiderdb.getFirstIp(&m_key); }; long m_hostHash32; long m_domHash32; long m_siteHash32; // this is computed from every outlink's tagdb record but i guess // we can update it when adding a spider rec reply long m_siteNumInlinks; // . when this request was first was added to spiderdb // . Spider.cpp dedups the oldest SpiderRequests that have the // same bit flags as this one. that way, we get the most uptodate // date in the request... UNFORTUNATELY we lose m_addedTime then!!! time_t m_addedTime; // if m_isNewOutlink is true, then this SpiderRequest is being added // for a link that did not exist on this page the last time it was // spidered. XmlDoc.cpp needs to set XmlDoc::m_min/maxPubDate for // m_url. if m_url's content does not contain a pub date explicitly // then we can estimate it based on when m_url's parent was last // spidered (when m_url was not an outlink on its parent page) time_t m_parentPrevSpiderTime; // info on the page we were harvest from long m_parentFirstIp; long m_parentHostHash32; long m_parentDomHash32; long m_parentSiteHash32; // the PROBABLE DOCID. if there is a collision with another docid // then we increment the last 8 bits or so. see Msg22.cpp. long long m_probDocId; //long m_parentPubDate; // . pub date taken from url directly, not content // . ie. http://mysite.com/blog/nov-06-2009/food.html // . ie. http://mysite.com/blog/11062009/food.html //long m_urlPubDate; // . replace this with something we need for smart compression // . this is zero if none or invalid long m_contentHash32; // . each request can have a different hop count // . this is only valid if m_hopCountValid is true! // . i made this a short from long to support m_parentLangId etc above short m_hopCount; // when creating a chinese search engine for instance it is nice // to know the language of the page we are spidering's parent. // typically a chinese page will link to another chinese page, // though not always of course. this is the primary language of // the parent. uint8_t m_parentLangId;//reserved1; // the new add url control will allow user to control link spidering // on each url they add. they can also specify file:// instead of // http:// to index local files. so we have to allow file:// /* char m_onlyAddSameDomainLinks :1; */ /* char m_onlyAddSameSubdomainLinks :1; */ /* char m_onlyDoNotAddLinksLinks :1; // max hopcount 1 */ /* char m_onlyDoNotAddLinksLinksLinks :1; // max hopcount 2 */ char m_ignoreDocUnchangedError:1;//reserved2a:1; char m_reserved2b:1; char m_reserved2c:1; char m_reserved2d:1; char m_reserved2e:1; char m_reserved2f:1; char m_reserved2g:1; char m_reserved2h:1; //long m_hopCount; // . this is now computed dynamically often based on the latest // m_addedTime and m_percentChanged of all the SpideRec *replies*. // we may decide to change some url filters // that affect this computation. so SpiderCache always changes // this value before adding any SpiderRec *request* to the // m_orderTree, etc. //time_t m_spiderTime; // // our bit flags // long m_hopCountValid:1; // are we a request/reply from the add url page? long m_isAddUrl:1; // are we a request/reply from PageReindex.cpp long m_isPageReindex:1; // are we a request/reply from PageInject.cpp long m_isPageInject:1; // or from PageParser.cpp directly long m_isPageParser:1; // should we use the test-spider-dir for caching test coll requests? long m_useTestSpiderDir:1; // . is the url a docid (not an actual url) // . could be a "query reindex" long m_urlIsDocId:1; // does m_url end in .rss? or a related rss file extension? long m_isRSSExt:1; // is url in a format known to be a permalink format? long m_isUrlPermalinkFormat:1; // is url "rpc.weblogs.com/shortChanges.xml"? long m_isPingServer:1; // . are we a delete instruction? (from Msg7.cpp as well) // . if you want it to be permanently banned you should ban or filter // it in the urlfilters/tagdb. so this is kinda useless... long m_forceDelete:1; // are we a fake spider rec? called from Test.cpp now! long m_isInjecting:1; // are we a respider request from Sections.cpp //long m_fromSections:1; // a new flag. replaced above. did we have a corresponding SpiderReply? long m_hadReply:1; // are we scraping from google, etc.? long m_isScraping:1; // page add url can be updated to store content for the web page // into titledb or something to simulate injections of yore. we can // use that content as the content of the web page. the add url can // accept it from a form and we store it right away into titledb i // guess using msg4, then we look it up when we spider the url. long m_hasContent:1; // is first ip a hash of url or docid or whatever? long m_fakeFirstIp:1; // www.xxx.com/*? or xxx.com/*? long m_isWWWSubdomain:1; // // these "parent" bits are invalid if m_parentHostHash32 is 0! // that includes m_isMenuOutlink // // if the parent was respidered and the outlink was there last time // and is there now, then this is "0", otherwise, this is "1" long m_isNewOutlink :1; long m_sameDom :1; long m_sameHost :1; long m_sameSite :1; long m_wasParentIndexed :1; long m_parentIsRSS :1; long m_parentIsPermalink :1; long m_parentIsPingServer:1; long m_parentHasAddress :1; // is this outlink from content or menu? long m_isMenuOutlink :1; // // these bits also in SpiderReply // // was it in google's index? long m_inGoogle:1; // expires after a certain time or if ownership changed // did it have an inlink from a really nice site? long m_hasAuthorityInlink :1; long m_hasContactInfo :1; long m_isContacty :1; long m_hasSiteVenue :1; // are the 3 bits above valid? // if site ownership changes might be invalidated. // "inGoogle" also may expire after so long too long m_inGoogleValid :1; long m_hasAuthorityInlinkValid :1; long m_hasContactInfoValid :1; long m_isContactyValid :1; long m_hasAddressValid :1; //long m_matchesUrlCrawlPattern :1; //long m_matchesUrlProcessPattern:1; long m_hasTODValid :1; long m_hasSiteVenueValid :1; long m_siteNumInlinksValid :1; // . only support certain tags in url filters now i guess // . use the tag value from most recent SpiderRequest only // . the "deep" tag is popular for hitting certain sites hard //long m_tagDeep:1; // we set this to one from Diffbot.cpp when urldata does not // want the url's to have their links spidered. default is to make // this 0 and to not avoid spidering the links. long m_avoidSpiderLinks:1; // for identifying address heavy sites... //long m_tagYellowPages:1; // when indexing urls for dmoz, i.e. the urls outputted from // 'dmozparse urldump -s' we need to index them even if there // was a ETCPTIMEDOUT because we have to have indexed the same // urls that dmoz has in it in order to be identical to dmoz. long m_ignoreExternalErrors:1; // called XmlDoc::set4() from PageSubmit.cpp? //long m_isPageSubmit:1; // // INTERNAL USE ONLY // // are we in the m_orderTree/m_doleTables/m_ipTree //long m_inOrderTree:1; // are we doled out? //long m_doled:1; // are we a re-add of a spiderrequest already in spiderdb added // from xmldoc.cpp when done spidering so that the spider request // gets back in the cache quickly? //long m_readd:1; // . what url filter num do we match in the url filters table? // . determines our spider priority and wait time short m_ufn; // . m_priority is dynamically computed like m_spiderTime // . can be negative to indicate filtered, banned, skipped, etc. // . for the spiderrec request, this is invalid until it is set // by the SpiderCache logic, but for the spiderrec reply this is // the priority we used! char m_priority; // . this is copied from the most recent SpiderReply into here // . its so XMlDoc.cpp can increment it and add it to the new // SpiderReply it adds in case there is another download error , // like ETCPTIMEDOUT or EDNSTIMEDOUT char m_errCount; // we really only need store the url for *requests* and not replies char m_url[MAX_URL_LEN+1]; // . basic functions // . clear all void reset() { memset ( this , 0 , (long)m_url - (long)&m_key ); // -1 means uninitialized, this is required now m_ufn = -1; // this too m_priority = -1; // this happens to be zero already, but just in case it changes m_parentLangId = langUnknown; }; static long getNeededSize ( long urlLen ) { return sizeof(SpiderRequest) - (long)MAX_URL_LEN + urlLen; }; long getRecSize () { return m_dataSize + 4 + sizeof(key128_t); } // how much buf will we need to serialize ourselves? //long getRecSize () { // //return m_dataSize + 4 + sizeof(key128_t); } // return (m_url - (char *)this) + gbstrlen(m_url) + 1 // // subtract m_key and m_dataSize // - sizeof(key_t) - 4 ; //}; long getUrlLen() { return m_dataSize - // subtract the \0 ((char *)m_url-(char *)&m_firstIp) - 1;}; char *getUrlPath() { char *p = m_url; for ( ; *p ; p++ ) { if ( *p != ':' ) continue; p++; if ( *p != '/' ) continue; p++; if ( *p != '/' ) continue; p++; break; } if ( ! *p ) return NULL; // skip until / then for ( ; *p && *p !='/' ; p++ ) ; if ( *p != '/' ) return NULL; // return root path of / if there. return p; }; //long getUrlLen() { return gbstrlen(m_url); }; void setKey ( long firstIp , long long parentDocId , long long uh48 , bool isDel ) ; void setKey ( long firstIp, long long parentDocId , bool isDel ) { long long uh48 = hash64b ( m_url ); setKey ( firstIp , parentDocId, uh48, isDel ); } void setDataSize ( ); long long getUrlHash48 () {return g_spiderdb.getUrlHash48(&m_key); }; long long getParentDocId (){return g_spiderdb.getParentDocId(&m_key);}; long print( class SafeBuf *sb ); long printToTable ( SafeBuf *sb , char *status , class XmlDoc *xd , long row ) ; // for diffbot... long printToTableSimple ( SafeBuf *sb , char *status , class XmlDoc *xd , long row ) ; static long printTableHeader ( SafeBuf *sb , bool currentlSpidering ) ; static long printTableHeaderSimple ( SafeBuf *sb , bool currentlSpidering ) ; // returns false and sets g_errno on error bool setFromAddUrl ( char *url ) ; bool setFromInject ( char *url ) ; }; // . XmlDoc adds this record to spiderdb after attempting to spider a url // supplied to it by a SpiderRequest // . before adding a SpiderRequest to the spider cache, we scan through // all of its SpiderRecReply records and just grab the last one. then // we pass that to ::getUrlFilterNum() // . if it was not a successful reply, then we try to populate it with // the member variables from the last *successful* reply before passing // it to ::getUrlFilterNum() // . getUrlFilterNum() also takes the SpiderRequest record as well now // . we only keep the last X successful SpiderRecReply records, and the // last unsucessful Y records (only if more recent), and we nuke all the // other SpiderRecReply records class SpiderReply { public: // we now define the data so we can use this class to cast // a SpiderRec outright key128_t m_key; long m_dataSize; // for calling getHostIdToDole() long m_firstIp; //long getFirstIp ( ) { return g_spiderdb.getFirstIp(&m_key); }; // we need this too in case it changes! long m_siteHash32; // and this for updating crawl delay in m_cdTable long m_domHash32; // since the last successful SpiderRecReply float m_percentChangedPerDay; // when we attempted to spider it time_t m_spideredTime; // . value of g_errno/m_indexCode. 0 means successfully indexed. // . might be EDOCBANNED or EDOCFILTERED long m_errCode; // this is fresher usually so we can use it to override // SpiderRequest's m_siteNumLinks long m_siteNumInlinks; // how many inlinks does this particular page have? //long m_pageNumInlinks; // the actual pub date we extracted (0 means none, -1 unknown) long m_pubDate; // . SpiderRequests added to spiderdb since m_spideredTime // . XmlDoc.cpp's ::getUrlFilterNum() uses this as "newinlinks" arg //long m_newRequests; // . replaced m_newRequests // . this is zero if none or invalid long m_contentHash32; // in milliseconds, from robots.txt (-1 means none) // TODO: store in tagdb, lookup when we lookup tagdb recs for all // out outlinks long m_crawlDelayMS; // . when we basically finished DOWNLOADING it // . use 0 if we did not download at all // . used by Spider.cpp to space out urls using sameIpWait long long m_downloadEndTime; // how many errors have we had in a row? //long m_retryNum; // . like "404" etc. "200" means successfully downloaded // . we can still successfully index pages that are 404 or permission // denied, because we might have link text for them. short m_httpStatus; // . only non-zero if errCode is set! // . 1 means it is the first time we tried to download and got an error // . 2 means second, etc. char m_errCount; // what language was the page in? char m_langId; // // our bit flags // // XmlDoc::isSpam() returned true for it! //char m_isSpam:1; // was the page in rss format? long m_isRSS:1; // was the page a permalink? long m_isPermalink:1; // are we a pingserver page? long m_isPingServer:1; // did we delete the doc from the index? //long m_deleted:1; // was it in the index when we were done? long m_isIndexed:1; // // these bits also in SpiderRequest // // was it in google's index? long m_inGoogle:1; // did it have an inlink from a really nice site? long m_hasAuthorityInlink:1; // does it have contact info long m_hasContactInfo:1; long m_isContacty :1; long m_hasAddress :1; long m_hasTOD :1; // make this "INvalid" not valid since it was set to 0 before // and we want to be backwards compatible long m_isIndexedINValid :1; //long m_hasSiteVenue :1; // expires after a certain time or if ownership changed long m_inGoogleValid :1; long m_hasContactInfoValid :1; long m_hasAuthorityInlinkValid :1; long m_isContactyValid :1; long m_hasAddressValid :1; long m_hasTODValid :1; //long m_hasSiteVenueValid :1; long m_reserved2 :1; long m_siteNumInlinksValid :1; // was the request an injection request long m_fromInjectionRequest :1; // did we TRY to send it to the diffbot backend filter? might be err? long m_sentToDiffbot :1; long m_hadDiffbotError :1; // . was it in the index when we started? // . we use this with m_isIndexed above to adjust quota counts for // this m_siteHash32 which is basically just the subdomain/host // for SpiderColl::m_quotaTable long m_wasIndexed :1; // this also pertains to m_isIndexed as well: long m_wasIndexedValid :1; // how much buf will we need to serialize ourselves? long getRecSize () { return m_dataSize + 4 + sizeof(key128_t); } // clear all void reset() { memset ( this , 0 , sizeof(SpiderReply) ); }; void setKey ( long firstIp, long long parentDocId , long long uh48 , bool isDel ) ; long print ( class SafeBuf *sbarg ); long long getUrlHash48 () {return g_spiderdb.getUrlHash48(&m_key); }; long long getParentDocId (){return g_spiderdb.getParentDocId(&m_key);}; }; // are we responsible for this ip? bool isAssignedToUs ( long firstIp ) ; #define DOLEDBKEY key_t // . store urls that can be spidered right NOW in doledb // . SpiderLoop.cpp doles out urls from its local spiderdb into // the doledb rdb of remote hosts (and itself as well sometimes!) // . then each host calls SpiderLoop::spiderDoledUrls() to spider the // urls doled to their group (shard) in doledb class Doledb { public: void reset(); bool init ( ); bool addColl ( char *coll, bool doVerify = true ); DiskPageCache *getDiskPageCache() { return &m_pc; }; // . see "overview of spidercache" below for key definition // . these keys when hashed are clogging up the hash table // so i am making the 7 reserved bits part of the urlhash48... key_t makeKey ( long priority , time_t spiderTime , long long urlHash48 , bool isDelete ) { // sanity checks if ( priority & 0xffffff00 ) { char *xx=NULL;*xx=0;} if ( urlHash48 & 0xffff000000000000LL ) { char *xx=NULL;*xx=0;} key_t k; k.n1 = (255 - priority); k.n1 <<= 24; k.n1 |= (spiderTime >>8); k.n0 = spiderTime & 0xff; k.n0 <<= 48; k.n0 |= urlHash48; // 7 bits reserved k.n0 <<= 7; // still reserved but when adding to m_doleReqTable it needs // to be more random!! otherwise the hash table is way slow! k.n0 |= (urlHash48 & 0x7f); // 1 bit for negative bit k.n0 <<= 1; // we are positive or not? setting this means we are positive if ( ! isDelete ) k.n0 |= 0x01; return k; }; // . use this for a query reindex // . a docid-based spider request // . crap, might we have collisions between a uh48 and docid???? key_t makeReindexKey ( long priority , time_t spiderTime , long long docId , bool isDelete ) { return makeKey ( priority,spiderTime,docId,isDelete); }; key_t makeFirstKey2 ( long priority ) { key_t k; k.setMin(); // set priority k.n1 = (255 - priority); k.n1 <<= 24; return k; }; key_t makeLastKey2 ( long priority ) { key_t k; k.setMax(); // set priority k.n1 = (255 - priority); k.n1 <<= 24; k.n1 |= 0x00ffffff; return k; }; long getPriority ( key_t *k ) { return 255 - ((k->n1 >> 24) & 0xff); }; long getSpiderTime ( key_t *k ) { unsigned long spiderTime = (k->n1) & 0xffffff; spiderTime <<= 8; // upper 8 bits of k.n0 are lower 8 bits of spiderTime spiderTime |= (unsigned long)((k->n0) >> (64-8)); return (long)spiderTime; }; long getIsDel ( key_t *k ) { if ( (k->n0 & 0x01) ) return 0; return 1; }; long long getUrlHash48 ( key_t *k ) { return (k->n0>>8)&0x0000ffffffffffffLL; } key_t makeFirstKey ( ) { key_t k; k.setMin(); return k;}; key_t makeLastKey ( ) { key_t k; k.setMax(); return k;}; Rdb *getRdb() { return &m_rdb;}; Rdb m_rdb; DiskPageCache m_pc; }; extern class Doledb g_doledb; // was 1000 but breached, now equals SR_READ_SIZE/sizeof(SpiderReply) #define MAX_BEST_REQUEST_SIZE (MAX_URL_LEN+1+sizeof(SpiderRequest)) #define MAX_DOLEREC_SIZE (MAX_BEST_REQUEST_SIZE+sizeof(key_t)+4) #define MAX_SP_REPLY_SIZE (sizeof(SpiderReply)) // we have one SpiderColl for each collection record class SpiderColl { public: ~SpiderColl ( ); SpiderColl ( ) ; void clearLocks(); // called by main.cpp on exit to free memory void reset(); bool load(); long long m_msg4Start; long getTotalOutstandingSpiders ( ) ; void urlFiltersChanged(); key128_t m_firstKey; // spiderdb is now 128bit keys key128_t m_nextKey; key128_t m_endKey; bool m_useTree; //bool m_lastDoledbReadEmpty; //bool m_encounteredDoledbRecs; //long long m_numRoundsDone; //bool m_bestRequestValid; //char m_bestRequestBuf[MAX_BEST_REQUEST_SIZE]; //SpiderRequest *m_bestRequest; //uint64_t m_bestSpiderTimeMS; //long m_bestMaxSpidersPerIp; bool m_lastReplyValid; char m_lastReplyBuf[MAX_SP_REPLY_SIZE]; // doledbkey + dataSize + bestRequestRec //char m_doleBuf[MAX_DOLEREC_SIZE]; SafeBuf m_doleBuf; bool m_isLoading; // for scanning the wait tree... bool m_isPopulating; // for reading from spiderdb //bool m_isReadDone; bool m_didRead; // corresponding to CollectionRec::m_siteListBuf //char *m_siteListAsteriskLine; bool m_siteListHasNegatives; bool m_siteListIsEmpty; bool m_siteListIsEmptyValid; // data buckets in this table are of type HashTableX m_siteListDomTable; // substring matches like "contains:goodstuff" or // later "regex:.*" SafeBuf m_negSubstringBuf; SafeBuf m_posSubstringBuf; RdbCache m_dupCache; RdbTree m_winnerTree; HashTableX m_winnerTable; long m_tailIp; long m_tailPriority; long long m_tailTimeMS; long long m_tailUh48; long m_tailHopCount; long long m_minFutureTimeMS; Msg4 m_msg4x; Msg4 m_msg4; Msg1 m_msg1; bool m_msg1Avail; bool isInDupCache ( SpiderRequest *sreq , bool addToCache ) ; // Rdb.cpp calls this bool addSpiderReply ( SpiderReply *srep ); bool addSpiderRequest ( SpiderRequest *sreq , long long nowGlobalMS ); void removeFromDoledbTable ( long firstIp ); bool addToDoleTable ( SpiderRequest *sreq ) ; bool updateSiteNumInlinksTable ( long siteHash32,long sni,long tstamp); uint64_t getSpiderTimeMS ( SpiderRequest *sreq, long ufn, SpiderReply *srep, uint64_t nowGlobalMS); // doledb cursor keys for each priority to speed up performance key_t m_nextKeys[MAX_SPIDER_PRIORITIES]; // save us scanning empty priorities char m_isDoledbEmpty [MAX_SPIDER_PRIORITIES]; // are all priority slots empt? //long m_allDoledbPrioritiesEmpty; //long m_lastEmptyCheck; // maps priority to first ufn that uses that // priority. map to -1 if no ufn uses it. that way when we scan // priorities for spiderrequests to dole out we can start with // priority 63 and see what the max spiders or same ip wait are // because we need the ufn to get the maxSpiders from the url filters // table. long m_priorityToUfn[MAX_SPIDER_PRIORITIES]; // init this to false, and also set to false on reset, then when // it is false we re-stock m_ufns. re-stock if user changes the // url filters table... bool m_ufnMapValid; // list for loading spiderdb recs during the spiderdb scan RdbList m_list; // spiderdb scan for populating waiting tree RdbList m_list2; Msg5 m_msg5b; bool m_gettingList2; key128_t m_nextKey2; key128_t m_endKey2; time_t m_lastScanTime; bool m_waitingTreeNeedsRebuild; long m_numAdded; long long m_numBytesScanned; long long m_lastPrintCount; // used by SpiderLoop.cpp long m_spidersOut; // . hash of collection name this arena represents // . 0 for main collection collnum_t m_collnum; char m_coll [ MAX_COLL_LEN + 1 ] ; class CollectionRec *getCollRec(); class CollectionRec *m_cr; char *getCollName(); bool m_isTestColl; HashTableX m_doleIpTable; // freshest m_siteNumInlinks per site stored in here HashTableX m_sniTable; // maps a domainHash32 to a crawl delay in milliseconds HashTableX m_cdTable; RdbCache m_lastDownloadCache; bool m_countingPagesIndexed; HashTableX m_localTable; long long m_lastReqUh48a; long long m_lastReqUh48b; long long m_lastRepUh48; // move to CollectionRec so it can load at startup and save it //HashTableX m_pageCountTable; bool makeDoleIPTable ( ); bool makeWaitingTable ( ); bool makeWaitingTree ( ); long long getEarliestSpiderTimeFromWaitingTree ( long firstIp ) ; bool printWaitingTree ( ) ; bool addToWaitingTree ( uint64_t spiderTime , long firstIp , bool callForScan ); long getNextIpFromWaitingTree ( ); void populateDoledbFromWaitingTree ( ); //bool scanSpiderdb ( bool needList ); // broke up scanSpiderdb into simpler functions: bool evalIpLoop ( ) ; bool readListFromSpiderdb ( ) ; bool scanListForWinners ( ) ; bool addWinnersIntoDoledb ( ) ; void populateWaitingTreeFromSpiderdb ( bool reentry ) ; HashTableX m_waitingTable; RdbTree m_waitingTree; RdbMem m_waitingMem; // used by m_waitingTree key_t m_waitingTreeKey; bool m_waitingTreeKeyValid; long m_scanningIp; long m_gotNewDataForScanningIp; long m_lastListSize; long m_lastScanningIp; long long m_totalBytesScanned; char m_deleteMyself; // start key for reading doledb key_t m_msg5StartKey; void devancePriority(); key_t m_nextDoledbKey; bool m_didRound; long m_pri2; bool m_twinDied; long m_lastUrlFiltersUpdate; // for reading lists from spiderdb Msg5 m_msg5; bool m_gettingList1; // how many outstanding spiders a priority has long m_outstandingSpiders[MAX_SPIDER_PRIORITIES]; bool printStats ( SafeBuf &sb ) ; }; class SpiderCache { public: // returns false and set g_errno on error bool init ( ) ; SpiderCache ( ) ; // what SpiderColl does a SpiderRec with this key belong? SpiderColl *getSpiderColl ( collnum_t collNum ) ; SpiderColl *getSpiderCollIffNonNull ( collnum_t collNum ) ; // called by main.cpp on exit to free memory void reset(); void save ( bool useThread ); bool needsSave ( ) ; void doneSaving ( ) ; bool m_isSaving; // . we allocate one SpiderColl per collection // . each one stores the collNum of the collection name it represents, // and has a ptr to it, m_cr, that is updated by sync() // when the Collectiondb is updated // . NOW, this is a ptr in the CollectionRec.. only new'd if // in use, and deleted if not being used... //SpiderColl *m_spiderColls [ MAX_COLL_RECS ]; //long m_numSpiderColls; }; extern class SpiderCache g_spiderCache; ///////// // // we now include the firstip in the case where the same url // has 2 spiderrequests where one is a fake firstip. in that scenario // we will miss the spider request to spider, the waiting tree // node will be removed, and the spider round will complete, // which triggers a waiting tree recompute and we end up spidering // the dup spider request right away and double increment the round. // ///////// inline long long makeLockTableKey ( long long uh48 , long firstIp ) { return uh48 ^ (unsigned long)firstIp; } inline long long makeLockTableKey ( SpiderRequest *sreq ) { return makeLockTableKey(sreq->getUrlHash48(),sreq->m_firstIp); } inline long long makeLockTableKey ( SpiderReply *srep ) { return makeLockTableKey(srep->getUrlHash48(),srep->m_firstIp); } class LockRequest { public: long long m_lockKeyUh48; long m_lockSequence; long m_firstIp; char m_removeLock; collnum_t m_collnum; }; class ConfirmRequest { public: long long m_lockKeyUh48; collnum_t m_collnum; key_t m_doledbKey; long m_firstIp; long m_maxSpidersOutPerIp; }; class UrlLock { public: long m_hostId; long m_lockSequence; long m_timestamp; long m_expires; long m_firstIp; char m_spiderOutstanding; char m_confirmed; collnum_t m_collnum; }; class Msg12 { public: Msg12(); bool confirmLockAcquisition ( ) ; //unsigned long m_lockGroupId; LockRequest m_lockRequest; ConfirmRequest m_confirmRequest; // stuff for getting the msg12 lock for spidering a url bool getLocks ( long long probDocId, char *url , DOLEDBKEY *doledbKey, collnum_t collnum, long sameIpWaitTime, // in milliseconds long maxSpidersOutPerIp, long firstIp, void *state, void (* callback)(void *state) ); bool gotLockReply ( class UdpSlot *slot ); bool removeAllLocks ( ); // these two things comprise the lock request buffer //unsigned long long m_lockKey; // this is the new lock key. just use docid for docid-only spider reqs. unsigned long long m_lockKeyUh48; long m_lockSequence; long long m_origUh48; long m_numReplies; long m_numRequests; long m_grants; bool m_removing; bool m_confirming; char *m_url; // for debugging void *m_state; void (*m_callback)(void *state); bool m_gettingLocks; bool m_hasLock; collnum_t m_collnum; DOLEDBKEY m_doledbKey; long m_sameIpWaitTime; long m_maxSpidersOutPerIp; long m_firstIp; Msg4 m_msg4; }; void handleRequest12 ( UdpSlot *udpSlot , long niceness ) ; void handleRequestc1 ( UdpSlot *slot , long niceness ) ; // . the spider loop // . it gets urls to spider from the SpiderCache global class, g_spiderCache // . supports robots.txt // . supports <META NAME="ROBOTS" CONTENT="NOINDEX"> (no indexing) // . supports <META NAME="ROBOTS" CONTENT="NOFOLLOW"> (no links) // . supports limiting spiders per domain // . max spiders we can have going at once for this process // . limit to 50 to preven OOM conditions #define MAX_SPIDERS 100 class SpiderLoop { public: ~SpiderLoop(); SpiderLoop(); bool isInLockTable ( long long probDocId ); bool printLockTable ( ); long getNumSpidersOutPerIp ( long firstIp , collnum_t collnum ) ; // free all XmlDocs and m_list void reset(); // . call this no matter what // . if spidering is disabled this will sleep about 10 seconds or so // before checking to see if it's been enabled void startLoop(); void doLoop(); void doleUrls1(); void doleUrls2(); long getMaxAllowableSpidersOut ( long pri ) ; void spiderDoledUrls ( ) ; bool gotDoledbList2 ( ) ; // . returns false if blocked and "callback" will be called, // true otherwise // . returns true and sets g_errno on error bool spiderUrl9 ( class SpiderRequest *sreq , key_t *doledbKey , collnum_t collnum,//char *coll , long sameIpWaitTime , // in milliseconds long maxSpidersOutPerIp ); bool spiderUrl2 ( ); Msg12 m_msg12; // state memory for calling SpiderUrl2() (maybe also getLocks()!) SpiderRequest *m_sreq; //char *m_coll; collnum_t m_collnum; char *m_content; long m_contentLen; char m_contentHasMime; key_t *m_doledbKey; void *m_state; void (*m_callback)(void *state); // . the one that was just indexed // . Msg7.cpp uses this to see what docid the injected doc got so it // can forward it to external program long long getLastDocId ( ); // delete m_msg14[i], decrement m_numSpiders, m_maxUsed void cleanUp ( long i ); // registers sleep callback iff not already registered void doSleep ( ) ; bool indexedDoc ( class XmlDoc *doc ); // are we registered for sleep callbacks bool m_isRegistered; long m_numSpidersOut; // for spidering/parsing/indexing a url(s) class XmlDoc *m_docs [ MAX_SPIDERS ]; // . this is "i" where m_msg14[i] is the highest m_msg14 in use // . we use it to limit our scanning to the first "i" m_msg14's long m_maxUsed; // . list for getting next url(s) to spider RdbList m_list; // for getting RdbLists Msg5 m_msg5; class SpiderColl *m_sc; // used to avoid calling getRec() twice! //bool m_gettingList0; long m_outstanding1; bool m_gettingDoledbList; HashTableX m_lockTable; // save on msg12 lookups! keep somewhat local... RdbCache m_lockCache; //bool m_gettingLocks; // for round robining in SpiderLoop::doleUrls(), etc. long m_cri; long long m_doleStart; long m_processed; }; extern class SpiderLoop g_spiderLoop; void clearUfnTable ( ) ; long getUrlFilterNum ( class SpiderRequest *sreq , class SpiderReply *srep , long nowGlobal , bool isForMsg20 , long niceness , class CollectionRec *cr , bool isOutlink , // = false , HashTableX *quotaTable );//= NULL ) ; #endif
[ "masanori.ogino@gmail.com" ]
masanori.ogino@gmail.com
074969dd07cb25669ac1b95fc37176a4c08ecfc9
a0f0efaaaf69d6ccdc2a91596db29f04025f122c
/install/pnp_msgs/include/pnp_msgs/PNPConditionRequest.h
45da55705fb3a2fce47329a8174d417aa26b0b27
[]
no_license
chiuhandsome/ros_ws_test-git
75da2723154c0dadbcec8d7b3b1f3f8b49aa5cd6
619909130c23927ccc902faa3ff6d04ae0f0fba9
refs/heads/master
2022-12-24T05:45:43.845717
2020-09-22T10:12:54
2020-09-22T10:12:54
297,582,735
0
0
null
null
null
null
UTF-8
C++
false
false
5,093
h
// Generated by gencpp from file pnp_msgs/PNPConditionRequest.msg // DO NOT EDIT! #ifndef PNP_MSGS_MESSAGE_PNPCONDITIONREQUEST_H #define PNP_MSGS_MESSAGE_PNPCONDITIONREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace pnp_msgs { template <class ContainerAllocator> struct PNPConditionRequest_ { typedef PNPConditionRequest_<ContainerAllocator> Type; PNPConditionRequest_() : cond() { } PNPConditionRequest_(const ContainerAllocator& _alloc) : cond(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _cond_type; _cond_type cond; typedef boost::shared_ptr< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> const> ConstPtr; }; // struct PNPConditionRequest_ typedef ::pnp_msgs::PNPConditionRequest_<std::allocator<void> > PNPConditionRequest; typedef boost::shared_ptr< ::pnp_msgs::PNPConditionRequest > PNPConditionRequestPtr; typedef boost::shared_ptr< ::pnp_msgs::PNPConditionRequest const> PNPConditionRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> >::stream(s, "", v); return s; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator==(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator1> & lhs, const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator2> & rhs) { return lhs.cond == rhs.cond; } template<typename ContainerAllocator1, typename ContainerAllocator2> bool operator!=(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator1> & lhs, const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator2> & rhs) { return !(lhs == rhs); } } // namespace pnp_msgs namespace ros { namespace message_traits { template <class ContainerAllocator> struct IsFixedSize< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { static const char* value() { return "ae73c3f52927beed1a1deae4df67effb"; } static const char* value(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xae73c3f52927beedULL; static const uint64_t static_value2 = 0x1a1deae4df67effbULL; }; template<class ContainerAllocator> struct DataType< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { static const char* value() { return "pnp_msgs/PNPConditionRequest"; } static const char* value(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { static const char* value() { return "string cond\n" ; } static const char* value(const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.cond); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct PNPConditionRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::pnp_msgs::PNPConditionRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::pnp_msgs::PNPConditionRequest_<ContainerAllocator>& v) { s << indent << "cond: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.cond); } }; } // namespace message_operations } // namespace ros #endif // PNP_MSGS_MESSAGE_PNPCONDITIONREQUEST_H
[ "chiuhandsome1966@gmail.com" ]
chiuhandsome1966@gmail.com
9843333381e8b78b55bf780d8ecf94aace2e9ccc
cc0b7d50a3c6e6b329aab5b0aa0a349580bddbdd
/constant/impp23/polyMesh/boundary
9463e5b708c4903bdb076b802d0a0a2dc0dc1ffa
[]
no_license
AndrewLindsay/OpenFoamFieldJoint
32eede3593516b550358673a01b7b442f69eb706
7940373dcc021225f2a7ff88e850a1dd51c62e36
refs/heads/master
2020-09-25T16:59:18.478368
2019-12-05T08:16:14
2019-12-05T08:16:14
226,048,923
0
0
null
null
null
null
UTF-8
C++
false
false
2,122
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1906 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class polyBoundaryMesh; location "constant/impp23/polyMesh"; object boundary; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // 6 ( front { type wedge; inGroups 1(wedge); nFaces 2500; startFace 4900; } back { type wedge; inGroups 1(wedge); nFaces 2500; startFace 7400; } wedgeright { type patch; nFaces 50; startFace 9900; } impp23_to_adh19 { type mappedWall; inGroups 1(wall); nFaces 50; startFace 9950; sampleMode nearestPatchFace; sampleRegion adh19; samplePatch adh19_to_impp23; } impp23_to_pps22 { type mappedWall; inGroups 1(wall); nFaces 50; startFace 10000; sampleMode nearestPatchFace; sampleRegion pps22; samplePatch pps22_to_impp23; } impp23_to_impp27 { type mappedWall; inGroups 1(wall); nFaces 50; startFace 10050; sampleMode nearestPatchFace; sampleRegion impp27; samplePatch impp27_to_impp23; } ) // ************************************************************************* //
[ "andrew.lindsay@westnet.com.au" ]
andrew.lindsay@westnet.com.au
a65f1a5bfb772a4a4b3da4486e77663f3749efff
406c354fac53f5bad5eda5fcf2d4dedbaa67340a
/Source/ColorPickerTest419/NativeWidgetHostColorPicker.h
bf6dc7752d261b9e9a000fdc71b26c3a6e7c92e9
[]
no_license
HSeo/ColorPickerTest419
920b518d170211deac83552f44e31578e86ce007
af6ade6032d56cdeb59102e7f4cae579fef2ab3d
refs/heads/master
2020-04-20T04:39:43.535925
2019-03-02T07:29:55
2019-03-02T07:29:55
168,634,448
3
2
null
null
null
null
UTF-8
C++
false
false
546
h
#pragma once #include "CoreMinimal.h" #include "Components/NativeWidgetHost.h" #include "NativeWidgetHostColorPicker.generated.h" class SColorPicker; UCLASS() class COLORPICKERTEST419_API UNativeWidgetHostColorPicker : public UNativeWidgetHost { GENERATED_BODY() public: UNativeWidgetHostColorPicker(const FObjectInitializer& ObjectInitializer); virtual void ReleaseSlateResources(bool bReleaseChildren) override; protected: virtual TSharedRef<SWidget> RebuildWidget() override; private: TSharedPtr<SColorPicker> color_picker_; };
[ "seo@sciement.com" ]
seo@sciement.com
f39b3eb935a5defcde6d8572a443ab49ced81265
b8376621d63394958a7e9535fc7741ac8b5c3bdc
/lib/lib_mech/src/server/AqServer/AqCentral/AqCentral.cpp
ec94ec3bde6681a7cede8fa66875041b16852c61
[]
no_license
15831944/job_mobile
4f1b9dad21cb7866a35a86d2d86e79b080fb8102
ebdf33d006025a682e9f2dbb670b23d5e3acb285
refs/heads/master
2021-12-02T10:58:20.932641
2013-01-09T05:20:33
2013-01-09T05:20:33
null
0
0
null
null
null
null
UHC
C++
false
false
1,776
cpp
// AqCentral.cpp : DLL 응용 프로그램을 위해 내보낸 함수를 정의합니다. // #include "stdafx.h" #include "AqCentral.h" #include <boost/bind.hpp> #include "csv_loader.h" #include "../AqCommon/jXmlSaveManager.h" Aq_NetDLL* g_pjConsoleDLL=0; void _OnPacketSize_UsageInfo(tcstr szPlugIn,uint64 packet_size,tname1024_t info) { g_jAqCommon.OnPacketSize_UsageInfo(szPlugIn,packet_size); } extern "C" { AQCENTRAL_API void* jCreateInterface(jIE* pE) { init_common_AQ(); /* tfname_t szDir; Load_Common_CSV(szDir); //jFOR_EACH(pCM->m_Sys_LocalizingText.m_List , boost::bind(&Sys_LocalizingText::jDebugPrint,_1)); Sys_LocalizingText* pN = jCSV(Sys_LocalizingText).find(jS(we_are_fiend)); if(pN) { pN->jDebugPrint(); } else { GetjILog()->Warning( _T("Sys_LocalizingText : we_are_fiend : not found") ); } */ if(g_pjConsoleDLL) return g_pjConsoleDLL; g_pjConsoleDLL = new Aq_NetDLL(); nInterface::g_pjINet_OGS->RunMessageThread(); nInterface::g_pjINet_OGS->SetCallback_PacketSize_UsageInfo(_OnPacketSize_UsageInfo); return g_pjConsoleDLL; } AQCENTRAL_API void jDeleteInterface() { SAFE_DELETE(g_pjConsoleDLL); } AQCENTRAL_API acstr jGetModuleOwnerName() { return "icandoit"; } } bool Aq_NetDLL::ParseCmd(tcstr szCommand) { if( parent_t::ParseCmd(szCommand) ) return true; //여기에 코드를 추가하시오 if(!g_pCurrPlugIn) return false; return g_pCurrPlugIn->ParseCmd(szCommand); } bool Aq_NetDLL::Start(tcstr szNetConfigFile,tcstr szNetConfig_Name) { if(!parent_t::Start(szNetConfigFile,szNetConfig_Name)) return false; // 여기에 코드를 추가하시오 return true; } void Aq_NetDLL::End() { //여기에 코드를 추가하시오 g_jXmlSaveManager.Destory(); parent_t::End(); }
[ "whdnrfo@gmail.com" ]
whdnrfo@gmail.com
1c0abe3d770f5f4f87770204d64740edc628c4df
4fe6b129a2f415b22f1c8752169b56daf8551e23
/Aligner/TiltCalibrationPage3.cpp
6045d5e91e2c73d2e0b61452fece8d6b1d71566e
[]
no_license
Kingarne/Aligner308MK3
1821d6ce9a8cd6d3e6def31bb43cd0c37b43fe1e
04adc7e1ca1e97e2b4165c626dd73f095ad77c93
refs/heads/master
2023-08-31T05:48:52.441714
2023-08-21T13:14:32
2023-08-21T13:14:32
207,835,311
0
1
null
null
null
null
UTF-8
C++
false
false
2,221
cpp
// $Id: TiltCalibrationPage3.cpp,v 1.3 2014-07-15 13:22:33 riar Exp $ // // Copyright (C) Shill Reglerteknik AB 2002 #include "stdafx.h" #include "TiltCalibrationPage3.h" #include "CalibrationSheet.h" IMPLEMENT_DYNAMIC(TiltCalibrationPage3, CPropertyPage) TiltCalibrationPage3::TiltCalibrationPage3( void ) : CPropertyPage(TiltCalibrationPage3::IDD) { // Empty } TiltCalibrationPage3::~TiltCalibrationPage3( void ) { // Empty } void TiltCalibrationPage3::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange( pDX ) ; } BEGIN_MESSAGE_MAP(TiltCalibrationPage3, CPropertyPage) END_MESSAGE_MAP() BOOL TiltCalibrationPage3::OnSetActive( void ) { CalibrationSheet *pSheet = static_cast<CalibrationSheet *>(GetParent()) ; ASSERT(pSheet -> IsKindOf( RUNTIME_CLASS(CalibrationSheet) )) ; pSheet -> PlotConverted( 2 ) ; pSheet -> m_measurement = 2 ; pSheet -> SetWizardButtons( PSWIZB_BACK | PSWIZB_NEXT ) ; MoveDlgToRightSideOfApp(pSheet); inProgress = false; return __super::OnSetActive() ; } LRESULT TiltCalibrationPage3::OnWizardNext( void ) { if(inProgress) { inProgress = false; return CPropertyPage::OnWizardNext(); } CalibrationSheet *pSheet = static_cast<CalibrationSheet *>(GetParent()) ; ASSERT(pSheet -> IsKindOf( RUNTIME_CLASS(CalibrationSheet) )) ; inProgress = true; pSheet -> SetWizardButtons( 0 ) ; pSheet -> StartMeasurement() ; return -1 ; } BOOL TiltCalibrationPage3::OnQueryCancel( void ) { CalibrationSheet *pSheet = static_cast<CalibrationSheet *>(GetParent()) ; ASSERT(pSheet -> IsKindOf( RUNTIME_CLASS(CalibrationSheet) )) ; pSheet -> StopMeasurement() ; pSheet -> SetWizardButtons( PSWIZB_NEXT | PSWIZB_BACK ) ; return IDYES == ::AfxMessageBox( IDS_REALY_ABORT, MB_YESNO | MB_DEFBUTTON2 ) ; } LRESULT TiltCalibrationPage3::OnWizardBack( void ) { CalibrationSheet *pSheet = static_cast<CalibrationSheet *>(GetParent()) ; ASSERT(pSheet -> IsKindOf( RUNTIME_CLASS(CalibrationSheet) )) ; if (pSheet -> IsMeasuring()) { pSheet -> StopMeasurement() ; pSheet -> SetWizardButtons( PSWIZB_NEXT | PSWIZB_BACK ) ; return -1 ; } return IDYES != ::AfxMessageBox( IDS_REALY_BACK, MB_YESNO | MB_DEFBUTTON2 ) ; }
[ "riar@now.se" ]
riar@now.se
c5d6b437b939d10b8a7d314d0a600e0ba112a0b1
c955730b68bd4ba2d9255183cfef092bd1ef2524
/CPP/chocoland.cpp
3d37c55fa71d75fad26834c5d97b202e00ecf4cd
[]
no_license
Manvi07/Competitive-programming
b6e95c2e8bc9673d9e23e784c460d50ed3754ab1
7b59d89988667b115500482691b3ae89c397d753
refs/heads/master
2020-05-19T06:12:07.019076
2020-05-08T09:22:16
2020-05-08T09:22:16
184,867,764
1
0
null
null
null
null
UTF-8
C++
false
false
280
cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,k,s; cin>>n>>k>>s; int d=s-s/7;int b=0; if(k*s>n*d)b=-1; else { while(1){ b++; if(b*n>=k*s) break;} } cout<<b<<endl; } }
[ "b17092@students.iitmandi.ac.in" ]
b17092@students.iitmandi.ac.in
1737c71e235f2108e03e5c40eab1eceadfae0f20
d4c0b7fd40ddd8be34cb092cb7fd173f381dba65
/ZeroBiasStudies/Utilities/PlottingTools/interface/PlottingTools.h
8323253147a587bcd5cf8897adee88676fa687aa
[]
no_license
ForwardGroupBrazil/ForwardAnalysis
8dceaacb1707c0769296f3c7b2e37c15a4a30ff7
5572335f19d1e0d385f73945e55e42fb4ed49761
refs/heads/master
2021-01-16T01:02:02.286181
2013-09-12T20:54:02
2013-09-12T20:54:02
12,787,581
1
4
null
null
null
null
UTF-8
C++
false
false
3,199
h
#ifndef UtilitiesPlottingTools_PlottingTools_h #define UtilitiesPlottingTools_PlottingTools_h class TFile; class TDirectory; #include "TH1F.h" #include <vector> #include <string> #include <map> #include <exception> class DefaultNorm{ public: /*DefaultNorm() {} double GetNormFactor(const TH1F* hist) {return hist->GetSumOfWeights();} double operator()(const TH1F* hist) {return GetNormFactor(hist);}*/ static double GetNorm(const TH1F* hist) {return hist->GetSumOfWeights();} private: }; class ConstNorm{ public: /*ConstNorm(double norm=1.):normalization_(norm) {} double GetNormFactor(const TH1F* hist) {return normalization_;} double operator()(const TH1F* hist) {return GetNormFactor(hist);}*/ static double GetNorm(const TH1F* hist) {return normalization;} private: //double normalization_; static double normalization; }; class NumberEntriesNorm{ public: /*NumberEntriesNorm() {} double operator()(const TH1F* hist) {return hist->GetSumOfWeights()/hist->GetEntries();}*/ static double GetNorm(const TH1F* hist) {return hist->GetSumOfWeights()/hist->GetEntries();} private: }; /*template <typename T> class Sum{ public: typedef T value_type; Sum(T const& init): sum_(init) {} void operator()(T const& x) {sum_ += x;} T const value() const {return sum_;} private: T sum_; }; template <typename T> class Mult{ public: typedef T value_type; Mult(T const& x): val_(x) {} T const operator()(T const& x) {return x*val_;} private: T val_; };*/ class RootException: public std::exception{ public: RootException(std::string const& msg = ""): message_(msg) {} ~RootException() throw() {} virtual char const* what() const throw() { return message_.c_str(); } private: std::string message_; }; //TH1F* getHisto(TFile*, const std::string&); TH1F* getHisto(TDirectory const*, std::string const&); void scaleHisto(TH1F* histo, double scale = 1., int line = 1, int color = 1, int rebin = 1); TH1F* rebinHisto(TH1F const* histo, std::vector<int> const& groups); std::map<std::string,std::vector<std::string> > buildVarMap(const std::vector<std::string>& varNames,const std::vector<std::string>& triggerBits); template<typename KeyType,typename ValueType> std::map<KeyType,ValueType> makeMap(const std::vector<KeyType>& keys,const std::vector<ValueType>& values){ std::map<KeyType,ValueType> res; typename std::vector<KeyType>::const_iterator key = keys.begin(); typename std::vector<ValueType>::const_iterator value = values.begin(); typename std::vector<KeyType>::const_iterator keys_end = keys.end(); typename std::vector<ValueType>::const_iterator values_end = values.end(); for(; key != keys_end && value != values_end; ++key,++value) res[*key] = *value; return res; } void plot(std::map<std::string,std::vector<std::string> >& variablesMap, TDirectory* dir, bool Norm = false); //template <class NormPolicy> //void plot(std::vector<std::string>& variables, std::vector<std::pair<std::string,TDirectory*> >& directories, NormPolicy& norm); #endif
[ "" ]
25963bc5f5842ffdd2909a8a32d50d5bb882cd46
da510e8caaa2791a1f7f11eb207f10fbe620cb0d
/games/src/Ghost.cpp
5ff9679f58b377fe995a3c16866dc54bdbc4d660
[]
no_license
LeBenki/arcade
d19d76a7d0b66d0f69994061b7f945c7d5acdd8e
0360b8ec80bb1fd85793a83355b9c89a1e981ea5
refs/heads/master
2020-03-24T03:42:30.612168
2018-08-02T11:39:41
2018-08-02T11:39:41
142,429,800
1
0
null
null
null
null
UTF-8
C++
false
false
1,571
cpp
/* ** EPITECH PROJECT, 2018 ** Ghost.cpp ** File description: ** Ghost entity class file */ #include "Ghost.hpp" arc::Ghost::Ghost(const arc::pos_t &pos, const unsigned int level, const unsigned int id) : arc::APacmanEntity("Ghost" + std::to_string(id % 4 + 1)) { _pos = {(float)(pos.x + 0.5), (float)(pos.y + 0.5)}; _health = 1; _speed = GHOSTSPEED * (1 + level * 0.5); _id = id; } void arc::Ghost::findPath(std::vector<std::vector<int>> distances, const std::vector<std::string> &map, const bool mode) { Direction target = DIR_UNDEFINED; int dist = -1; posf_t posTo; for (int i = 1; i < 5; i++) { posTo = getNextTile(_pos, (arc::Direction)i, map); if (_health == 0 && _distances[posTo.y][posTo.x] != -2 && (dist == -1 || _distances[posTo.y][posTo.x] < dist)) { target = (Direction)i; dist = _distances[posTo.y][posTo.x]; } else if (_health > 0 && distances[posTo.y][posTo.x] != -2 && (dist == -1 || (mode) ? distances[posTo.y][posTo.x] > dist : distances[posTo.y][posTo.x] < dist)) { target = (arc::Direction)i; dist = distances[posTo.y][posTo.x]; } } _direction = target; } void arc::Ghost::updateAnimation(const std::vector<std::string> &map) { std::chrono::milliseconds now = std::chrono::duration_cast< std::chrono::milliseconds>(std::chrono::system_clock::now() .time_since_epoch()); (void)map; if (now.count() - _lastUpdate.count() > ANIMATION_FREQUENCY / (_speed / GHOSTSPEED)) { _lastUpdate = now; _animationStatus = _animationStatus + 1 > 1 ? 0 : _animationStatus + 1; } }
[ "lucas.benkemoun@epitech.Eu" ]
lucas.benkemoun@epitech.Eu
b7808a2833e69a7500da4523732a15eb3d10600f
a6b7e6ff776bf577c7f63926edf3b236ec2ec917
/Protótipos_ESP8266_IDE-Arduino/ANDRE_SINAL/ANDRE_SINAL.ino
b042dff4f36b1f0f12e5f35faa626446cf30eb6d
[ "MIT" ]
permissive
francenylson/Robotica_ESP8266
a4f51cd0b2c322f8d52380f210cd7ee9f250ba25
882568b2656d319144aa19b3f34a0caf3c132b22
refs/heads/master
2022-12-05T11:14:10.715099
2020-08-28T15:36:43
2020-08-28T15:36:43
291,081,432
0
0
null
null
null
null
UTF-8
C++
false
false
2,690
ino
#define led_1 D0 //verde direito #define led_2 D1 //amarelo direito #define led_3 D2 //vermelho direito #define led_4 D3 //azul #define led_5 D4 //azul #define led_6 D5 //azul #define led_7 D6 //azul #define led_8 D7 //azul #define led_9 D8 void setup() { pinMode(led_1, OUTPUT); pinMode(led_2, OUTPUT); pinMode(led_3, OUTPUT); pinMode(led_4, OUTPUT); pinMode(led_5, OUTPUT); pinMode(led_6, OUTPUT); pinMode(led_7, OUTPUT); pinMode(led_8, OUTPUT); pinMode(led_9, OUTPUT); } void loop() { digitalWrite(led_1, HIGH); digitalWrite(led_2, LOW); digitalWrite(led_3, LOW); digitalWrite(led_4, HIGH); digitalWrite(led_5, LOW); digitalWrite(led_6, LOW); digitalWrite(led_7, HIGH); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(3000); digitalWrite(led_1, HIGH); digitalWrite(led_2, LOW); digitalWrite(led_3, LOW); digitalWrite(led_4, LOW); digitalWrite(led_5, HIGH); digitalWrite(led_6, LOW); digitalWrite(led_7, HIGH); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, LOW); digitalWrite(led_3, HIGH); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, LOW); digitalWrite(led_8, HIGH); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, LOW); digitalWrite(led_3, HIGH); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, LOW); digitalWrite(led_8, HIGH); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, HIGH); digitalWrite(led_3, LOW); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, HIGH); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, HIGH); digitalWrite(led_2, LOW); digitalWrite(led_3, LOW); digitalWrite(led_4, HIGH); digitalWrite(led_5, LOW); digitalWrite(led_6, LOW); digitalWrite(led_7, HIGH); digitalWrite(led_8, HIGH); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, HIGH); digitalWrite(led_3, LOW); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, LOW); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(2000); digitalWrite(led_1, LOW); digitalWrite(led_2, HIGH); digitalWrite(led_3, LOW); digitalWrite(led_4, LOW); digitalWrite(led_5, LOW); digitalWrite(led_6, HIGH); digitalWrite(led_7, LOW); digitalWrite(led_8, LOW); digitalWrite(led_9, LOW); delay(2000); }
[ "francenylson@gmail.com" ]
francenylson@gmail.com
4affec17d1d45ea635b2b85555fd49a59c51f24a
376b40b62f996ecc6665de0e0bc9735bf6a18268
/src/core/buffer/AsyncFrameBuffer.h
c028562f96f434be4b1b6046c0298e12884d7c6f
[ "MIT" ]
permissive
PearCoding/PearRay
f687863b3bc722240997fb0b3d22e5032d91b7b8
95f065adb20fc6202dfa40140d0308fc605dc440
refs/heads/master
2022-05-02T01:01:28.462545
2022-04-13T09:52:16
2022-04-13T09:52:16
45,111,096
20
0
MIT
2020-06-22T11:32:21
2015-10-28T12:33:36
C++
UTF-8
C++
false
false
2,414
h
#pragma once #include "FrameBuffer.h" #include <vector> namespace PR { template <typename T> class AsyncFrameBuffer { PR_CLASS_NON_COPYABLE(AsyncFrameBuffer); public: inline AsyncFrameBuffer(Size1i channels, const Size2i& size, const T& clear_value = T(), bool never_clear = false) : mFrameBuffer(channels, size, clear_value, never_clear) , mLocks(size) { } inline ~AsyncFrameBuffer() { } inline const Size2i& size() const { return mFrameBuffer.size(); } inline Size1i width() const { return mFrameBuffer.width(); } inline Size1i widthPitch() const { return mFrameBuffer.widthPitch(); } inline Size1i widthBytePitch() const { return mFrameBuffer.widthBytePitch(); } inline Size1i height() const { return mFrameBuffer.height(); } inline Size1i heightPitch() const { return mFrameBuffer.heightPitch(); } inline Size1i heightBytePitch() const { return mFrameBuffer.heightBytePitch(); } inline Size1i channels() const { return mFrameBuffer.channels(); } inline Size1i channelPitch() const { return mFrameBuffer.channelPitch(); } inline Size1i channelBytePitch() const { return mFrameBuffer.channelBytePitch(); } inline void setNeverClear(bool b) { mFrameBuffer.setNeverClear(b); } inline bool isNeverCleared() const { return mFrameBuffer.isNeverCleared(); } inline void setFragment(const Point2i& p, Size1i channel, const T& v) { mLocks.lock(p); mFrameBuffer.setFragment(p, channel, v); mLocks.unlock(p); } inline T getFragment(const Point2i& p, Size1i channel) const { mLocks.lock(p); const T ret = mFrameBuffer.getFragment(p, channel); mLocks.unlock(p); return ret; } inline void setFragment(Size1i pixelindex, Size1i channel, const T& v) { mLocks.lock(p); mFrameBuffer.setFragment(pixelindex, channel, v); mLocks.unlock(p); } inline T getFragment(Size1i pixelindex, Size1i channel = 0) const { mLocks.lock(p); const T ret = mFrameBuffer.getFragment(p, channel); mLocks.unlock(p); return ret; } inline const T* ptr() const { return mData.data(); } inline T* ptr() { return mData.data(); } inline void clearUnsafe(bool force = false) { mFrameBuffer.clear(force); } inline void fillUnsafe(const T& v) { mFrameBuffer.fill(v); } private: FrameBuffer<T> mFrameBuffer; PixelLock mLocks; }; typedef AsyncFrameBuffer<float> AsyncFrameBufferFloat; typedef AsyncFrameBuffer<uint32> AsyncFrameBufferUInt32; } // namespace PR
[ "yazici@cg.uni-saarland.de" ]
yazici@cg.uni-saarland.de
e86216202f0dcf0b5150326077e1bc5a2ea3657c
3a1fa284cccc1ee84aea82d109362c7f749dcb0c
/engine/enginecode/include/independent/systems/systems/resourceManager.h
09f0feaf64b7ea706eaec892c15dda3472300c86
[]
no_license
DanBullin/Owl-Engine
8007ebccaf31f4af9e73c9015f25c3be1fcfad80
d67c2a0c76458c6566dfd69e9c8d81153a7ec12c
refs/heads/main
2023-04-24T19:24:47.367794
2021-05-17T07:18:57
2021-05-17T07:18:57
367,107,845
0
0
null
null
null
null
UTF-8
C++
false
false
5,060
h
/*! \file resourceManager.h * * \brief A resource manager containing all the resources that are currently loaded. All resources are stored in a single map containing a key which is a unique string. * * \author Daniel Bullin * */ #ifndef RESOURCEMANAGER_H #define RESOURCEMANAGER_H #include <json.hpp> #include "independent/systems/system.h" #include "independent/core/common.h" #include "independent/systems/components/resource.h" #include "independent/rendering/geometry/vertexBuffer.h" #include "independent/rendering/geometry/indexBuffer.h" #include "independent/rendering/geometry/vertexArray.h" #include "independent/rendering/geometry/indirectBuffer.h" #include "independent/rendering/uniformBuffer.h" #include "independent/rendering/frameBuffer.h" #include "independent/rendering/shaders/shaderProgram.h" #include "independent/rendering/textures/texture.h" #include "independent/rendering/textures/subTexture.h" #include "independent/rendering/geometry/model3D.h" #include "independent/rendering/materials/material.h" namespace OwlEngine { namespace Config { /*! \enum ConfigData * \brief The different types of configurable data */ enum ConfigData { MaxSubTexturesPerMaterial = 0, VertexCapacity3D = 1, IndexCapacity3D = 2, BatchCapacity3D = 3, BatchCapacity2D = 4, MaxLayersPerScene = 5, MaxRenderPassesPerScene = 6, MaxLightsPerDraw = 7, UseBloom = 8, BloomBlurFactor = 9, PrintResourcesInDestructor = 10, PrintOpenGLDebugMessages = 11, ShowColliders = 12, ApplyFog = 13 }; } /*! \class ResourceManager * \brief A resource manager managing resources */ class ResourceManager : public System { private: static bool s_enabled; //!< Is this system enabled static std::map<std::string, Resource*> s_loadedResources; //!< A list of loaded resources static std::vector<uint32_t> s_configValues; //!< The config values static std::string s_resBeingLoaded; //!< The name of the resource being loaded public: ResourceManager(); //!< Constructor ~ResourceManager(); //!< Destructor void start() override; //!< Start the system void stop() override; //!< Stop the system static const bool resourceExists(const std::string& resourceName); //!< Check if the resource name exists static void registerResource(const std::string& resourceName, Resource* resource); //!< Register a resource static void destroyResource(const std::string& resourceName = ""); //!< Destroy a resource by name or all of them static void loadNTResources(); //!< Load non-threaded resources static void loadTResources(); //!< Load threaded resources template<typename T> static T* getResource(const std::string& resourceName); //!< Get a resource by name template<typename T> static std::vector<T*> getResourcesOfType(const ResourceType type); //!< Get all resources of a certain type static std::map<std::string, Resource*>& getResources(); //!< Get a list of all resources static std::string getCurrentDirectory(); //!< Returns the current directory static std::string getContents(const std::string& filePath); //!< Return the file contents static std::string getLineFromString(const std::string& stringContents, const uint32_t lineIndex); //!< Return the contents on line static nlohmann::json getJSON(const std::string& filePath); //!< Load the contents of a file into a JSON object and return the object static const uint32_t getConfigValue(const Config::ConfigData data); //!< Get a config value static void setConfigValue(const Config::ConfigData data, const uint32_t value); //!< Set a config value static FrameBuffer* getDefaultFrameBuffer(); //!< Get the default framebuffer static const std::string& getResBeingLoaded(); //!< Get the name of the resource being loaded static void setResBeingLoaded(const std::string& name); //!< Set the name of the resource being loaded static void printResourceManagerDetails(); //!< Print resource manager details static void printResourceDetails(const std::string& resourceName = ""); //!< Print resource details }; template<typename T> //! getResource() /*! \param resourceName a const std::string& - The name of the resource \return a T* - The resource in type T */ static T* ResourceManager::getResource(const std::string& resourceName) { // Check if resource exists by name // Cast and return it if it does, otherwise return nullptr // No type checking, quite frankly its your fault if you get it wrong if (resourceExists(resourceName)) return static_cast<T*>(s_loadedResources[resourceName]); else return nullptr; } template<typename T> //! getResourcesOfType() /*! \param type a const ResourceType - The resource type \return a std::vector<T*> - The list of resources of type T */ static std::vector<T*> ResourceManager::getResourcesOfType(const ResourceType type) { std::vector<T*> resources; for (auto& res : s_loadedResources) { if (res.second) { if (res.second->getType() == type) resources.emplace_back(static_cast<T*>(res.second)); } } return resources; } } #endif
[ "danbullin@gmail.com" ]
danbullin@gmail.com
86b06258526acab138213f35e6eadd055b1e2769
dccd1058e723b6617148824dc0243dbec4c9bd48
/atcoder/arc036/b.cpp
7d80832839e6ae2d5b8a82f4540dd8f4b5781436
[]
no_license
imulan/procon
488e49de3bcbab36c624290cf9e370abfc8735bf
2a86f47614fe0c34e403ffb35108705522785092
refs/heads/master
2021-05-22T09:24:19.691191
2021-01-02T14:27:13
2021-01-02T14:27:13
46,834,567
7
1
null
null
null
null
UTF-8
C++
false
false
836
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,n) for(i=0;i<n;++i) #define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr) #define mp make_pair #define pb push_back #define fi first #define sc second int main(int argc, char const *argv[]) { int i; int n; cin >>n; std::vector<int> h(n); rep(i,n) scanf(" %d",&h[i]); std::vector<int> v; v.pb(0); int now=0; rep(i,n-1){ if(h[i+1]-h[i]>0){ if(now<0){ v.pb(now); now=0; } ++now; } else{ if(now>0){ v.pb(now); now=0; } --now; } } if(now!=0) v.pb(now); v.pb(0); int ans=0; rep(i,(int)v.size()-1){ if(v[i]>=0&&v[i+1]<=0){ ans=max(ans,v[i]-v[i+1]+1); } } std::cout << ans << std::endl; return 0; }
[ "k0223.teru@gmail.com" ]
k0223.teru@gmail.com
cf96835845de5aeaf4cf803b74175b0ce93499fa
aaf052bb772a863f86512724373f51a2b6e39576
/include/smp/components/samplers/theta_star_gaussian.hpp
b267b9483ac91e6dcf4bdc3bd6f06ed57ed893f1
[ "BSD-2-Clause" ]
permissive
HsiaoRay/proxemics_anytimerrts
0cec5c1736ebd1df38319e24bf22ab1dd55475e1
6d1c76e04ace18d53af91c3bfcfc9eddbb9fec60
refs/heads/master
2020-07-07T13:35:44.064098
2016-06-16T15:13:48
2016-06-16T15:13:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,667
hpp
#ifndef _SMP_SAMPLER_GAUSS_HPP_ #define _SMP_SAMPLER_GAUSS_HPP_ #include <iostream> #include <cstdlib> #include <smp/components/samplers/theta_star_gaussian.h> #include <smp/components/samplers/base.hpp> #include "eigenmultivariatenormal.cpp" template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sm_update_insert_vertex (vertex_t *vertex_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sm_update_insert_edge (edge_t *edge_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sm_update_delete_vertex (vertex_t *vertex_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sm_update_delete_edge (edge_t *edge_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::theta_star_gaussian() { // Initialize the sampling distribution support. for (int i = 0; i < NUM_DIMENSIONS; i++) { support.center[i] = 0.0; support.size[i] = 1.0; } } template< class typeparams, int NUM_DIMENSIONS > smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::~theta_star_gaussian () { } /// Sample function for a Circle Region template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::sample (state_t **state_sample_out) { // Sampling by Using Multivariate Gaussians Eigen::Vector2d mean; Eigen::Matrix2d covar; Eigen::Vector2d ns; double sigmaxi,sigmayi; if (NUM_DIMENSIONS <= 0) return 0; state_t *state_new = new state_t; mean << support.center[0],support.center[1]; sigmaxi=1; sigmayi=1; Eigen::Matrix2d rot ; rot=Eigen::Rotation2Dd(0).matrix(); covar = rot*Eigen::DiagonalMatrix<double,2,2>(sigmaxi,sigmayi)*rot.transpose(); EigenMultivariateNormal<double,2> *normX = new EigenMultivariateNormal<double,2>(mean,covar); (*normX).reseed(rand()+100*std::time(0)*rand()+std::time(0)); normX->nextSample(ns); // cout<<"DEBUG: sample --x,y--: -- "<<ns(0)<<","<<ns(1)<<endl; (*state_new)[0]=ns(0); (*state_new)[1]=ns(1); (*state_new)[2]=support.ang_range*rand()/(RAND_MAX + 1.0)-support.ang_range/2+support.center[2]; *state_sample_out = state_new; return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::theta_star_gaussian<typeparams,NUM_DIMENSIONS> ::set_support (region_t support_in) { support = support_in; return 1; } #endif
[ "charlyhuang@ira.e.ntu.edu.tw" ]
charlyhuang@ira.e.ntu.edu.tw
d448f34cb86d5a1cd96b276e295b6f59924de2fc
e549cbc5938a9404d781d2b9762b0b08737f8312
/Задача 6/Задача 6/Задача 6.cpp
2d14736008654b6badbde108e90862726317b242
[]
no_license
babikov02/Laborator-4
7b1cf4ae089a2a1c65a12c9edfe92d559db78497
67679bf1fa4b8e54875b3bb49713070d401f10f8
refs/heads/master
2022-12-31T15:35:15.361848
2020-10-18T12:12:06
2020-10-18T12:12:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,256
cpp
// Задача 6.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> using namespace std; #include <cmath> int main() { setlocale(LC_ALL, "rus"); float a, b, c; cout << "Введите a: "; cin >> a; cout << "Введите b: "; cin >> b; cout << "Введите c: "; cin >> c; float D = b * b - 4 * a * c; cout << "D = "; cout << D << endl; if (D == 0) { float x = -b / (2 * a); cout << "х = "; cout << x << endl; } else if (D > 0) { float x1 = (-b + sqrt(D)) / (2 * a); float x2 = (-b - sqrt(D)) / (2 * a); cout << "х1 = "; cout << x1 << endl; cout << "х2 = "; cout << x2 << endl; } else { cout << "Корней нет!" << endl; } } // Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки" // Отладка программы: F5 или меню "Отладка" > "Запустить отладку" // Советы по началу работы // 1. В окне обозревателя решений можно добавлять файлы и управлять ими. // 2. В окне Team Explorer можно подключиться к системе управления версиями. // 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения. // 4. В окне "Список ошибок" можно просматривать ошибки. // 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода. // 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
[ "noreply@github.com" ]
babikov02.noreply@github.com
acca10ddff67ddc4be42297ec92c4dbcec7b7d31
d57a25c0dd59b71801e7b9633dcb85029b12bb36
/include/dll/generators/inmemory_data_generator.hpp
5414ee048543d419bc32365d1aa81a94b201c644
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
xinsuinizhuan/dll
c391a81b53b790484d0b7abcad5c401af61605b1
df1fcae4bdf14fbc73290214cc6dbf4578ac1efe
refs/heads/master
2022-12-12T15:26:53.208901
2020-09-04T16:32:04
2020-09-04T16:32:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,721
hpp
//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Implementation of an in-memory data generator */ #pragma once #include <atomic> #include <thread> namespace dll { /*! * \brief a in-memory data generator */ template <typename Iterator, typename LIterator, typename Desc, typename Enable = void> struct inmemory_data_generator; /*! * \copydoc inmemory_data_generator */ template <typename Iterator, typename LIterator, typename Desc> struct inmemory_data_generator<Iterator, LIterator, Desc, std::enable_if_t<!is_augmented<Desc>>> { using desc = Desc; ///< The generator descriptor using weight = etl::value_t<typename std::iterator_traits<Iterator>::value_type>; ///< The data type using data_cache_helper_t = cache_helper<Desc, Iterator>; ///< The helper for the data cache using label_cache_helper_t = label_cache_helper<Desc, weight, LIterator>; ///< The helper for the label cache using data_cache_type = typename data_cache_helper_t::cache_type; ///< The type of the data cache using label_cache_type = typename label_cache_helper_t::cache_type; ///< The type of the label cache static constexpr bool dll_generator = true; ///< Simple flag to indicate that the class is a DLL generator static inline constexpr size_t batch_size = desc::BatchSize; ///< The size of the generated batches data_cache_type input_cache; ///< The input cache label_cache_type label_cache; ///< The label cache size_t current = 0; ///< The current index bool is_safe = false; ///< Indicates if the generator is safe to reclaim memory from template <typename Input, typename Label> inmemory_data_generator(const Input& input, const Label& label, size_t n, size_t n_classes){ // Initialize both caches for enough elements data_cache_helper_t::init(n, &input, input_cache); label_cache_helper_t::init(n, n_classes, &label, label_cache); } /*! * \brief Construct an inmemory data generator */ inmemory_data_generator(Iterator first, Iterator last, LIterator lfirst, [[maybe_unused]] LIterator llast, size_t n_classes){ const size_t n = std::distance(first, last); data_cache_helper_t::init(n, first, input_cache); label_cache_helper_t::init(n, n_classes, lfirst, label_cache); // Fill the cache size_t i = 0; while (first != last) { input_cache(i) = *first; label_cache_helper_t::set(i, lfirst, label_cache); ++i; ++first; ++lfirst; } // Transform if necessary pre_scaler<desc>::transform_all(input_cache); pre_normalizer<desc>::transform_all(input_cache); pre_binarizer<desc>::transform_all(input_cache); // In case of auto-encoders, the label images also need to be transformed if constexpr (desc::AutoEncoder) { pre_scaler<desc>::transform_all(label_cache); pre_normalizer<desc>::transform_all(label_cache); pre_binarizer<desc>::transform_all(label_cache); } } inmemory_data_generator(const inmemory_data_generator& rhs) = delete; inmemory_data_generator operator=(const inmemory_data_generator& rhs) = delete; inmemory_data_generator(inmemory_data_generator&& rhs) = delete; inmemory_data_generator operator=(inmemory_data_generator&& rhs) = delete; /*! * \brief Display a description of the generator in the given stream * \param stream The stream to print to * \return stream */ std::ostream& display(std::ostream& stream) const { stream << "In-Memory Data Generator" << std::endl; stream << " Size: " << size() << std::endl; stream << " Batches: " << batches() << std::endl; if (augmented_size() != size()) { stream << " Augmented Size: " << augmented_size() << std::endl; } return stream; } /*! * \brief Display a description of the generator in the standard output. */ void display() const { display(std::cout); } /*! * \brief Indicates that it is safe to destroy the memory of the generator * when not used by the pretraining phase */ void set_safe() { is_safe = true; } /*! * \brier Clear the memory of the generator. * * This is only done if the generator is marked as safe it is safe. */ void clear() { if (is_safe) { input_cache.clear(); label_cache.clear(); } } /*! * brief Sets the generator in test mode */ void set_test() { // Nothing to do } /*! * brief Sets the generator in train mode */ void set_train() { // Nothing to do } /*! * \brief Reset the generator to the beginning */ void reset() { current = 0; } /*! * \brief Reset the generator and shuffle the order of samples */ void reset_shuffle() { current = 0; shuffle(); } /*! * \brief Shuffle the order of the samples. * * This should only be done when the generator is at the beginning. */ void shuffle() { cpp_assert(!current, "Shuffle should only be performed on start of generation"); etl::parallel_shuffle(input_cache, label_cache, dll::rand_engine()); } /*! * \brief Prepare the dataset for an epoch */ void prepare_epoch(){ input_cache.ensure_gpu_up_to_date(); label_cache.ensure_gpu_up_to_date(); } /*! * \brief Return the index of the current batch in the generation * \return The current batch index */ size_t current_batch() const { return current / batch_size; } /*! * \brief Returns the number of elements in the generator * \return The number of elements in the generator */ size_t size() const { return etl::dim<0>(input_cache); } /*! * \brief Returns the augmented number of elements in the generator. * * This number may be an estimate, depending on which augmentation * techniques are enabled. * * \return The augmented number of elements in the generator */ size_t augmented_size() const { return etl::dim<0>(input_cache); } /*! * \brief Returns the number of batches in the generator. * \return The number of batches in the generator */ size_t batches() const { return size() / batch_size + (size() % batch_size == 0 ? 0 : 1); } /*! * \brief Indicates if the generator has a next batch or not * \return true if the generator has a next batch, false otherwise */ bool has_next_batch() const { return current < size(); } /*! * \brief Moves to the next batch. * * This should only be called if the generator has a next batch. */ void next_batch() { current += batch_size; } /*! * \brief Returns the current data batch * \return a a batch of data. */ auto data_batch() const { return etl::slice(input_cache, current, std::min(current + batch_size, size())); } /*! * \brief Returns the current label batch * \return a a batch of label. */ auto label_batch() const { return etl::slice(label_cache, current, std::min(current + batch_size, size())); } /*! * \brief Set some part of the data to a new set of value * \param i The beginning at which to start storing the new data * \param input_batch An input batch */ template <typename Input> void set_data_batch(size_t i, Input&& input_batch) { etl::slice(input_cache, i, i + etl::dim<0>(input_batch)) = input_batch; } /*! * \brief Set some part of the labels to a new set of value * \param i The beginning at which to start storing the new data * \param input_batch A label batch */ template <typename Input> void set_label_batch(size_t i, Input&& input_batch) { etl::slice(label_cache, i, i + etl::dim<0>(input_batch)) = input_batch; } /*! * \brief Finalize the dataset if it was filled directly after having being prepared. */ void finalize_prepared_data() { pre_scaler<desc>::transform_all(input_cache); pre_normalizer<desc>::transform_all(input_cache); pre_binarizer<desc>::transform_all(input_cache); // In case of auto-encoders, the label images also need to be transformed if constexpr (desc::AutoEncoder) { pre_scaler<desc>::transform_all(label_cache); pre_normalizer<desc>::transform_all(label_cache); pre_binarizer<desc>::transform_all(label_cache); } } /*! * \brief Returns the number of dimensions of the input. * \return The number of dimensions of the input. */ static constexpr size_t dimensions() { return etl::dimensions<data_cache_type>() - 1; } }; /*! * \copydoc inmemory_data_generator */ template <typename Iterator, typename LIterator, typename Desc> struct inmemory_data_generator<Iterator, LIterator, Desc, std::enable_if_t<is_augmented<Desc>>> { using desc = Desc; ///< The generator descriptor using weight = etl::value_t<typename Iterator::value_type>; ///< The data type using data_cache_helper_t = cache_helper<desc, Iterator>; ///< The helper for the data cache using label_cache_helper_t = label_cache_helper<desc, weight, LIterator>; ///< The helper for the label cache using data_cache_type = typename data_cache_helper_t::cache_type; ///< The type of the data cache using big_cache_type = typename data_cache_helper_t::big_cache_type; ///< The type of big data cache using label_cache_type = typename label_cache_helper_t::cache_type; ///< The type of the label cache static constexpr bool dll_generator = true; ///< Simple flag to indicate that the class is a DLL generator static constexpr inline size_t batch_size = desc::BatchSize; ///< The size of the generated batches static constexpr inline size_t big_batch_size = desc::BigBatchSize; ///< The number of batches kept in cache data_cache_type input_cache; ///< The data cache big_cache_type batch_cache; ///< The data batch cache label_cache_type label_cache; ///< The label cache random_cropper<Desc> cropper; ///< The random cropper random_mirrorer<Desc> mirrorer; ///< The random mirrorer elastic_distorter<Desc> distorter; ///< The elastic distorter random_noise<Desc> noiser; ///< The random noiser size_t current = 0; ///< The current index bool is_safe = false; ///< Indicates if the generator is safe to reclaim memory from mutable volatile bool status[big_batch_size]; ///< Status of each batch mutable volatile size_t indices[big_batch_size]; ///< Indices of each batch mutable std::mutex main_lock; ///< The main lock mutable std::condition_variable condition; ///< The condition variable for the thread to wait for some space mutable std::condition_variable ready_condition; ///< The condition variable for a reader to wait for ready data volatile bool stop_flag = false; ///< Boolean flag indicating to the thread to stop std::thread main_thread; ///< The main thread bool train_mode = false; ///< The train mode status /*! * \brief Construct an inmemory data generator */ inmemory_data_generator(Iterator first, Iterator last, LIterator lfirst, [[maybe_unused]] LIterator llast, size_t n_classes) : cropper(*first), mirrorer(*first), distorter(*first), noiser(*first) { const size_t n = std::distance(first, last); data_cache_helper_t::init(n, first, input_cache); data_cache_helper_t::init_big(first, batch_cache); label_cache_helper_t::init(n, n_classes, lfirst, label_cache); // Fill the cache size_t i = 0; while (first != last) { input_cache(i) = *first; label_cache_helper_t::set(i, lfirst, label_cache); ++i; ++first; ++lfirst; } // Transform if necessary pre_scaler<desc>::transform_all(input_cache); pre_normalizer<desc>::transform_all(input_cache); pre_binarizer<desc>::transform_all(input_cache); // In case of auto-encoders, the label images also need to be transformed if constexpr (desc::AutoEncoder) { pre_scaler<desc>::transform_all(label_cache); pre_normalizer<desc>::transform_all(label_cache); pre_binarizer<desc>::transform_all(label_cache); } for (size_t b = 0; b < big_batch_size; ++b) { status[b] = false; indices[b] = b; } main_thread = std::thread([this] { while (true) { // The index of the batch inside the batch cache size_t index = 0; { std::unique_lock<std::mutex> ulock(main_lock); bool found = false; // Try to find a read batch first for (size_t b = 0; b < big_batch_size; ++b) { if (!status[b] && indices[b] * batch_size < size()) { index = b; found = true; break; } } // if not found, wait for a ready to compute batch if (!found) { // Wait for the end or for some work condition.wait(ulock, [this, &index] { if (stop_flag) { return true; } for (size_t b = 0; b < big_batch_size; ++b) { if (!status[b] && indices[b] * batch_size < size()) { index = b; return true; } } return false; }); // If there is no more thread for the thread, exit if (stop_flag) { return; } } } // Get the batch that needs to be read const size_t batch = indices[index]; // Get the index from where to read inside the input cache const size_t input_n = batch * batch_size; for (size_t i = 0; i < batch_size && input_n + i < size(); ++i) { if (train_mode) { // Random crop the image cropper.transform_first(batch_cache(index)(i), input_cache(input_n + i)); // Mirror the image mirrorer.transform(batch_cache(index)(i)); // Distort the image distorter.transform(batch_cache(index)(i)); // Noise the image noiser.transform(batch_cache(index)(i)); } else { // Center crop the image cropper.transform_first_test(batch_cache(index)(i), input_cache(input_n + i)); } } // Notify a waiter that one batch is ready { std::unique_lock<std::mutex> ulock(main_lock); status[index] = true; ready_condition.notify_one(); } } }); } inmemory_data_generator(const inmemory_data_generator& rhs) = delete; inmemory_data_generator operator=(const inmemory_data_generator& rhs) = delete; inmemory_data_generator(inmemory_data_generator&& rhs) = delete; inmemory_data_generator operator=(inmemory_data_generator&& rhs) = delete; /*! * \brief Display a description of the generator in the given stream * \param stream The stream to print to * \return stream */ std::ostream& display(std::ostream& stream) const { stream << "In-Memory Data Generator" << std::endl; stream << " Size: " << size() << std::endl; stream << " Batches: " << batches() << std::endl; if (augmented_size() != size()) { stream << " Augmented Size: " << augmented_size() << std::endl; } return stream; } /*! * \brief Display a description of the generator in the standard output. */ void display() const { display(std::cout); } /*! * \brief Indicates that it is safe to destroy the memory of the generator * when not used by the pretraining phase */ void set_safe() { is_safe = true; } /*! * \brier Clear the memory of the generator. * * This is only done if the generator is marked as safe it is safe. */ void clear() { if (is_safe) { input_cache.clear(); batch_cache.clear(); label_cache.clear(); } } /*! * brief Sets the generator in test mode */ void set_test() { train_mode = false; } /*! * brief Sets the generator in train mode */ void set_train() { train_mode = true; } /*! * \brief Destructs the inmemory_data_generator */ ~inmemory_data_generator() { cpp::with_lock(main_lock, [this] { stop_flag = true; }); condition.notify_all(); main_thread.join(); } /*! * \brief Reset the generation to its beginning */ void reset_generation() { std::unique_lock<std::mutex> ulock(main_lock); for (size_t b = 0; b < big_batch_size; ++b) { status[b] = false; indices[b] = b; } condition.notify_one(); } /*! * \brief Reset the generator to the beginning */ void reset() { current = 0; reset_generation(); } /*! * \brief Reset the generator and shuffle the order of samples */ void reset_shuffle() { current = 0; shuffle(); reset_generation(); } /*! * \brief Shuffle the order of the samples. * * This should only be done when the generator is at the beginning. */ void shuffle() { cpp_assert(!current, "Shuffle should only be performed on start of generation"); etl::parallel_shuffle(input_cache, label_cache, dll::rand_engine()); } /*! * \brief Prepare the dataset for an epoch */ void prepare_epoch(){ // Nothing can be done here } /*! * \brief Return the index of the current batch in the generation * \return The current batch index */ size_t current_batch() const { return current / batch_size; } /*! * \brief Returns the number of elements in the generator * \return The number of elements in the generator */ size_t size() const { return etl::dim<0>(input_cache); } /*! * \brief Returns the augmented number of elements in the generator. * * This number may be an estimate, depending on which augmentation * techniques are enabled. * * \return The augmented number of elements in the generator */ size_t augmented_size() const { return cropper.scaling() * mirrorer.scaling() * noiser.scaling() * distorter.scaling() * etl::dim<0>(input_cache); } /*! * \brief Returns the number of batches in the generator. * \return The number of batches in the generator */ size_t batches() const { return size() / batch_size + (size() % batch_size == 0 ? 0 : 1); } /*! * \brief Indicates if the generator has a next batch or not * \return true if the generator has a next batch, false otherwise */ bool has_next_batch() const { return current < size(); } /*! * \brief Moves to the next batch. * * This should only be called if the generator has a next batch. */ void next_batch() { // Get information from batch that has been consumed const auto batch = current / batch_size; const auto b = batch % big_batch_size; { std::unique_lock<std::mutex> ulock(main_lock); status[b] = false; indices[b] += big_batch_size; condition.notify_one(); } current += batch_size; } /*! * \brief Returns the current data batch * \return a a batch of data. */ auto data_batch() const { std::unique_lock<std::mutex> ulock(main_lock); const auto batch = current / batch_size; const auto b = batch % big_batch_size; if (status[b]) { const auto input_n = indices[b] * batch_size + batch_size; if (input_n > size()) { return etl::slice(batch_cache(b), 0, batch_size - (input_n - size())); } else { return etl::slice(batch_cache(b), 0, batch_size); } } ready_condition.wait(ulock, [this, b] { return status[b]; }); const auto input_n = indices[b] * batch_size + batch_size; if (input_n > size()) { return etl::slice(batch_cache(b), 0, batch_size - (input_n - size())); } else { return etl::slice(batch_cache(b), 0, batch_size); } } /*! * \brief Returns the current label batch * \return a a batch of label. */ auto label_batch() const { return etl::slice(label_cache, current, std::min(current + batch_size, size())); } /*! * \brief Returns the number of dimensions of the input. * \return The number of dimensions of the input. */ static constexpr size_t dimensions() { return etl::dimensions<data_cache_type>() - 1; } }; /*! * \brief Display the given generator on the given stream * \param os The output stream * \param generator The generator to display * \return os */ template <typename Iterator, typename LIterator, typename Desc> std::ostream& operator<<(std::ostream& os, inmemory_data_generator<Iterator, LIterator, Desc>& generator) { return generator.display(os); } /*! * \brief Descriptor for a inmemory_data_generator */ template <typename... Parameters> struct inmemory_data_generator_desc { /*! * A list of all the parameters of the descriptor */ using parameters = cpp::type_list<Parameters...>; /*! * \brief The size of a batch */ static constexpr size_t BatchSize = detail::get_value_v<batch_size<1>, Parameters...>; /*! * \brief The number of batch in cache */ static constexpr size_t BigBatchSize = detail::get_value_v<big_batch_size<1>, Parameters...>; /*! * \brief Indicates if the generators must make the labels categorical */ static constexpr bool Categorical = parameters::template contains<categorical>(); /*! * \brief Indicates if horizontal mirroring should be used as augmentation. */ static constexpr bool HorizontalMirroring = parameters::template contains<horizontal_mirroring>(); /*! * \brief Indicates if vertical mirroring should be used as augmentation. */ static constexpr bool VerticalMirroring = parameters::template contains<vertical_mirroring>(); /*! * \brief The random cropping X */ static constexpr size_t random_crop_x = detail::get_value_1_v<random_crop<0, 0>, Parameters...>; /*! * \brief The random cropping Y */ static constexpr size_t random_crop_y = detail::get_value_2_v<random_crop<0, 0>, Parameters...>; /*! * \brief The elastic distortion kernel */ static constexpr size_t ElasticDistortion = detail::get_value_v<elastic_distortion<0>, Parameters...>; /*! * \brief The noise */ static constexpr size_t Noise = detail::get_value_v<noise<0>, Parameters...>; /*! * \brief The scaling */ static constexpr size_t ScalePre = detail::get_value_v<scale_pre<0>, Parameters...>; /*! * \brief The scaling */ static constexpr size_t BinarizePre = detail::get_value_v<binarize_pre<0>, Parameters...>; /*! * \brief Indicates if input are normalized */ static constexpr bool NormalizePre = parameters::template contains<normalize_pre>(); /*! * \brief Indicates if this is an auto-encoder task */ static constexpr bool AutoEncoder = parameters::template contains<autoencoder>(); static_assert(BatchSize > 0, "The batch size must be larger than one"); static_assert(BigBatchSize > 0, "The big batch size must be larger than one"); static_assert(!(AutoEncoder && (random_crop_x || random_crop_y)), "autoencoder mode is not compatible with random crop"); //Make sure only valid types are passed to the configuration list static_assert( detail::is_valid_v< cpp::type_list< batch_size_id, big_batch_size_id, horizontal_mirroring_id, vertical_mirroring_id, random_crop_id, elastic_distortion_id, categorical_id, noise_id, nop_id, normalize_pre_id, binarize_pre_id, scale_pre_id, autoencoder_id>, Parameters...>, "Invalid parameters type for rbm_desc"); /*! * The generator type */ template <typename Iterator, typename LIterator> using generator_t = inmemory_data_generator<Iterator, LIterator, inmemory_data_generator_desc<Parameters...>>; }; /*! * \brief Make an out of memory data generator from iterators */ template <typename Iterator, typename LIterator, typename... Parameters> auto make_generator(Iterator first, Iterator last, LIterator lfirst, LIterator llast, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<Iterator, LIterator>; return std::make_unique<generator_t>(first, last, lfirst, llast, n_classes); } /*! * \brief Make an out of memory data generator from containers */ template <typename Container, typename LContainer, typename... Parameters> auto make_generator(const Container& container, const LContainer& lcontainer, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<typename Container::const_iterator, typename LContainer::const_iterator>; return std::make_unique<generator_t>(container.begin(), container.end(), lcontainer.begin(), lcontainer.end(), n_classes); } // The following are simply helpers for creating generic generators /*! * \brief Make an out of memory data generator from iterators */ template <typename Iterator, typename LIterator, typename... Parameters> auto make_generator(Iterator first, Iterator last, LIterator lfirst, LIterator llast, [[maybe_unused]] size_t n, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<Iterator, LIterator>; return std::make_unique<generator_t>(first, last, lfirst, llast, n_classes); } /*! * \brief Make an out of memory data generator from containers */ template <typename Container, typename LContainer, typename... Parameters> auto make_generator(const Container& container, const LContainer& lcontainer, [[maybe_unused]] size_t n, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<typename Container::const_iterator, typename LContainer::const_iterator>; return std::make_unique<generator_t>(container.begin(), container.end(), lcontainer.begin(), lcontainer.end(), n_classes); } /*! * \brief Prepare an in-memory data generator from an example. The generator * will be constructed to hold the given size and can then be filled. */ template <typename Input, typename Label, typename... Parameters> auto prepare_generator(const Input& input, const Label& label, size_t n, size_t n_classes, const inmemory_data_generator_desc<Parameters...>& /*desc*/) { // Create fake iterators for the type (won't be iterated using Iterator = const Input*; using LIterator = const Label*; // The generator type using generator_t = typename inmemory_data_generator_desc<Parameters...>::template generator_t<Iterator, LIterator>; return std::make_unique<generator_t>(input, label, n, n_classes); } } //end of dll namespace
[ "baptiste.wicht@gmail.com" ]
baptiste.wicht@gmail.com
4c032df9c5f81503760ae95bda4d60241eeff118
1064d896f7c1465a368db07ed4ce73f4172a6b2c
/C++/src/routine_superpixel_texture_and_color_majority.cpp
82bbf8f08e1b3fc5d29edb49148af4e757d8d5cd
[]
no_license
kyle5/apple_detection
264b73751f120ca0f8ecf970c7b844ecbe484a2e
875e178eda12a210afd36ccf9560d4e397cd1e50
refs/heads/master
2021-01-20T15:39:11.534313
2015-02-22T04:38:12
2015-02-22T04:38:12
31,152,198
0
0
null
null
null
null
UTF-8
C++
false
false
8,594
cpp
#include "utility.h" #include "include_in_all.h" #include "superpixel_computation.h" #include "visualization.h" #include "ml_helper_methods.h" #include "feature_computation.h" #include "setup_correct_apple_paths.h" #include "classify_images.h" #include "setup_feature_sets.h" #include "utility.h" #include <iomanip> #include <dirent.h> #include <cstdlib> #define PI 3.14159265 using namespace std; using namespace cv; string feature_type = "SURF"; string apple_type("green"); string root_data_directory = "/media/YIELDEST_KY/apple/"; string dataset_name = "2011_09_15_sunrise_9b/"; // TODO : ex: should mark the dark pixel values throughout the image as pixels that are "dark" // main function that calls everything else // first on one image then make a function to call everything else int main( int argc, char *argv[] ) { srand ( unsigned ( time(NULL) ) ); string dataset_path = root_data_directory + dataset_name; struct filepaths_apple_project fpaths = setup_correct_apple_paths( dataset_path ); string mkdir_apple_type_cmd = string("mkdir ") + apple_type; system( mkdir_apple_type_cmd.c_str() ); float percent_apple, percent_non_apple; Mat temp_percents; // TODO: Need to find a way to only do apple parts classification over the apple segments // full image: labels, texture features, color features ... // aim : features_full_images.all_texture_features string path_features_full_images_mask_dir = "features_full_images_mask/"; string system_call_features_save = string( "mkdir " ) + path_features_full_images_mask_dir; system( system_call_features_save.c_str() ); struct features_full_images features_apple_images; float resize_factor = 1; int save_full_img_features = 0; if ( save_full_img_features ) { features_apple_images = setup_features_full_images( fpaths.raw_training_paths, resize_factor, feature_type, fpaths ); save_features_full_images( path_features_full_images_mask_dir, features_apple_images, fpaths ); } else { features_apple_images = load_features_full_images( path_features_full_images_mask_dir, fpaths ); } vector<Mat> classifications_apple_segmentation; string root_saving_string_mask( "mask_images_" ); struct supervised_feature_set features_mask = setup_supervised_feature_set( fpaths.raw_training_paths, fpaths.mask_paths, 1, fpaths, root_saving_string_mask, resize_factor ); string root_saving_string_mos( "mos_images_" ); struct supervised_feature_set features_mask_of_shape = setup_supervised_feature_set( fpaths.raw_training_paths, fpaths.mos_paths, 0, fpaths, root_saving_string_mos, resize_factor ); // TODO : ex: make a leave one out function for ( int i = 0; i < (int) fpaths.raw_training_paths.size(); i++ ) { if ( fpaths.mask_paths[i].length() == 0 ) continue; // struct classifier_features loo_cf = setup_classifier_features( features_mask, i ); // create_svm( loo_cf ); // create_random_forest( loo_cf ); string raw_image_path = fpaths.raw_training_paths[i]; vector<Mat> superpixels_to_check_vec_mask; struct classification_result cur_class_result = classify_image( loo_cf, raw_image_path, features_apple_images, feature_type, superpixels_to_check_vec_mask, i ); Mat percentages_by_type = calculate_percentage_by_type( cur_class_result.superpixel_image, cur_class_result.classifications ); float min_probability = 0.7; // ex TODO : loop over a number of probabilities : segment superpixels that have a certainty of being apple pixels Mat classifications = calculate_maximal_classifications( percentages_by_type, min_probability ); // vector<Mat> superpixel_indices = calculate_superpixel_indices( cur_class_result.superpixel_image ); // Mat classifications_drawn = draw_classifications( cur_class_result.superpixel_image, classifications ); Mat classifications_drawn = draw_apple_pixels( cur_class_result.superpixel_image, read_image_and_flip_90(raw_image_path, 1), classifications ); ostringstream stream; stream << apple_type << "/results_simple_loo_" << i << ".ppm"; string image_path_cur = stream.str(); imwrite( image_path_cur, classifications_drawn ); if ( fpaths.mos_paths[i].length() == 0 ) continue; // There is no corresponding apple parts image struct classifier_features loo_mos_cf = setup_classifier_features( features_mask_of_shape, i ); Mat superpixels_to_check( classifications.rows, 1, CV_8U, Scalar(0) ); for ( int j = 0; j < classifications.rows; j++ ) { if ( classifications.at<uchar>( j, 0 ) == 1 ) { superpixels_to_check.at<uchar>(j, 0) = 1; } } vector<Mat> superpixels_to_check_vec_mos; superpixels_to_check_vec_mos.push_back( superpixels_to_check ); struct classification_result cur_class_result_mos = classify_image(loo_mos_cf, raw_image_path, features_apple_images, feature_type, superpixels_to_check_vec_mos, i); Mat percentages_by_type_mos = calculate_percentage_by_type( cur_class_result_mos.superpixel_image, cur_class_result_mos.classifications ); float min_probability_mos = 0.25; Mat classifications_mos = calculate_maximal_classifications( percentages_by_type_mos, min_probability_mos ); Mat classifications_drawn_mos = draw_apple_pixels( cur_class_result.superpixel_image, read_image_and_flip_90(raw_image_path, 1), classifications_mos ); ostringstream stream_mos; stream_mos << apple_type << "/results_simple_loo_mos_" << i << ".ppm"; string image_path_cur_mos = stream_mos.str(); imwrite( image_path_cur_mos, classifications_drawn_mos ); } int classify_testing_images = 0; if ( classify_testing_images ) { // TODO : Setup classification over images from a testing set // for each of the testing images : segment apples : segment mos /// load image /// get apple segmentation /// save apple segmentation struct classifier_features full_cf = setup_classifier_features( features_mask ); struct features_full_images temp_input; for ( int i = 0; i < (int) fpaths.testing_image_paths.size(); i++ ) { string cur_testing_image_path = fpaths.testing_image_paths[i]; int cur_testing_image_number = fpaths.testing_image_numbers[i]; vector<Mat> superpixels_to_check_vec_mask; // note i = -1 struct classification_result cur_class_result = classify_image( full_cf, cur_testing_image_path, temp_input, feature_type, superpixels_to_check_vec_mask, -1 ); Mat percentages_by_type = calculate_percentage_by_type( cur_class_result.superpixel_image, cur_class_result.classifications ); float min_probability = 0.7; // ex TODO : loop over a number of probabilities : segment superpixels that have a certainty of being apple pixels Mat classifications = calculate_maximal_classifications( percentages_by_type, min_probability ); // vector<Mat> superpixel_indices = calculate_superpixel_indices( cur_class_result.superpixel_image ); // Mat classifications_drawn = draw_classifications( cur_class_result.superpixel_image, classifications ); Mat raw_img = read_image_and_flip_90(cur_testing_image_path, 1); Mat classifications_drawn = draw_apple_pixels( cur_class_result.superpixel_image, raw_img, classifications ); ostringstream stream; stream << apple_type << "/results_testing_classifications_" << cur_testing_image_number << ".ppm"; string image_path_cur = stream.str(); imwrite( image_path_cur, classifications_drawn ); ostringstream stream_superpixel_img; stream_superpixel_img << apple_type << "/superpixel_image_" << cur_testing_image_number << ".png"; imwrite( stream_superpixel_img.str(), cur_class_result.superpixel_image ); // save the probability of apple classification int idx_apple = 0; Mat apple_classifications_probability_8U = draw_classification_probability( cur_class_result.superpixel_image, percentages_by_type, idx_apple ); ostringstream ap_prob_stream; ap_prob_stream << apple_type << "/apple_probabilities_" << cur_testing_image_number << ".pgm"; imwrite( ap_prob_stream.str(), apple_classifications_probability_8U ); // save the actual classifications Mat apple_classifications_drawn_8U = draw_only_apple_classifications( cur_class_result.superpixel_image, classifications ); ostringstream ap_class_stream; ap_class_stream << apple_type << "/apple_classifications_" << cur_testing_image_number << ".pgm"; imwrite( ap_class_stream.str(), apple_classifications_drawn_8U ); } printf( "z\n" ); } return 0; }
[ "kyle@kyle-All-Series.(none)" ]
kyle@kyle-All-Series.(none)
d30eb7835336c078b994c6947861a94b3fa5c410
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/boost/interfaces/extract.hpp
4a3ce5ac936a78aa303d77001082113c7418afde
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
1,765
hpp
// (C) Copyright Jonathan Turkanis 2004. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) // Disclaimer: Not a Boost library. #ifndef BOOST_IDL_EXTRACT_HPP_INCLUDED #define BOOST_IDL_EXTRACT_HPP_INCLUDED #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <typeinfo> // bad_cast. #include <boost/interfaces/access.hpp> #include <boost/interfaces/detail/interface_table.hpp> #include <boost/interfaces/detail/constants.hpp> #include <boost/interfaces_fwd.hpp> //#include <boost/static_assert.hpp> //#include <boost/type_traits/is_const.hpp> #include <boost/type_traits/remove_const.hpp> namespace boost { namespace interfaces { class bad_extract : public std::bad_cast { public: const char* what() const throw() { return "boost::interfaces::bad_extract: failed extraction"; } }; template<typename X, typename Interface> X& extract(const Interface& i) { typedef typename remove_const<X>::type base_type; // BOOST_STATIC_ASSERT( is_const<X>::value || // !(Interface::interface_flags & flags::is_const) ); try { if (!i) throw bad_extract(); detail::thrower throw_ = detail::get_thrower(i); throw_(access::get_interface_pointer(i)); throw 0; // Unreachable. } catch (base_type* x) { return *x; } catch (void*) { throw bad_extract(); } } template<typename Interface> const std::type_info& target_type(const Interface& i) { if (!i) throw bad_extract(); detail::typer typer = detail::get_typer(i); return typer(); } } } // End namespaces interfaces, boost. #endif // #ifndef BOOST_IDL_EXTRACT_HPP_INCLUDED
[ "j@coderage.com" ]
j@coderage.com
cb6821270b6df9f5231b97e5bb6c491ec05917f6
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h
9f2913252f11f98cf93ae9287fe5f25a9cdbbb7a
[ "MIT", "NCSA", "BSD-3-Clause", "NTP", "LicenseRef-scancode-unknown-license-reference" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
2,066
h
//===-- PPCMCTargetDesc.h - PowerPC Target Descriptions ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file provides PowerPC specific target descriptions. // //===----------------------------------------------------------------------===// #ifndef PPCMCTARGETDESC_H #define PPCMCTARGETDESC_H // GCC #defines PPC on Linux but we use it as our namespace name #undef PPC #include "llvm/Support/DataTypes.h" namespace llvm { class MCAsmBackend; class MCCodeEmitter; class MCContext; class MCInstrInfo; class MCObjectWriter; class MCRegisterInfo; class MCSubtargetInfo; class Target; class StringRef; class raw_ostream; extern Target ThePPC32Target; extern Target ThePPC64Target; extern Target ThePPC64LETarget; MCCodeEmitter *createPPCMCCodeEmitter(const MCInstrInfo &MCII, const MCRegisterInfo &MRI, const MCSubtargetInfo &STI, MCContext &Ctx); MCAsmBackend *createPPCAsmBackend(const Target &T, StringRef TT, StringRef CPU); /// createPPCELFObjectWriter - Construct an PPC ELF object writer. MCObjectWriter *createPPCELFObjectWriter(raw_ostream &OS, bool Is64Bit, uint8_t OSABI); } // End llvm namespace // Generated files will use "namespace PPC". To avoid symbol clash, // undefine PPC here. PPC may be predefined on some hosts. #undef PPC // Defines symbolic names for PowerPC registers. This defines a mapping from // register name to register number. // #define GET_REGINFO_ENUM #include "PPCGenRegisterInfo.inc" // Defines symbolic names for the PowerPC instructions. // #define GET_INSTRINFO_ENUM #include "PPCGenInstrInfo.inc" #define GET_SUBTARGETINFO_ENUM #include "PPCGenSubtargetInfo.inc" #endif
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
02680ec075b5e117fd54a7751662d18f658cc1c7
988e7ad6574222ca77e8620b9fbe15e1b0cc9a1a
/reverse-of-string.cpp
0b91f66f5cc1dd35f0bca05cdf71353472e9e8e8
[]
no_license
vaarigupta/C-_programs
361df5af8ebb9eb36f79a24189e4ff0be3934bd6
ae5d5c6f3b147b16c5dbdbc449de2c6fbb8a5dac
refs/heads/master
2020-03-12T20:36:20.483047
2018-04-26T08:36:29
2018-04-26T08:36:29
130,809,479
0
0
null
null
null
null
UTF-8
C++
false
false
253
cpp
#include<iostream> #include<cstring> using namespace std; void reverse(char a[]) { int i=0; int j =strlen(a) -1; while(i<=j) { swap(a[i],a[j]); i++; j--; } } int main() { char a[100]; cin.get(a,100); reverse(a); cout<<a; return 0; }
[ "cutievaarigupta@gmail.com" ]
cutievaarigupta@gmail.com
d9519972705fbebaf42f077a5dad57ac7dd8707c
ea43e29d2c81f156e324ed7a18d419fa8e311076
/LCompiler/Function.hpp
98e6b4e052600c6c55296adad5aa59f0fddfc194
[ "MIT" ]
permissive
PedroFGP/LCompiler
7ca7b50900d06a7a8519bc090895a1148cd0e664
4e61ce4ae4b0f8f5575d5d844efc97fa65f5bc2d
refs/heads/master
2021-07-06T17:01:34.295851
2017-10-02T21:38:10
2017-10-02T21:38:10
105,586,440
2
0
null
null
null
null
UTF-8
C++
false
false
121
hpp
#include "Includes.hpp" #pragma once class Function { public: RegisterType m_Type; std::string m_Address; };
[ "noreply@github.com" ]
PedroFGP.noreply@github.com
9aac9a88600abc61c4bcceb500b8a798de196ad5
451915543cefc4c588192895204c728dab2278b7
/ProgrammingMethodsAndTechnics/container_Sort.cpp
858059ca3b1d4c47da35b3fe43c7fed7324bfa74
[]
no_license
Bumer19981/ProgrammingMethodsAndTechnics
a523d8838f36bcbf4269b09172219c44869cb073
85bf25e4399ecf06cd16d2c7f19beab4c9153c3f
refs/heads/master
2021-04-02T04:04:19.361030
2020-05-30T17:56:03
2020-05-30T17:56:03
248,238,844
0
0
null
null
null
null
UTF-8
C++
false
false
1,647
cpp
#include <fstream> #include "container_atd.h" using namespace std; namespace simple_langtypes { //bool Compare(langtype* first, langtype* second); void sort(Container& c) { if (c.list.head == NULL) { throw std::invalid_argument("Error: list is empty!"); } for (int i = 0; i < c.list.size - 1; i++) { for (int j = i + 1; j < c.list.size; j++) { Container::List::Node* ComparableItem1 = new Container::List::Node; Container::List::Node* ComparableItem2 = new Container::List::Node; for (int k = 0; k <= i; ++k) { if (k == 0) { ComparableItem1 = c.list.head; } else { ComparableItem1 = ComparableItem1->next; } } for (int k = 0; k <= j; ++k) { if (k == 0) { ComparableItem2 = c.list.head; } else { ComparableItem2 = ComparableItem2->next; } } if (compare(ComparableItem1->l, ComparableItem2->l)) { Container::List::Node* tmp; tmp = ComparableItem2->next; ComparableItem2->next = ComparableItem1->next; ComparableItem2->next->prev = ComparableItem2; ComparableItem1->next = tmp; ComparableItem1->next->prev = ComparableItem1; tmp = ComparableItem1->prev; ComparableItem1->prev = ComparableItem2->prev; ComparableItem1->prev->next = ComparableItem1; ComparableItem2->prev = tmp; ComparableItem2->prev->next = ComparableItem2; if (compare(c.list.head->l, ComparableItem2->l)) c.list.head = ComparableItem2; } } } for (int i = 0; i < c.list.size; ++i) { if (i == 0) { c.list.tail = c.list.head; } else { c.list.tail = c.list.tail->next; } } } }
[ "bumer19981@gmail.com" ]
bumer19981@gmail.com
de22b7071a63a301c8fd819b9184914c37367a37
c4692fbdc122876043a060756aa9ef61e563fca1
/proper/abi/include/locale_misc/collate-inl.h
c68b9b05c41cccf3e2fb4ea0916d0182d6b8e1d9
[]
no_license
nahratzah/ilias_os
837b8eabe3d638767d552206b5c2691a176069fa
a63c03a36e656cee1b897eb952a39bccc2616406
refs/heads/master
2021-01-23T13:43:55.103755
2015-06-11T07:37:01
2015-06-11T07:37:01
28,526,656
1
0
null
null
null
null
UTF-8
C++
false
false
2,653
h
#ifndef _LOCALE_MISC_COLLATE_INL_H_ #define _LOCALE_MISC_COLLATE_INL_H_ #include <locale_misc/collate.h> _namespace_begin(std) template<typename Char> collate<Char>::collate(size_t refs) : locale::facet(refs) {} template<typename Char> collate<Char>::~collate() noexcept {} template<typename Char> auto collate<Char>::compare(const char_type* b1, const char_type* e1, const char_type* b2, const char_type* e2) const -> int { return do_compare(b1, e1, b2, e2); } template<typename Char> auto collate<Char>::transform(const char_type* b, const char_type* e) const -> string_type { return do_transform(b, e); } template<typename Char> auto collate<Char>::hash(const char_type* b, const char_type* e) const -> long { return do_hash(b, e); } template<typename Char> auto collate<Char>::do_compare(const char_type* b1, const char_type* e1, const char_type* b2, const char_type* e2) const -> int { int rv = char_traits<Char>::compare(b1, e1, min(e1 - b1, e2 - b2)); if (rv == 0) { if (e1 - b1 < e2 - b2) return -1; if (e1 - b1 > e2 - b2) return 1; } return 0; } template<typename Char> auto collate<Char>::do_transform(const char_type* b, const char_type* e) const -> string_type { return string_type(b, e); } template<typename Char> auto collate<Char>::do_hash(const char_type* b, const char_type* e) const -> long { using string = basic_string_ref<Char>; using hash_t = _namespace(std)::hash<string>; return hash_t()(string(b, typename string::size_type(e - b))); } template<typename Char> collate_byname<Char>::collate_byname(const char* name, size_t refs) : collate_byname(string_ref(name), refs) {} template<typename Char> collate_byname<Char>::collate_byname(const string& name, size_t refs) : collate_byname(string_ref(name), refs) {} template<typename Char> collate_byname<Char>::collate_byname(string_ref name, size_t refs) : collate<Char>(refs), impl::facet_ref<collate<Char>>(locale(name)) {} template<typename Char> auto collate_byname<Char>::do_compare(const char_type* b1, const char_type* e1, const char_type* b2, const char_type* e2) const -> int { return this->impl.compare(b1, e1, b2, e2); } template<typename Char> auto collate_byname<Char>::do_transform(const char_type* b, const char_type* e) const -> string_type { return this->impl.transform(b, e); } template<typename Char> auto collate_byname<Char>::do_hash(const char_type* b, const char_type* e) const -> long { return this->impl.hash(b, e); } _namespace_end(std) #endif /* _LOCALE_MISC_COLLATE_INL_H_ */
[ "ariane@stack.nl" ]
ariane@stack.nl
2e1947524297a95429c1a81937b6c253756bef76
48a73a0ba850ac2925118dd304baa8f7b2874582
/C++/source/Framework/ObjectRelationalMapping/RelationshipInfoFromSchemaDifference.cpp
4af631b6afd62673a1f66b385e6fdd8d05d10ecf
[ "Apache-2.0" ]
permissive
cxvisa/Wave
5e66dfbe32c85405bc2761c509ba8507ff66f8fe
1aca714933ff1df53d660f038c76ca3f2202bf4a
refs/heads/master
2021-05-03T15:00:49.991391
2018-03-31T23:06:40
2018-03-31T23:06:40
56,774,204
2
1
null
null
null
null
UTF-8
C++
false
false
7,063
cpp
/** *@file RelationshipInfoFromSchemaDifference.h * Copyright (C) 2011 Brocade Communications Systems,Inc. * All rights reserved. * Description: This file declares the class that stores the info regarding a relation * It will be used in the context of storing the added/removed relationships * for each table. * * * Author : Aashish Akhouri * Date : 10/20/2011 */ #include "Framework/ObjectRelationalMapping/RelationshipInfoFromSchemaDifference.h" #include "Framework/Utils/TraceUtils.h" namespace WaveNs { RelationshipInfoFromSchemaDifference::RelationshipInfoFromSchemaDifference (const string & relationName, const string & relatedToTable, OrmRelationUmlType relationUmlType, OrmRelationType relationType, bool disableValidations, bool canBeEmpty) : m_relationName (relationName), m_relatedToTable (relatedToTable), m_relationUmlType (relationUmlType), m_relationType (relationType), m_disableValidations (disableValidations), m_canBeEmpty (canBeEmpty), m_changedRelationshipAttributes (0) { } RelationshipInfoFromSchemaDifference::RelationshipInfoFromSchemaDifference (string relationName, string relationFieldType) { m_relationName = relationName; vector<string> tokens; tokenize(relationFieldType, tokens, '-'); if (tokens[0]=="a") { m_relationUmlType = ORM_RELATION_UML_TYPE_ASSOCIATION; } else if (tokens[0]=="c") { m_relationUmlType = ORM_RELATION_UML_TYPE_COMPOSITION; } else if (tokens[0]=="g") { m_relationUmlType = ORM_RELATION_UML_TYPE_AGGREGATION; } if (tokens[1]=="1") { m_relationType = ORM_RELATION_TYPE_ONE_TO_ONE; } else if (tokens[1]=="m") { m_relationType = ORM_RELATION_TYPE_ONE_TO_MANY; } vector<string>tkns; tokenize(tokens[2],tkns,'|'); m_relatedToTable = tkns[0]; if (tkns[2] == "0") { m_disableValidations = false; } else { m_disableValidations = true; } if (tkns[3] == "0") { m_canBeEmpty = false; } else { m_canBeEmpty = true; } m_changedRelationshipAttributes = 0; } const RelationshipInfoFromSchemaDifference & RelationshipInfoFromSchemaDifference::operator= (const RelationshipInfoFromSchemaDifference & relationInfo) { if(this != &relationInfo) { m_relationName = relationInfo.getRelationName (); m_relatedToTable = relationInfo.getRelatedToTable (); m_relationUmlType = relationInfo.getRelationUmlType (); m_relationType = relationInfo.getRelationType (); m_disableValidations = relationInfo.getDisableValidations (); m_canBeEmpty = relationInfo.getCanBeEmpty (); m_changedRelationshipAttributes = relationInfo.getChangedRelationshipAttributes (); } return (*this); } RelationshipInfoFromSchemaDifference::RelationshipInfoFromSchemaDifference (const RelationshipInfoFromSchemaDifference & relationInfo) { m_relationName = relationInfo.getRelationName (); m_relatedToTable = relationInfo.getRelatedToTable (); m_relationUmlType = relationInfo.getRelationUmlType (); m_relationType = relationInfo.getRelationType (); m_disableValidations = relationInfo.getDisableValidations (); m_canBeEmpty = relationInfo.getCanBeEmpty (); m_changedRelationshipAttributes = relationInfo.getChangedRelationshipAttributes (); } RelationshipInfoFromSchemaDifference::~RelationshipInfoFromSchemaDifference () { } const string & RelationshipInfoFromSchemaDifference::getRelationName () const { return (m_relationName); } const string & RelationshipInfoFromSchemaDifference::getRelatedToTable () const { return (m_relatedToTable); } OrmRelationUmlType RelationshipInfoFromSchemaDifference::getRelationUmlType () const { return (m_relationUmlType); } OrmRelationType RelationshipInfoFromSchemaDifference::getRelationType () const { return (m_relationType); } bool RelationshipInfoFromSchemaDifference::getDisableValidations () const { return (m_disableValidations); } bool RelationshipInfoFromSchemaDifference::getCanBeEmpty () const { return (m_canBeEmpty); } UI8 RelationshipInfoFromSchemaDifference::getChangedRelationshipAttributes () const { return (m_changedRelationshipAttributes); } bool RelationshipInfoFromSchemaDifference::isChangedRelationship () const { if (0 == m_changedRelationshipAttributes) { return false; } return true; } void RelationshipInfoFromSchemaDifference::setCanBeEmptyChanged () { m_changedRelationshipAttributes = ((m_changedRelationshipAttributes) | 0x01); } bool RelationshipInfoFromSchemaDifference::isCanBeEmptyChanged () const { if (0x01 == ((m_changedRelationshipAttributes) & 0x01)) { return true; } return false; } void RelationshipInfoFromSchemaDifference::setDisableValidationChanged () { m_changedRelationshipAttributes = ((m_changedRelationshipAttributes) | 0x02); } bool RelationshipInfoFromSchemaDifference::isDisableValidationChanged () const { if (0x02 == ((m_changedRelationshipAttributes) & 0x02)) { return true; } return false; } void RelationshipInfoFromSchemaDifference::printContentsForDebugging () { if (isChangedRelationship ()) { tracePrintf (TRACE_LEVEL_INFO, false, false, " Relation Name : %s is a changed Relationship\n",m_relationName.c_str()); if (isCanBeEmptyChanged ()) { tracePrintf (TRACE_LEVEL_INFO, false, false, " Can Be Empty is modified in this relation and it is now set to : %d\n", m_canBeEmpty); } if (isDisableValidationChanged ()) { tracePrintf (TRACE_LEVEL_INFO, false, false, " Disable Validation is modified in this relation and it is now set to : %d\n", m_disableValidations); } } tracePrintf (TRACE_LEVEL_INFO, false, false, " Relation Name : %s\n",m_relationName.c_str()); tracePrintf (TRACE_LEVEL_INFO, false, false, " Related To Table : %s\n",m_relatedToTable.c_str()); if (m_relationUmlType == ORM_RELATION_UML_TYPE_ASSOCIATION) { trace (TRACE_LEVEL_INFO, " Relation UML Type : Association"); } else if (m_relationUmlType == ORM_RELATION_UML_TYPE_AGGREGATION) { trace (TRACE_LEVEL_INFO, " Relation UML Type : Aggregation"); } else if (m_relationUmlType == ORM_RELATION_UML_TYPE_COMPOSITION) { trace (TRACE_LEVEL_INFO, " Relation UML Type : Composition"); } if (m_relationType == ORM_RELATION_TYPE_ONE_TO_ONE) { trace (TRACE_LEVEL_INFO, " Relation Type : One to One"); } else if (m_relationType == ORM_RELATION_TYPE_ONE_TO_MANY) { trace (TRACE_LEVEL_INFO, " Relation Type : One to Many"); } tracePrintf (TRACE_LEVEL_INFO, false, false, " Disable Validations is set to : %d\n",m_disableValidations); tracePrintf (TRACE_LEVEL_INFO, false, false, " Can Be Empty is set to : %d\n",m_canBeEmpty); } }
[ "sagar@wave.sagar.cisco.com" ]
sagar@wave.sagar.cisco.com
e381831028fd574d1c0d62069e8810ba4d330d17
0fc78bbf3e9656878924d0ac4b2beec5a4579d81
/perpalin.cpp
8c76d85b7ccc4ee2f25de4fbbc40e94776862524
[]
no_license
adityalahiri/CPP-Code
b15e7139a49b78d87be849465294bff44a87cbe9
98defdeb37388ceb109a5e94b1ac75a0bdc7ec70
refs/heads/master
2021-10-09T12:02:50.874157
2018-12-27T10:51:19
2018-12-27T10:51:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ int num_tests = 0; cin>>num_tests; while(num_tests--){ ll N,P; cin>>N>>P; if((N==P && N==2) || P == 1 || P == 2){ cout<<"impossible"<<endl; continue; } string s[P]; s[0] = 'a'; s[P-1] = 'a'; for(ll i = 1; i<P-1; i++) s[i] = 'b'; for(ll i = 0; i<N; i+=P){ for(ll i = 0; i<P; i++) cout<<s[i]; } cout<<endl; } }
[ "arrayslayer@gmail.com" ]
arrayslayer@gmail.com
2c44462a1140f06e18bf0a60f6494730d14d3c2c
320aebafb7235465345a4e94aa598e4192663813
/tradeapi/utf8/USTPFtdcMduserApi.h
5fc01a883b74701202683e142e73bc9e49e7ebcc
[]
no_license
charmer1989/node-femas-api
5108f7c9ea9ec1cf66ed074b77fb7ed677bacbd7
6584da6d94dc6c6094000264bee6a99fc65504e8
refs/heads/master
2020-07-27T09:53:40.349144
2016-09-23T07:11:17
2016-09-23T07:11:17
67,613,337
3
0
null
null
null
null
UTF-8
C++
false
false
7,902
h
///////////////////////////////////////////////////////////////////////// ///@system 风控前置系统 ///@company 上海金融期货信息技术有限公司 ///@file USTPFtdcMduserApi.h ///@brief 定义了客户端接口 ///@history ///20130520 徐忠华 创建该文件 ///////////////////////////////////////////////////////////////////////// #if !defined(USTP_FTDCMDUSERAPI_H) #define USTP_FTDCMDUSERAPI_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "USTPFtdcUserApiStruct.h" #if defined(ISLIB) && defined(WIN32) #ifdef LIB_MDUSER_API_EXPORT #define MDUSER_API_EXPORT __declspec(dllexport) #else #define MDUSER_API_EXPORT __declspec(dllimport) #endif #else #define MDUSER_API_EXPORT #endif class CUstpFtdcMduserSpi { public: ///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。 virtual void OnFrontConnected(){}; ///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。 ///@param nReason 错误原因 /// 0x1001 网络读失败 /// 0x1002 网络写失败 /// 0x2001 接收心跳超时 /// 0x2002 发送心跳失败 /// 0x2003 收到错误报文 virtual void OnFrontDisconnected(int nReason){}; ///心跳超时警告。当长时间未收到报文时,该方法被调用。 ///@param nTimeLapse 距离上次接收报文的时间 virtual void OnHeartBeatWarning(int nTimeLapse){}; ///报文回调开始通知。当API收到一个报文后,首先调用本方法,然后是各数据域的回调,最后是报文回调结束通知。 ///@param nTopicID 主题代码(如私有流、公共流、行情流等) ///@param nSequenceNo 报文序号 virtual void OnPackageStart(int nTopicID, int nSequenceNo){}; ///报文回调结束通知。当API收到一个报文后,首先调用报文回调开始通知,然后是各数据域的回调,最后调用本方法。 ///@param nTopicID 主题代码(如私有流、公共流、行情流等) ///@param nSequenceNo 报文序号 virtual void OnPackageEnd(int nTopicID, int nSequenceNo){}; ///错误应答 virtual void OnRspError(CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///风控前置系统用户登录应答 virtual void OnRspUserLogin(CUstpFtdcRspUserLoginField *pRspUserLogin, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///用户退出应答 virtual void OnRspUserLogout(CUstpFtdcRspUserLogoutField *pRspUserLogout, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///订阅主题应答 virtual void OnRspSubscribeTopic(CUstpFtdcDisseminationField *pDissemination, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///主题查询应答 virtual void OnRspQryTopic(CUstpFtdcDisseminationField *pDissemination, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///深度行情通知 virtual void OnRtnDepthMarketData(CUstpFtdcDepthMarketDataField *pDepthMarketData) {}; ///订阅合约的相关信息 virtual void OnRspSubMarketData(CUstpFtdcSpecificInstrumentField *pSpecificInstrument, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///退订合约的相关信息 virtual void OnRspUnSubMarketData(CUstpFtdcSpecificInstrumentField *pSpecificInstrument, CUstpFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; }; class MDUSER_API_EXPORT CUstpFtdcMduserApi { public: ///创建MduserApi ///@param pszFlowPath 存贮订阅信息文件的目录,默认为当前目录 ///@return 创建出的UserApi static CUstpFtdcMduserApi *CreateFtdcMduserApi(const char *pszFlowPath = ""); ///获取系统版本号 ///@param nMajorVersion 主版本号 ///@param nMinorVersion 子版本号 ///@return 系统标识字符串 static const char *GetVersion(int &nMajorVersion, int &nMinorVersion); ///删除接口对象本身 ///@remark 不再使用本接口对象时,调用该函数删除接口对象 virtual void Release() = 0; ///初始化 ///@remark 初始化运行环境,只有调用后,接口才开始工作 virtual void Init() = 0; ///等待接口线程结束运行 ///@return 线程退出代码 virtual int Join() = 0; ///获取当前交易日 ///@retrun 获取到的交易日 ///@remark 只有登录成功后,才能得到正确的交易日 virtual const char *GetTradingDay() = 0; ///注册前置机网络地址 ///@param pszFrontAddress:前置机网络地址。 ///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:17001”。 ///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”17001”代表服务器端口号。 virtual void RegisterFront(char *pszFrontAddress) = 0; ///注册名字服务器网络地址 ///@param pszNsAddress:名字服务器网络地址。 ///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:12001”。 ///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”12001”代表服务器端口号。 ///@remark RegisterFront优先于RegisterNameServer virtual void RegisterNameServer(char *pszNsAddress) = 0; ///注册回调接口 ///@param pSpi 派生自回调接口类的实例 virtual void RegisterSpi(CUstpFtdcMduserSpi *pSpi) = 0; ///加载证书 ///@param pszCertFileName 用户证书文件名 ///@param pszKeyFileName 用户私钥文件名 ///@param pszCaFileName 可信任CA证书文件名 ///@param pszKeyFilePassword 用户私钥文件密码 ///@return 0 操作成功 ///@return -1 可信任CA证书载入失败 ///@return -2 用户证书载入失败 ///@return -3 用户私钥载入失败 ///@return -4 用户证书校验失败 virtual int RegisterCertificateFile(const char *pszCertFileName, const char *pszKeyFileName, const char *pszCaFileName, const char *pszKeyFilePassword) = 0; ///订阅市场行情。 ///@param nTopicID 市场行情主题 ///@param nResumeType 市场行情重传方式 /// USTP_TERT_RESTART:从本交易日开始重传 /// USTP_TERT_RESUME:从上次收到的续传(非订阅全部合约时,不支持续传模式) /// USTP_TERT_QUICK:先传送当前行情快照,再传送登录后市场行情的内容 ///@remark 该方法要在Init方法前调用。若不调用则不会收到私有流的数据。 virtual void SubscribeMarketDataTopic(int nTopicID, USTP_TE_RESUME_TYPE nResumeType) = 0; ///订阅合约行情。 ///@param ppInstrumentID 合约ID ///@param nCount 要订阅/退订行情的合约个数 ///@remark virtual int SubMarketData(char *ppInstrumentID[], int nCount)=0; ///退订合约行情。 ///@param ppInstrumentID 合约ID ///@param nCount 要订阅/退订行情的合约个数 ///@remark virtual int UnSubMarketData(char *ppInstrumentID[], int nCount)=0; ///设置心跳超时时间。 ///@param timeout 心跳超时时间(秒) virtual void SetHeartbeatTimeout(unsigned int timeout) = 0; ///风控前置系统用户登录请求 virtual int ReqUserLogin(CUstpFtdcReqUserLoginField *pReqUserLogin, int nRequestID) = 0; ///用户退出请求 virtual int ReqUserLogout(CUstpFtdcReqUserLogoutField *pReqUserLogout, int nRequestID) = 0; ///订阅主题请求 virtual int ReqSubscribeTopic(CUstpFtdcDisseminationField *pDissemination, int nRequestID) = 0; ///主题查询请求 virtual int ReqQryTopic(CUstpFtdcDisseminationField *pDissemination, int nRequestID) = 0; ///订阅合约的相关信息 virtual int ReqSubMarketData(CUstpFtdcSpecificInstrumentField *pSpecificInstrument, int nRequestID) = 0; ///退订合约的相关信息 virtual int ReqUnSubMarketData(CUstpFtdcSpecificInstrumentField *pSpecificInstrument, int nRequestID) = 0; protected: ~CUstpFtdcMduserApi(){}; }; #endif
[ "charmer01@sina.com" ]
charmer01@sina.com
b62269ed8c719e6316288749234db36b395ce70e
6e05fc9db48d795d0485ce8502b3cb9f0ac53074
/spt_helper/src/spt_user_info.cpp
bb868568e39ff024d60a177fdb9e2f18257fa295
[]
no_license
squirrel-project/squirrel_hri
df4a6e6ffb55c25187c7c4f5c334ac8e2c1a3546
719514c945bd06adde608cfc3afeec4ba3cb3869
refs/heads/indigo_dev
2021-09-08T21:27:48.355442
2018-03-12T10:30:13
2018-03-12T10:30:13
28,039,712
0
4
null
2018-03-12T10:30:14
2014-12-15T14:18:25
C
UTF-8
C++
false
false
4,407
cpp
#include <ros/ros.h> #include <visualization_msgs/Marker.h> #include <tf/transform_listener.h> #include <squirrel_person_tracker_msgs/SkeletonVector.h> geometry_msgs::Point gtransformToGpoint(const geometry_msgs::TransformStamped& transform, geometry_msgs::Point& tmpPoint) { tmpPoint.x = transform.transform.translation.x; tmpPoint.y = transform.transform.translation.y; tmpPoint.z = transform.transform.translation.z; return tmpPoint; } void createLineSkel(const squirrel_person_tracker_msgs::Skeleton& skel, visualization_msgs::Marker& line_list) { geometry_msgs::Point tmpPoint; std::vector<geometry_msgs::Point> joint_points; geometry_msgs::TransformStamped transform; line_list.color.b = 1.0; line_list.color.a = 1.0; for (int i = 0; i < skel.skeleton_joints.size(); ++i) { joint_points.push_back(gtransformToGpoint(skel.skeleton_joints[i].joint, tmpPoint)); } if (!joint_points.empty()) { line_list.points.push_back(joint_points[0]); line_list.points.push_back(joint_points[1]); line_list.points.push_back(joint_points[1]); line_list.points.push_back(joint_points[2]); line_list.points.push_back(joint_points[1]); line_list.points.push_back(joint_points[3]); line_list.points.push_back(joint_points[3]); line_list.points.push_back(joint_points[4]); line_list.points.push_back(joint_points[4]); line_list.points.push_back(joint_points[5]); line_list.points.push_back(joint_points[1]); line_list.points.push_back(joint_points[6]); line_list.points.push_back(joint_points[6]); line_list.points.push_back(joint_points[7]); line_list.points.push_back(joint_points[7]); line_list.points.push_back(joint_points[8]); line_list.points.push_back(joint_points[2]); line_list.points.push_back(joint_points[9]); line_list.points.push_back(joint_points[9]); line_list.points.push_back(joint_points[10]); line_list.points.push_back(joint_points[10]); line_list.points.push_back(joint_points[11]); line_list.points.push_back(joint_points[2]); line_list.points.push_back(joint_points[12]); line_list.points.push_back(joint_points[12]); line_list.points.push_back(joint_points[13]); line_list.points.push_back(joint_points[13]); line_list.points.push_back(joint_points[14]); } } void skelVecCB(const squirrel_person_tracker_msgs::SkeletonVector::ConstPtr skel_vec, std::string frame_id, const ros::Publisher& marker_pub, const ros::Publisher& point_pub) { visualization_msgs::Marker line_list; line_list.header.frame_id = frame_id; line_list.header.stamp = ros::Time(0); line_list.action = visualization_msgs::Marker::ADD; line_list.pose.orientation.w = 1.0; line_list.id = 0; line_list.type = visualization_msgs::Marker::LINE_LIST; line_list.scale.x = 0.05; visualization_msgs::Marker sphere_list; sphere_list.header.frame_id = frame_id; sphere_list.header.stamp = ros::Time(0); sphere_list.action = visualization_msgs::Marker::ADD; sphere_list.pose.orientation.w = 1.0; sphere_list.id = 0; sphere_list.type = visualization_msgs::Marker::POINTS; sphere_list.scale.x = 0.15; sphere_list.scale.y = 0.15; sphere_list.color.r = 1; sphere_list.color.g = 0; sphere_list.color.b = 0; sphere_list.color.a = 1; for (int i = 0; i < skel_vec->skeleton_vector.size(); ++i) { createLineSkel(skel_vec->skeleton_vector[i], line_list); if (skel_vec->skeleton_vector[i].isPointing) { sphere_list.header = skel_vec->skeleton_vector[i].pointingPoint.header; sphere_list.points.push_back(skel_vec->skeleton_vector[i].pointingPoint.point); } } point_pub.publish(sphere_list); marker_pub.publish(line_list); sphere_list.points.clear(); line_list.points.clear(); } int main(int argc, char** argv) { ros::init(argc, argv, "spt_skeleton_lines"); ros::NodeHandle n; std::string frame_id = "/kinect_depth_optical_frame"; ros::Publisher marker_pub = n.advertise<visualization_msgs::Marker>("skeleton_lines", 10); ros::Publisher point_pub = n.advertise<visualization_msgs::Marker>("pointing_point", 10); ros::Subscriber subSkelVec = n.subscribe<squirrel_person_tracker_msgs::SkeletonVector>( "/squirrel_person_tracker/user_information", 1, boost::bind(&skelVecCB, _1, frame_id, marker_pub, point_pub)); ros::spin(); }
[ "pregier@cs.uni-bonn.de" ]
pregier@cs.uni-bonn.de
7602f0262c2e8af1dc6e5fbd4beedc47f54ee83c
21b99ea7396881e8a56f41b53e5672e689c805a7
/omnetpp-5.2.1/include/omnetpp/cscheduler.h
1f700bb08652b6ea3085a20f84dbaed9ecfc6a63
[]
no_license
mohammedalasmar/omnetpp-data-transport-model-ndp
7bf8863091345c0c7ce5b5e80052dc739baa8700
cbede62fc2b375e8e0012421a4d60f70f1866d69
refs/heads/master
2023-06-27T06:17:57.433908
2020-10-09T11:30:02
2020-10-09T11:30:02
194,747,934
2
2
null
2021-08-02T17:03:56
2019-07-01T21:54:32
HTML
UTF-8
C++
false
false
7,692
h
//========================================================================= // CSCHEDULER.H - part of // OMNeT++/OMNEST // Discrete System Simulation in C++ // //========================================================================= /*--------------------------------------------------------------* Copyright (C) 2003-2017 Andras Varga Copyright (C) 2006-2017 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file `license' for details on this and other legal matters. *--------------------------------------------------------------*/ #ifndef __OMNETPP_CSCHEDULER_H #define __OMNETPP_CSCHEDULER_H #include "platdep/timeutil.h" // for timeval #include "cobject.h" #include "clifecyclelistener.h" namespace omnetpp { class cEvent; class cSimulation; /** * @brief Abstract class to encapsulate event scheduling. * * The central method is takeNextEvent(). * * To switch to your own scheduler class (reasons you'd like to do that * include real-time simulation, hardware-in-the-loop simulation, * distributed (federated) simulation, parallel distributed simulation), * subclass cScheduler, register your new class with * the Register_Class() macro, then add the following to * <tt>omnetpp.ini</tt>: * * <pre> * [General] * scheduler-class = "MyClass" * </pre> * * @ingroup SimSupport * @ingroup ExtensionPoints */ class SIM_API cScheduler : public cObject, public cISimulationLifecycleListener { protected: cSimulation *sim; protected: /** * A cISimulationLifecycleListener method. Delegates to startRun(), endRun() and * executionResumed(); override if needed. */ virtual void lifecycleEvent(SimulationLifecycleEventType eventType, cObject *details) override; public: /** * Constructor. */ cScheduler(); /** * Destructor. */ virtual ~cScheduler(); /** * Return a short description. This string will be displayed in the Qtenv * and Tkenv GUIs as scheduler information. Returning an empty string means * "default scheduler", and is reserved for cSequentialScheduler. */ virtual std::string str() const override; /** * Pass cSimulation object to scheduler. */ virtual void setSimulation(cSimulation *_sim); /** * Returns the simulation the scheduler belongs to. */ cSimulation *getSimulation() const {return sim;} /** * Called at the beginning of a simulation run. */ virtual void startRun() {} /** * Called at the end of a simulation run. */ virtual void endRun() {} /** * Called every time the user hits the Run button in Tkenv. * Real-time schedulers (e.g. cRealTimeScheduler) may make use of * this callback to pin current simulation time to current * wall clock time. */ virtual void executionResumed() {} /** * Return the likely next event in the simulation. This method is for UI * purposes, it does not play any role in the simulation. A basic * implementation would just return a pointer to the first event in the FES, * which is accurate for sequential simulation; with parallel, distributed or * real-time simulation there might be other events coming from other processes * with a yet smaller timestamp. * * This method should not have side effects, except for discarding stale events * from the FES. */ virtual cEvent *guessNextEvent() = 0; /** * Return the next event to be processed. Normally (with sequential execution), * it just returns the first event in the FES. With parallel and/or real-time * simulation, it is also the scheduler's task to synchronize with real time * and/or with other partitions. * * If there's no more event, it throws cTerminationException. * * A nullptr return value means that there's no error but execution * was stopped by the user (e.g. with STOP button on the GUI) * while takeNextEvent() was waiting for external synchronization. */ virtual cEvent *takeNextEvent() = 0; /** * Undo for takeNextEvent(), approximately: if an event was obtained from * takeNextEvent() but was not yet processed, it is possible to temporarily * put it back to the FES. * * The scheduler class must guarantee that removing the event via * takeNextEvent() again does NOT repeat the side effects of the * first takeNextEvent()! That is, the sequence * * <pre> * e = takeNextEvent(); * putBackEvent(e); * e = takeNextEvent(); * </pre> * * should be equivalent to a single takeNextEvent() call. */ virtual void putBackEvent(cEvent *event) = 0; }; /** * @brief Event scheduler for sequential simulation. * * @ingroup SimSupport */ class SIM_API cSequentialScheduler : public cScheduler { public: /** * Constructor. */ cSequentialScheduler() {} /** * Returns empty string as description. */ virtual std::string str() const override; /** * Returns the first event in the Future Event Set. */ virtual cEvent *guessNextEvent() override; /** * Removes the first event from the Future Event Set, and returns it. */ virtual cEvent *takeNextEvent() override; /** * Puts back the event into the Future Event Set. */ virtual void putBackEvent(cEvent *event) override; }; /** * @brief Real-time scheduler class. * * When installed as scheduler using the scheduler-class omnetpp.ini entry, * it will synchronize simulation execution to real (wall clock) time. * * Operation: a "base time" is determined when startRun() is called. Later on, * the scheduler object calls usleep() from takeNextEvent() to synchronize the * simulation time to real time, that is, to wait until * the current time minus base time becomes equal to the simulation time. * Should the simulation lag behind real time, this scheduler will try to catch up * by omitting sleep calls altogether. * * Scaling is supported via the realtimescheduler-scaling omnetpp.ini entry. * For example, if it is set to 2.0, the simulation will try to execute twice * as fast as real time. * * @ingroup SimSupport */ //TODO soft realtime, hard realtime (that is: tries to catch up, or resynchronizes on each event) class SIM_API cRealTimeScheduler : public cScheduler { protected: // configuration: bool doScaling; double factor; // state: timeval baseTime; protected: virtual void startRun() override; bool waitUntil(const timeval& targetTime); public: /** * Constructor. */ cRealTimeScheduler(); /** * Destructor. */ virtual ~cRealTimeScheduler(); /** * Returns a description that depends on the parametrization of this class. */ virtual std::string str() const override; /** * Recalculates "base time" from current wall clock time. */ virtual void executionResumed() override; /** * Returns the first event in the Future Event Set. */ virtual cEvent *guessNextEvent() override; /** * Scheduler function -- it comes from cScheduler interface. * This function synchronizes to real time: before returning the * first event from the FES, it waits (using usleep()) until * the real time reaches the time of that simulation event. */ virtual cEvent *takeNextEvent() override; /** * Puts back the event into the Future Event Set. */ virtual void putBackEvent(cEvent *event) override; }; } // namespace omnetpp #endif
[ "mohammedzsalasmar@gmail.com" ]
mohammedzsalasmar@gmail.com
b5952f4126ae3959822968d187aae5fa4f573542
40aa541c6529115e964d50ec4fe6f7cf774bc0cb
/opt_algs.1.0/oa_hillclimb.h
cca2d76d9dcf6d367305bcfd95f5e41230d7cc99
[ "BSD-3-Clause" ]
permissive
ghornby/opt_algs
663edcc2f32d7a195f394108c883948d48dd614c
b68aefceda7c6ab50976e87551cc6986b5616321
refs/heads/master
2020-05-18T19:33:01.257390
2017-04-05T18:57:17
2017-04-05T18:57:17
20,343,075
1
0
null
null
null
null
UTF-8
C++
false
false
2,041
h
/*** This file is part of the OptAlgs C++ library originally developed by Gregory Hornby. This code is released under the BSD-3 license: http://opensource.org/licenses/BSD-3-Clause See the file "license.txt" in the root directory for full details. ***/ /* author: Gregory S. Hornby file: oa_hillclimb.h Description: This a simple search algorithm which uses a hill-climbing strategy. */ #ifndef OA_HILLCLIMB_HEADER_FILE #define OA_HILLCLIMB_HEADER_FILE #include "opt_alg.h" #include <iostream> #include <fstream> #include <map> #include <semaphore.h> #include <set> #include <string> #include <vector> class FitnessFunc; class Individual; class HillClimber : public OptAlg { friend std::ostream& operator<<(std::ostream&, const HillClimber&); friend std::istream& operator>>(std::istream&, HillClimber&); public: const static std::string class_name_; /* ******* */ HillClimber(const FitnessFunc* func, const Individual* ind_template); ~HillClimber(); std::string get_class_name() const { return class_name_; } void copy_settings(const HillClimber* p_src); OptAlg* new_instance(const Individual*) const; OptAlg* new_instance() const; OptAlg* make_copy() const; void clear(); void init_variables(); // Only resets evaluation counts. virtual int configure(const char *fname, int verbose); // ************************************************** void do_search_step(); // ************************************************** void print_current_individs(std::ostream& ostr); void print_current_individs(); virtual std::ostream& write_template(std::ostream& ostr) const; virtual std::ostream& write_header(std::ostream& ostr) const; virtual std::ostream& write(std::ostream& os) const; virtual bool write(const char *fname) const; virtual bool write_backup() const; virtual std::istream& read(std::istream& is); virtual bool read(const char *fname); // ********************* protected: Individual* individ_best_; Individual* individ_new_; }; #endif
[ "ghornby@gmail.com" ]
ghornby@gmail.com
b0f9da022642503c09c3942f0110255898253dfd
1a20961af3b03b46c109b09812143a7ef95c6caa
/ZGame/DX11/DirectXTex/ScreenGrab/ScreenGrab12.h
f20c42191774ee2c60f1bf686f41b38e63d8f6bd
[ "MIT" ]
permissive
JetAr/ZNginx
eff4ae2457b7b28115787d6af7a3098c121e8368
698b40085585d4190cf983f61b803ad23468cdef
refs/heads/master
2021-07-16T13:29:57.438175
2017-10-23T02:05:43
2017-10-23T02:05:43
26,522,265
3
1
null
null
null
null
UTF-8
C++
false
false
1,845
h
//-------------------------------------------------------------------------------------- // File: ScreenGrab12.h // // Function for capturing a 2D texture and saving it to a file (aka a 'screenshot' // when used on a Direct3D 12 Render Target). // // Note these functions are useful as a light-weight runtime screen grabber. For // full-featured texture capture, DDS writer, and texture processing pipeline, // see the 'Texconv' sample and the 'DirectXTex' library. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=248926 // http://go.microsoft.com/fwlink/?LinkID=615561 //-------------------------------------------------------------------------------------- #pragma once #include <d3d12.h> #include <ocidl.h> #include <stdint.h> #include <functional> namespace DirectX { HRESULT __cdecl SaveDDSTextureToFile( _In_ ID3D12CommandQueue* pCommandQueue, _In_ ID3D12Resource* pSource, _In_z_ const wchar_t* fileName, D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET); HRESULT __cdecl SaveWICTextureToFile( _In_ ID3D12CommandQueue* pCommandQ, _In_ ID3D12Resource* pSource, REFGUID guidContainerFormat, _In_z_ const wchar_t* fileName, D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATES afterState = D3D12_RESOURCE_STATE_RENDER_TARGET, _In_opt_ const GUID* targetFormat = nullptr, _In_opt_ std::function<void __cdecl(IPropertyBag2*)> setCustomProps = nullptr); }
[ "126.org@gmail.com" ]
126.org@gmail.com
e3d9c3f1e076ae554af9d032aa9628c1aa5df376
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/vis/writer/vis_writer_factory.cpp
f17a2d9662492c70428061ca51440dccfd7d2525
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,323
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_VIS #include "apps/vis/writer/vis_writer_factory.h" #include "apps/vis/writer/vis_writer_keeper.h" #include "apps/vis/writer/vis_png_writer.h" #include "apps/vis/writer/vis_pdf_writer.h" namespace vis { WriterFactory:: WriterFactory( void ) {} WriterFactory::~WriterFactory() {} // ---------------------------------------------------------------------- std::string WriterFactory:: name( void ) const throw() { return "vis_writer"; } // ---------------------------------------------------------------------- std::string WriterFactory:: description( void ) const throw() { return "Vis filewriter objects"; } } #endif
[ "csinger08@users.sourceforge.net" ]
csinger08@users.sourceforge.net
98efd4f0d622df241b771c7a6d3ec86923f8d5cc
e51d009c6c6a1633c2c11ea4e89f289ea294ec7e
/xr2-dsgn/sources/xray/physics/sources/geometry.h
b87b5dc0b929c6fe532929e5251760a5b90d7e52
[]
no_license
avmal0-Cor/xr2-dsgn
a0c726a4d54a2ac8147a36549bc79620fead0090
14e9203ee26be7a3cb5ca5da7056ecb53c558c72
refs/heads/master
2023-07-03T02:05:00.566892
2021-08-06T03:10:53
2021-08-06T03:10:53
389,939,196
3
2
null
null
null
null
UTF-8
C++
false
false
1,697
h
//////////////////////////////////////////////////////////////////////////// // Created : 30.01.2008 // Author : Konstantin Slipchenko // Description : geometry: collision geometry to integration cycle interface //////////////////////////////////////////////////////////////////////////// #ifndef XRAY_PHYSICS_GEOMETRY_H_INCLUDED #define XRAY_PHYSICS_GEOMETRY_H_INCLUDED #include "pose_anchor.h" class contact_info_buffer; class complex_geometry; class transformed_geometry; class box_geometry; class sphere_geometry; class cylinder_geometry; class triangle_mesh_base; class geometry { public: virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const transformed_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const complex_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const box_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const sphere_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const cylinder_geometry& og ) const = 0; virtual void generate_contacts( contact_info_buffer& contacts, const pose_anchor &anch, const triangle_mesh_base& og ) const = 0; public: virtual ~geometry( ){} protected: // virtual void generate_contacts( contact_info_buffer &contacts, const pose_anchor &anch, const geometry &og )const =0; }; #endif
[ "youalexandrov@icloud.com" ]
youalexandrov@icloud.com
224e33f06ee86e3c2566ca1191cf2820190c4e62
39a14ada3b83a1c873fb9eab216ce136fe63acb2
/TETRIS_VS_Server/TETRIS_VS_Server/RoomManager.h
2433545cbad58e1fb548263379c27d581776c6ea
[]
no_license
shield1203/TETRIS_VS_Server
d725c58da040278fee512d0d1832bea904691e5b
02821837db4bfdffb2debdd644cbf4f606a4f249
refs/heads/master
2021-01-02T02:27:36.255157
2020-03-05T17:45:04
2020-03-05T17:45:04
239,449,317
0
0
null
null
null
null
UTF-8
C++
false
false
522
h
#pragma once class GameUser; class PacketManager; enum ROOM_MANAGER { FULL_USER_COUNT = 2 }; struct GameRoom { int roomNum = 0; list<PacketManager*>gameUserList; }; class RoomManager { private: static RoomManager* Inst; RoomManager(); public: list<GameRoom*>m_roomList; public: static RoomManager* getInstance(); void CreateGameRoom(PacketManager*); bool EnterRoom(int, PacketManager*); void ExitRoom(int); void CheckRoom(GameRoom*); void GameStartRoom(int); void SetGameResult(int); ~RoomManager(); };
[ "57628185+shield1203@users.noreply.github.com" ]
57628185+shield1203@users.noreply.github.com
cce76a425374a67e655a29adb6fe02cc28bab0a2
afe353957386de4859f782d29743d1536c5660c5
/OpenGL_4_Application_VS2015/Camera.hpp
0475847f179ecd65e67d48e8eb18d126fa4a5f88
[]
no_license
BlagaCristi/GraphicalProcessingSystemsProject
df0722819f4e40acea150bbdfefd5e2768e638ee
f4380fb0c4168023b28e416625d4426ce02396ba
refs/heads/master
2023-03-05T01:28:49.308577
2021-01-30T19:13:08
2021-01-30T19:13:08
334,490,492
0
0
null
null
null
null
UTF-8
C++
false
false
862
hpp
// // Camera.hpp // // Created by CGIS on 28/10/2016. // Copyright © 2016 CGIS. All rights reserved. // #ifndef Camera_hpp #define Camera_hpp #include <stdio.h> #include "glm/glm.hpp" #include "glm/gtx/transform.hpp" namespace gps { enum MOVE_DIRECTION {MOVE_FORWARD, MOVE_BACKWARD, MOVE_RIGHT, MOVE_LEFT}; class Camera { public: Camera(glm::vec3 cameraPosition, glm::vec3 cameraTarget); glm::mat4 getViewMatrix(); glm::vec3 getCameraTarget(); glm::vec3 getCameraPosition(); void move(MOVE_DIRECTION direction, float speed); void rotate(float pitch, float yaw); void rotateAroundY(float angle); private: glm::vec3 cameraPosition; glm::vec3 cameraTarget; glm::vec3 cameraDirection; glm::vec3 cameraRightDirection; }; } #endif /* Camera_hpp */
[ "blaga.cristi23@gmail.com" ]
blaga.cristi23@gmail.com
527066550fcc10c61464f38660542c8052c3c0ae
1d351697bcf282cd30044db8c35eb10036bca483
/Sound/ScriptMgr.h
8d14371b2cbacc90c901f1b9e984f2b149e03e50
[]
no_license
Hyski/ParadiseCracked
489c007d39a7f7f7a0331a7282d8ba4f083918c0
b3815cc146c038a8454c97e9f48d462c8ddc50ca
refs/heads/master
2021-04-04T13:21:18.347302
2020-03-19T09:25:44
2020-03-19T09:25:44
248,460,973
0
1
null
null
null
null
WINDOWS-1251
C++
false
false
631
h
#if !defined(__SCRIPT_MANAGER_INCLUDED__) #define __SCRIPT_MANAGER_INCLUDED__ #include <map> class cc_DirectMusic; class cc_SndScript; class cc_SegmentMgr; class cc_ScriptMgr { static const char *m_LogFile; typedef std::map<std::string,cc_SndScript *> scripts_t; scripts_t m_Scripts; DECLARE_LOG_MEMBER(m_log); cc_SegmentMgr *m_segmentMgr; public: cc_ScriptMgr(cc_SegmentMgr *); ~cc_ScriptMgr(); // Инициализация/деинициализация // void init(); // void shut(); cc_SndScript *getScript(const char *scriptName); // Для загрузчика void addScript(cc_SndScript *); }; #endif
[ "43969955+Hyski@users.noreply.github.com" ]
43969955+Hyski@users.noreply.github.com
b85c598b93e86eab1aed35bfbcad0e64e41fc4fd
1e58f86db88d590ce63110c885c52305d67f8136
/Common/application.h
135c6ff621210a865d79a44129e62e0f359c1abb
[]
no_license
urielyan/F270
32a9b87780b6b0bbbd8e072ca4305cd38dc975c1
c3d1eceead895ded12166eeb6748df111f46ef2d
refs/heads/master
2021-01-10T02:06:40.335370
2016-03-02T03:23:02
2016-03-02T03:23:02
52,927,128
1
1
null
null
null
null
UTF-8
C++
false
false
999
h
#ifndef APPLICATION_H #define APPLICATION_H #include <QApplication> #include <QTimer> #include "eventaction.h" class Application : public QApplication { Q_OBJECT public: explicit Application(int & argc, char ** argv); bool notify(QObject *receiver, QEvent *e); void actionEventNotify(EVENT_OBJECT *pEvent); //动作事件通知 void lcdSaverConfigChanged(); //TODO,启动时待调用 void autoGroupConfigChanged(); //TODO,启动时待调用 void homeWinConfigChanged(); //TODO,启动时待调用 private slots: void slotLcdSaverTimeOut(); void slotAutoGroupTimerOut(); void slotHomeWinTimeOut(); private: int m_actionEvent; //动作事件类型注册值 bool m_lcdSaved; //LCD屏幕保护模式 QTimer m_lcdSaver; //LCD屏幕保护定时器 QTimer m_autoGroup; //组自动切换定时器 QTimer m_homeWin; //默认窗体切换定时器 friend class EventAction; }; #endif // APPLICATION_H
[ "urielyan@sina.com" ]
urielyan@sina.com
00027acf9ab6f5987171deeec9ca0d7328220c6e
ec5a3af4822403e5adbfb44dfba9ece0c8998ed6
/src/Vulkan/VulkanPipeline.cpp
5e90094384230427fd69843572f5b47e86b295a6
[]
no_license
WeyrSDev/VirtualVistaVulkan
99ff448a39f4d06fe49f2b0d9aa5543c8d79cbd6
6a979510da45b3e55b47674d74078ffdb42565f0
refs/heads/master
2021-05-05T19:14:38.918264
2017-06-15T22:52:09
2017-06-15T22:52:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,561
cpp
#include "VulkanPipeline.h" namespace vv { ///////////////////////////////////////////////////////////////////////////////////////////// Public VulkanPipeline::VulkanPipeline() { } VulkanPipeline::~VulkanPipeline() { } void VulkanPipeline::create(VulkanDevice *device, Shader *shader, VkPipelineLayout pipeline_layout, VulkanRenderPass *render_pass, VkFrontFace front_face, bool depth_test_enable, bool depth_write_enable) { _device = device; VkPipelineShaderStageCreateInfo vert_shader_create_info = {}; vert_shader_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; vert_shader_create_info.stage = VK_SHADER_STAGE_VERTEX_BIT; vert_shader_create_info.module = shader->vert_module; vert_shader_create_info.pName = "main"; VkPipelineShaderStageCreateInfo frag_shader_create_info = {}; frag_shader_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; frag_shader_create_info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; frag_shader_create_info.module = shader->frag_module; frag_shader_create_info.pName = "main"; std::array<VkPipelineShaderStageCreateInfo, 2> shaders = { vert_shader_create_info, frag_shader_create_info }; // Fixed Function Pipeline Layout VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info = {}; vertex_input_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; vertex_input_state_create_info.flags = 0; vertex_input_state_create_info.vertexBindingDescriptionCount = 1; vertex_input_state_create_info.vertexAttributeDescriptionCount = (uint32_t)Vertex::getAttributeDescriptions().size(); vertex_input_state_create_info.pVertexBindingDescriptions = &Vertex::getBindingDesciption(); vertex_input_state_create_info.pVertexAttributeDescriptions = Vertex::getAttributeDescriptions().data(); VkPipelineInputAssemblyStateCreateInfo input_assembly_create_info = {}; input_assembly_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; input_assembly_create_info.flags = 0; input_assembly_create_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; // render triangles input_assembly_create_info.primitiveRestartEnable = VK_FALSE; // todo: viewport should be dynamic. figure out how to update pipeline when needed. probably has to do with dynamic state settings. VkViewport viewport = {}; viewport.width = static_cast<float>(Settings::inst()->getWindowWidth()); viewport.height = static_cast<float>(Settings::inst()->getWindowHeight()); viewport.x = 0.0f; viewport.y = 0.0f; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = { 0, 0 }; scissor.extent.width = static_cast<uint32_t>(Settings::inst()->getWindowWidth()); scissor.extent.height = static_cast<uint32_t>(Settings::inst()->getWindowHeight()); VkPipelineViewportStateCreateInfo viewport_state_create_info = {}; viewport_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewport_state_create_info.flags = 0; viewport_state_create_info.viewportCount = 1; viewport_state_create_info.scissorCount = 1; viewport_state_create_info.pViewports = &viewport; viewport_state_create_info.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterization_state_create_info = {}; rasterization_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterization_state_create_info.depthClampEnable = VK_FALSE; // clamp geometry within clip space rasterization_state_create_info.rasterizerDiscardEnable = VK_FALSE; // discard geometry rasterization_state_create_info.polygonMode = VK_POLYGON_MODE_FILL; // create fragments from the inside of a polygon rasterization_state_create_info.lineWidth = 1.0f; rasterization_state_create_info.cullMode = VK_CULL_MODE_BACK_BIT; // cull the back of polygons from rendering rasterization_state_create_info.frontFace = front_face;// VK_FRONT_FACE_CLOCKWISE; // order of vertices rasterization_state_create_info.depthBiasEnable = VK_FALSE; // all stuff for shadow mapping? look into it rasterization_state_create_info.depthBiasClamp = 0.0f; rasterization_state_create_info.depthBiasConstantFactor = 0.0f; rasterization_state_create_info.depthBiasSlopeFactor = 0.0f; // todo: add anti-aliasing settings support VkPipelineMultisampleStateCreateInfo multisample_state_create_info = {}; multisample_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisample_state_create_info.flags = 0; multisample_state_create_info.sampleShadingEnable = VK_FALSE; multisample_state_create_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; multisample_state_create_info.minSampleShading = 1.0f; multisample_state_create_info.pSampleMask = nullptr; multisample_state_create_info.alphaToCoverageEnable = VK_FALSE; multisample_state_create_info.alphaToOneEnable = VK_FALSE; VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info = {}; depth_stencil_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depth_stencil_state_create_info.flags = 0; depth_stencil_state_create_info.depthTestEnable = depth_test_enable; depth_stencil_state_create_info.depthWriteEnable = depth_write_enable; depth_stencil_state_create_info.depthCompareOp = VK_COMPARE_OP_LESS; depth_stencil_state_create_info.depthBoundsTestEnable = VK_FALSE; depth_stencil_state_create_info.minDepthBounds = 0.0f; depth_stencil_state_create_info.maxDepthBounds = 1.0f; depth_stencil_state_create_info.stencilTestEnable = VK_FALSE; // don't want to do any cutting of the image currently. depth_stencil_state_create_info.front = {}; depth_stencil_state_create_info.back = {}; // todo: for some reason, if this is activated the output color is overridden // This along with color blend create info specify alpha blending operations VkPipelineColorBlendAttachmentState color_blend_attachment_state = {}; color_blend_attachment_state.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; color_blend_attachment_state.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo color_blend_state_create_info = {}; color_blend_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; color_blend_state_create_info.logicOpEnable = VK_FALSE; color_blend_state_create_info.logicOp = VK_LOGIC_OP_COPY; color_blend_state_create_info.attachmentCount = 1; color_blend_state_create_info.pAttachments = &color_blend_attachment_state; color_blend_state_create_info.blendConstants[0] = 0.0f; color_blend_state_create_info.blendConstants[1] = 0.0f; color_blend_state_create_info.blendConstants[2] = 0.0f; color_blend_state_create_info.blendConstants[3] = 0.0f; // add enum values here for more dynamic pipeline state changes!! /*std::array<VkDynamicState, 2> dynamic_pipeline_settings = { VK_DYNAMIC_STATE_VIEWPORT }; VkPipelineDynamicStateCreateInfo dynamic_state_create_info = {}; dynamic_state_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; dynamic_state_create_info.flags = 0; dynamic_state_create_info.dynamicStateCount = (uint32_t)dynamic_pipeline_settings.size(); dynamic_state_create_info.pDynamicStates = dynamic_pipeline_settings.data();*/ VkGraphicsPipelineCreateInfo graphics_pipeline_create_info = {}; graphics_pipeline_create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; graphics_pipeline_create_info.flags = 0; graphics_pipeline_create_info.stageCount = 2; graphics_pipeline_create_info.pStages = shaders.data(); graphics_pipeline_create_info.pVertexInputState = &vertex_input_state_create_info; graphics_pipeline_create_info.pInputAssemblyState = &input_assembly_create_info; graphics_pipeline_create_info.pViewportState = &viewport_state_create_info; graphics_pipeline_create_info.pRasterizationState = &rasterization_state_create_info; graphics_pipeline_create_info.pDynamicState = VK_NULL_HANDLE;//&dynamic_state_create_info; graphics_pipeline_create_info.pTessellationState = VK_NULL_HANDLE; graphics_pipeline_create_info.pMultisampleState = &multisample_state_create_info; graphics_pipeline_create_info.pDepthStencilState = &depth_stencil_state_create_info; graphics_pipeline_create_info.pColorBlendState = &color_blend_state_create_info; graphics_pipeline_create_info.layout = pipeline_layout; graphics_pipeline_create_info.renderPass = render_pass->render_pass; graphics_pipeline_create_info.subpass = 0; // index of render_pass that this pipeline will be used with graphics_pipeline_create_info.basePipelineHandle = VK_NULL_HANDLE; // used for creating new pipeline from existing one. // info: the null handle here specifies a VkPipelineCache that can be used to store pipeline creation info after a pipeline's deletion. VV_CHECK_SUCCESS(vkCreateGraphicsPipelines(_device->logical_device, VK_NULL_HANDLE, 1, &graphics_pipeline_create_info, nullptr, &pipeline)); } void VulkanPipeline::shutDown() { vkDestroyPipeline(_device->logical_device, pipeline, nullptr); } void VulkanPipeline::bind(VkCommandBuffer command_buffer, VkPipelineBindPoint bind_point) const { vkCmdBindPipeline(command_buffer, bind_point, pipeline); } ///////////////////////////////////////////////////////////////////////////////////////////// Private }
[ "romanylarionov@gmail.com" ]
romanylarionov@gmail.com
2cc76ada63d066c138b7a4202bf08d90b6980398
140d78334109e02590f04769ec154180b2eaf78d
/aws-cpp-sdk-marketplace-entitlement/include/aws/marketplace-entitlement/model/Entitlement.h
cb1cbd41f3eecf0ef1a6221433aa447189bb6eda
[ "Apache-2.0", "MIT", "JSON" ]
permissive
coderTong/aws-sdk-cpp
da140feb7e5495366a8d2a6a02cf8b28ba820ff6
5cd0c0a03b667c5a0bd17394924abe73d4b3754a
refs/heads/master
2021-07-08T07:04:40.181622
2017-08-22T21:50:00
2017-08-22T21:50:00
101,145,374
0
1
Apache-2.0
2021-05-04T21:06:36
2017-08-23T06:24:37
C++
UTF-8
C++
false
false
12,794
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/marketplace-entitlement/MarketplaceEntitlementService_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/marketplace-entitlement/model/EntitlementValue.h> #include <aws/core/utils/DateTime.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace MarketplaceEntitlementService { namespace Model { /** * <p>An entitlement represents capacity in a product owned by the customer. For * example, a customer might own some number of users or seats in an SaaS * application or some amount of data capacity in a multi-tenant * database.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/entitlement.marketplace-2017-01-11/Entitlement">AWS * API Reference</a></p> */ class AWS_MARKETPLACEENTITLEMENTSERVICE_API Entitlement { public: Entitlement(); Entitlement(const Aws::Utils::Json::JsonValue& jsonValue); Entitlement& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline const Aws::String& GetProductCode() const{ return m_productCode; } /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline void SetProductCode(const Aws::String& value) { m_productCodeHasBeenSet = true; m_productCode = value; } /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline void SetProductCode(Aws::String&& value) { m_productCodeHasBeenSet = true; m_productCode = std::move(value); } /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline void SetProductCode(const char* value) { m_productCodeHasBeenSet = true; m_productCode.assign(value); } /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline Entitlement& WithProductCode(const Aws::String& value) { SetProductCode(value); return *this;} /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline Entitlement& WithProductCode(Aws::String&& value) { SetProductCode(std::move(value)); return *this;} /** * <p>The product code for which the given entitlement applies. Product codes are * provided by AWS Marketplace when the product listing is created.</p> */ inline Entitlement& WithProductCode(const char* value) { SetProductCode(value); return *this;} /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline const Aws::String& GetDimension() const{ return m_dimension; } /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline void SetDimension(const Aws::String& value) { m_dimensionHasBeenSet = true; m_dimension = value; } /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline void SetDimension(Aws::String&& value) { m_dimensionHasBeenSet = true; m_dimension = std::move(value); } /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline void SetDimension(const char* value) { m_dimensionHasBeenSet = true; m_dimension.assign(value); } /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline Entitlement& WithDimension(const Aws::String& value) { SetDimension(value); return *this;} /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline Entitlement& WithDimension(Aws::String&& value) { SetDimension(std::move(value)); return *this;} /** * <p>The dimension for which the given entitlement applies. Dimensions represent * categories of capacity in a product and are specified when the product is listed * in AWS Marketplace.</p> */ inline Entitlement& WithDimension(const char* value) { SetDimension(value); return *this;} /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline const Aws::String& GetCustomerIdentifier() const{ return m_customerIdentifier; } /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline void SetCustomerIdentifier(const Aws::String& value) { m_customerIdentifierHasBeenSet = true; m_customerIdentifier = value; } /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline void SetCustomerIdentifier(Aws::String&& value) { m_customerIdentifierHasBeenSet = true; m_customerIdentifier = std::move(value); } /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline void SetCustomerIdentifier(const char* value) { m_customerIdentifierHasBeenSet = true; m_customerIdentifier.assign(value); } /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline Entitlement& WithCustomerIdentifier(const Aws::String& value) { SetCustomerIdentifier(value); return *this;} /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline Entitlement& WithCustomerIdentifier(Aws::String&& value) { SetCustomerIdentifier(std::move(value)); return *this;} /** * <p>The customer identifier is a handle to each unique customer in an * application. Customer identifiers are obtained through the ResolveCustomer * operation in AWS Marketplace Metering Service.</p> */ inline Entitlement& WithCustomerIdentifier(const char* value) { SetCustomerIdentifier(value); return *this;} /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline const EntitlementValue& GetValue() const{ return m_value; } /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline void SetValue(const EntitlementValue& value) { m_valueHasBeenSet = true; m_value = value; } /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline void SetValue(EntitlementValue&& value) { m_valueHasBeenSet = true; m_value = std::move(value); } /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline Entitlement& WithValue(const EntitlementValue& value) { SetValue(value); return *this;} /** * <p>The EntitlementValue represents the amount of capacity that the customer is * entitled to for the product.</p> */ inline Entitlement& WithValue(EntitlementValue&& value) { SetValue(std::move(value)); return *this;} /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline const Aws::Utils::DateTime& GetExpirationDate() const{ return m_expirationDate; } /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline void SetExpirationDate(const Aws::Utils::DateTime& value) { m_expirationDateHasBeenSet = true; m_expirationDate = value; } /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline void SetExpirationDate(Aws::Utils::DateTime&& value) { m_expirationDateHasBeenSet = true; m_expirationDate = std::move(value); } /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline Entitlement& WithExpirationDate(const Aws::Utils::DateTime& value) { SetExpirationDate(value); return *this;} /** * <p>The expiration date represents the minimum date through which this * entitlement is expected to remain valid. For contractual products listed on AWS * Marketplace, the expiration date is the date at which the customer will renew or * cancel their contract. Customers who are opting to renew their contract will * still have entitlements with an expiration date.</p> */ inline Entitlement& WithExpirationDate(Aws::Utils::DateTime&& value) { SetExpirationDate(std::move(value)); return *this;} private: Aws::String m_productCode; bool m_productCodeHasBeenSet; Aws::String m_dimension; bool m_dimensionHasBeenSet; Aws::String m_customerIdentifier; bool m_customerIdentifierHasBeenSet; EntitlementValue m_value; bool m_valueHasBeenSet; Aws::Utils::DateTime m_expirationDate; bool m_expirationDateHasBeenSet; }; } // namespace Model } // namespace MarketplaceEntitlementService } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
ae46a06e17c1a9187514d036bfc4bac1e9491e79
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/mpl/set/aux_/include_preprocessed.hpp
e7e455895e5e9a9d32b208739377283b0ab8051f
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:d014fe3aeb77d984dbcdb21c769c2d8c9c4f8ffc3265b98dac482537fda280f9 size 1189
[ "YLiLarry@gmail.com" ]
YLiLarry@gmail.com
412a88248a3dbc80ac3a655c4df69467f01d4d69
1d11ed2f1fdba2fd9472f6d762d8ab2369bd0fc8
/Spaghetti/Spaghetti/src/Spaghetti/CCollision.h
ede2d93210813cfc98e0cdf00227dce11acae08c
[]
no_license
SamOatesUniversity/Year-3---Physics---Spaghetti
339c8c9e72c04ecdcba17e5e76176608c21aeb12
0785a2cfcc87048b04f95fca5f81d108cf5c57d8
refs/heads/master
2021-03-12T20:36:06.364559
2013-06-06T09:21:30
2013-06-06T09:21:30
41,171,737
0
0
null
null
null
null
UTF-8
C++
false
false
257
h
#pragma once #include <Ogre/Ogre.h> class CSpaghettiRigidBody; class CCollision { public: CSpaghettiRigidBody *bodyOne; CSpaghettiRigidBody *bodyTwo; Ogre::Vector3 collisionPoint; Ogre::Vector3 collisionNormal; float penetration; };
[ "sam@samoatesgames.com" ]
sam@samoatesgames.com
750ba1e613b374e8fce1631ec5ab6f16090c2e9c
bb0c64f97a7350b48e0a1c7a6f54429a436c6e10
/board.h
71ae61c69c16351dbe3496c4401a98b66bec957f
[]
no_license
arladerus/cs246FinalProject
1c32df001c46a56082b6c0925c3cb52fbb4feaec
23e2e6ac2338227d822c8c8cdb9b5b5ee9a99f75
refs/heads/master
2021-01-18T10:36:50.335480
2013-07-21T04:07:55
2013-07-21T04:07:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
958
h
#ifndef __BOARD_H__ #define __BOARD_H__ #include "cell.h" #include "window.h" #include<iostream> class Board{ Cell ** gameBoard; //the board object that holds the game matrix Xwindow * window; //the GUI int xStartPos; //default starting location for the blocks int yStartPos; int column; //column of the matrix int row; //row of the matrix int cellSize; //size of each cell on screen public: Board(); Board(const int& row, const int& column, const int& xStart, const int& yStart); ~Board(); bool isEmpty(const int&x , const int&y); //returns if the location is empty, false if it reaches an edge bool moveCell(const int& xFrom, const int& yFrom, const int& xDest, const int& yDest); //moves the cell, empties the original cell, invoked by the Block class //returns false if the destination cell is occupied void XwindowUpdate(); //updates the window friend std::ostream& operator<<(std::ostream&, const Board&); }; #endif
[ "joeyjoeyze@hotmail.com" ]
joeyjoeyze@hotmail.com
ffffac42c7fa4978d9cc8e3c3ceb3417e791107a
2ba632d229790bfd58a0f0401b75266e3a7594eb
/CODES/code37.cpp
cbbe957168db1c74754441b961b46c8132517dc9
[]
no_license
M0315G/C-plus-plus-Basics
b1e4ae3a824367d98c5e82635f62d5aafa7c7227
bcc75d78d8f69c156df1a52299517b9ffc4cc5d0
refs/heads/main
2023-06-11T02:25:41.604185
2021-06-29T16:44:47
2021-06-29T16:44:47
333,783,501
0
0
null
null
null
null
UTF-8
C++
false
false
590
cpp
// Problem: T-primes // Link: https://codeforces.com/contest/230/problem/B #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; while(n>0){ int a; cin >> a; int sqr = sqrt(a); bool flag=false; for(int i=2; i<a/2; ++i){ if(sqr%2==0){ flag=true; break; } } if(!flag){ cout << "YES" << endl; }else{ cout << "NO" << endl; } n--; } return 0; }
[ "noreply@github.com" ]
M0315G.noreply@github.com
1155eb6019593a66d25280bca0f01b0eafb59f5c
5b6708afab2d064a3040a715e200057a90f47317
/src_lowlatency/components/store/kvstore_test.cc
22f6f3fe5f0be7f6ea88aa70778151419d41f030
[]
no_license
ldanilek/CalvinHDFS
0f032bd4b5d8e13431cfe6402f6826525932fe1d
22059285419519a92c4e6d6c7945ca3824440a3b
refs/heads/master
2020-12-02T11:30:16.998527
2017-05-25T20:42:18
2017-05-25T20:42:18
96,644,617
0
0
null
null
null
null
UTF-8
C++
false
false
2,397
cc
// Author: Alexander Thomson <thomson@cs.yale.edu> // // TODO(agt): Move to btreestore_test.cc // TODO(agt): Test Actions. #include "components/store/kvstore.h" #include "components/store/btreestore.h" #include "components/store/leveldbstore.h" #include <gflags/gflags.h> #include <gtest/gtest.h> #include <glog/logging.h> #include <map> #include <string> #include "common/utils.h" using std::map; template<class KVStoreType> void TestInsertDelete() { KVStoreType s; string result; EXPECT_FALSE(s.Exists("a")); EXPECT_FALSE(s.Get("a", &result)); s.Put("a", "alpha"); EXPECT_TRUE(s.Exists("a")); EXPECT_TRUE(s.Get("a", &result)); EXPECT_EQ("alpha", result); s.Put("b", "bravo"); EXPECT_TRUE(s.Exists("a")); EXPECT_TRUE(s.Get("a", &result)); EXPECT_EQ("alpha", result); EXPECT_TRUE(s.Exists("b")); EXPECT_TRUE(s.Get("b", &result)); EXPECT_EQ("bravo", result); s.Delete("a"); EXPECT_FALSE(s.Exists("a")); EXPECT_FALSE(s.Get("a", &result)); EXPECT_TRUE(s.Exists("b")); EXPECT_TRUE(s.Get("b", &result)); EXPECT_EQ("bravo", result); } TEST(BTreeStoreTest, EmptyIterator) { BTreeStore s; KVStore::Iterator* i = s.GetIterator(); EXPECT_FALSE(i->Valid()); i->Next(); EXPECT_FALSE(i->Valid()); delete i; // TODO(agt): ASSERT_DEATH tests on bad i->Key() and i->Value() calls. } template<class KVStoreType> void TestIterator() { BTreeStore s; map<string, string> m; for (int i = 0; i < 1000; i++) { string k = RandomString(3 + rand() % 7); string v = RandomString(100); s.Put(k, v); m[k] = v; } KVStore::Iterator* i = s.GetIterator(); EXPECT_FALSE(i->Valid()); i->Next(); for (auto j = m.begin(); j != m.end(); ++j) { EXPECT_TRUE(i->Valid()); EXPECT_EQ(j->first, i->Key()); EXPECT_EQ(j->second, i->Value()); i->Next(); } EXPECT_FALSE(i->Valid()); delete i; // TODO(agt): Also test thread safety. } TEST(BTreeStoreTest, InsertDelete) { TestInsertDelete<BTreeStore>(); } TEST(BTreeStoreTest, Iterator) { TestIterator<BTreeStore>(); } TEST(LevelDBStoreTest, InsertDelete) { TestInsertDelete<LevelDBStore>(); } TEST(LevelDBStoreTest, Iterator) { TestIterator<LevelDBStore>(); } int main(int argc, char **argv) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "kun.ren@yale.edu" ]
kun.ren@yale.edu
7bc63bd72caca2f993780a10e12a197cee0663fd
f538e176b90909c0907cca87525567d596731b0c
/multiServer/client.cc
6433b1999dbc602675d7a94f1c85cb06d91d1862
[]
no_license
GzhuFlyer/Unix_demo
d9655117300ad614c9077b1679ced278b4c3ecf8
f684773913bbe176a3e1a7d0bce41ab3b15f10b3
refs/heads/master
2023-02-01T11:40:43.200894
2020-12-21T16:55:55
2020-12-21T16:55:55
317,797,840
0
0
null
null
null
null
UTF-8
C++
false
false
1,108
cc
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <unistd.h> #define ERR_EXIT(M) \ do \ { \ perror(M); \ exit(EXIT_FAILURE); \ }while(0) int main(void) { int sock; if((sock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0) ERR_EXIT("socket"); struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // servaddr.sin_addr.s_addr = inet_addr("47.112.152.139"); if(connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) ERR_EXIT("connect"); // printf("error connect\n"); char sendbuf[1024] = {0}; char recvbuf[1024] = {0}; while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL) { write(sock,sendbuf,strlen(sendbuf)); read(sock,recvbuf,sizeof(recvbuf)); fputs(recvbuf,stdout); } close(sock); return 0; }
[ "gzhuflyer@foxmail.com" ]
gzhuflyer@foxmail.com
6f10decb3fb7fdccc21a5afb410c1c402a63c10d
6e98a5d1588baaff7870316210c8033631fd7d3c
/programs/create_genesis/genesis_mapper.hpp
9b3c9794827c2152b9738bb0f26d11c3027d170b
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
scorum/scorum
f2ca45a678e46638d1bd0ebe868bed0431a53492
f660e3f8ead05f90e412f4d83f92e34ada13a61b
refs/heads/develop
2022-08-16T19:09:03.918951
2022-06-09T08:45:52
2022-06-09T10:04:56
106,838,543
57
30
NOASSERTION
2023-08-31T15:33:27
2017-10-13T15:01:17
C++
UTF-8
C++
false
false
1,292
hpp
#pragma once #include <map> #include <string> #include <scorum/chain/genesis/genesis_state.hpp> #include <fc/static_variant.hpp> namespace scorum { namespace util { using scorum::chain::genesis_state_type; using account_type = genesis_state_type::account_type; using steemit_bounty_account_type = genesis_state_type::steemit_bounty_account_type; using scorum::protocol::asset; using scorum::protocol::public_key_type; using genesis_account_info_item_type = fc::static_variant<account_type, steemit_bounty_account_type>; class genesis_mapper { public: genesis_mapper(); void reset(const genesis_state_type&); void update(const genesis_account_info_item_type&); void update(const std::string& name, const public_key_type&, const asset& scr_amount, const asset& sp_amount); void save(genesis_state_type&); private: void calculate_and_set_supply_rest(genesis_state_type& genesis); using genesis_account_info_item_map_by_type = std::map<int, genesis_account_info_item_type>; using genesis_account_info_items_type = std::map<std::string, genesis_account_info_item_map_by_type>; genesis_account_info_items_type _uniq_items; asset _accounts_supply = asset(0, SCORUM_SYMBOL); asset _steemit_bounty_accounts_supply = asset(0, SP_SYMBOL); }; } }
[ "andrew.masilevich@scorum.com" ]
andrew.masilevich@scorum.com
5dd2849e3bc77c03135eb50c025edc182ba92279
40295e5de2f76e184cbf3385d432f003ef45d611
/ChartShow_new/moc_chartshow.cpp
b8bba5ea2e06e5ae702efe91d411dd183ca34d78
[]
no_license
alive2202/pukh_chart_lnx
1e67409b066dc71b633547dbd47e5de2a5b85127
992d5102f3c4674642275a4db8ac6738d67ccf6e
refs/heads/master
2020-11-27T10:13:03.433931
2019-12-21T08:42:21
2019-12-21T08:42:21
229,398,114
0
0
null
null
null
null
UTF-8
C++
false
false
5,191
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'chartshow.h' ** ** Created: Wed Jan 9 16:23:39 2019 ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "chartshow.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'chartshow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_ChartShow[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 19, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 11, 10, 10, 10, 0x0a, 26, 10, 10, 10, 0x0a, 45, 10, 10, 10, 0x0a, 64, 10, 10, 10, 0x0a, 90, 10, 10, 10, 0x0a, 117, 10, 10, 10, 0x0a, 143, 10, 10, 10, 0x0a, 164, 10, 10, 10, 0x0a, 194, 10, 10, 10, 0x0a, 218, 10, 10, 10, 0x0a, 247, 10, 10, 10, 0x0a, 274, 10, 10, 10, 0x0a, 300, 10, 10, 10, 0x0a, 325, 10, 10, 10, 0x0a, 356, 10, 10, 10, 0x0a, 390, 10, 10, 10, 0x0a, 426, 10, 10, 10, 0x0a, 458, 10, 10, 10, 0x0a, 492, 10, 10, 10, 0x0a, 0 // eod }; static const char qt_meta_stringdata_ChartShow[] = { "ChartShow\0\0makeRandData()\0chbTData_clicked()\0" "btnClose_clicked()\0PushButtonStart_clicked()\0" "PushButtonOffAll_clicked()\0" "PushButtonOnAll_clicked()\0" "CheckBoxLK_clicked()\0PushButtonIshRazmDN_clicked()\0" "CheckBoxRegKK_clicked()\0" "PushButtonStartOsc_clicked()\0" "PushButtonAccept_clicked()\0" "PushButtonNoise_clicked()\0" "PushButtonSigs_clicked()\0" "PushButtonIshRazmOsc_clicked()\0" "ComboBoxPoints_activated(QString)\0" "SpinBoxCanals_valueChanged(QString)\0" "LineEditUp_textChanged(QString)\0" "LineEditDown_textChanged(QString)\0" "LineEditData_textChanged(QString)\0" }; void ChartShow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); ChartShow *_t = static_cast<ChartShow *>(_o); switch (_id) { case 0: _t->makeRandData(); break; case 1: _t->chbTData_clicked(); break; case 2: _t->btnClose_clicked(); break; case 3: _t->PushButtonStart_clicked(); break; case 4: _t->PushButtonOffAll_clicked(); break; case 5: _t->PushButtonOnAll_clicked(); break; case 6: _t->CheckBoxLK_clicked(); break; case 7: _t->PushButtonIshRazmDN_clicked(); break; case 8: _t->CheckBoxRegKK_clicked(); break; case 9: _t->PushButtonStartOsc_clicked(); break; case 10: _t->PushButtonAccept_clicked(); break; case 11: _t->PushButtonNoise_clicked(); break; case 12: _t->PushButtonSigs_clicked(); break; case 13: _t->PushButtonIshRazmOsc_clicked(); break; case 14: _t->ComboBoxPoints_activated((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 15: _t->SpinBoxCanals_valueChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 16: _t->LineEditUp_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 17: _t->LineEditDown_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 18: _t->LineEditData_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; default: ; } } } const QMetaObjectExtraData ChartShow::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject ChartShow::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_ChartShow, qt_meta_data_ChartShow, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &ChartShow::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *ChartShow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *ChartShow::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_ChartShow)) return static_cast<void*>(const_cast< ChartShow*>(this)); return QWidget::qt_metacast(_clname); } int ChartShow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 19) qt_static_metacall(this, _c, _id, _a); _id -= 19; } return _id; } QT_END_MOC_NAMESPACE
[ "pukhalexander@gmail.com" ]
pukhalexander@gmail.com
7f6a11197bac3e7b61a0a73dbdebf7aa4706137e
ec259beef8c61f42d2e9eb8e851cacd36cf5e391
/FinalProjectArchive/code/UserSettings.h
8d87d59359e1ee50d21f7b2c9835ec7feb9bf71f
[]
no_license
AlexanderJHill/Software-Engineering
4b19844b01f8b9213d6d884a808667d8ed9b2009
63ac151d57b60a752e9307cbc5a129861c1c2ff6
refs/heads/master
2021-01-01T16:45:27.099696
2015-05-09T20:41:26
2015-05-09T20:41:26
31,767,606
0
0
null
2015-04-27T14:59:25
2015-03-06T12:06:11
C++
UTF-8
C++
false
false
1,226
h
#ifndef _USERSETTINGS_H_ #define _USERSETTINGS_H_ //! \file usersettings.h //! \brief contains the users global simulation parameters. //! \brief contains the users global simulation parameters. class UserSettings{ public: UserSettings(); int getfisherNum(); /*!< Returns the number of Fishers to use in the simulation*/ int getfishLoc(); /*!< Returns the number of different locations */ int getfishType(); /*!< Returns the number of fish types.*/ int getfishPop(); /*!< Returns the inital population of fish when the simulation starts. */ int getfishTemp(); /*!< Returns the conditions: overcast, snow, rain. */ int getRuntime(); /*!< Returns the number of days to run the simulation. */ protected: int fisherNum; /*!< The number of Fishers to use in the simulation*/ int fishLoc; /*!< The number of different locations */ int fishType; /*!< The number of fish types. */ int fishPop; /*!< The inital population of fish when the simulation starts. */ int fishTemp; /*!< The conditions: overcast, snow, rain */ int runtime; /*!< The number of days to run the simulation */ }; #endif
[ "ahill6984@gmail.com" ]
ahill6984@gmail.com
9a3de840c4dbae563c3192d145700ff9cbffb07a
f8542f61530d7b8028e5a920c0b9a19036ba21c5
/Euler_336/Euler_336.cpp
4c02b77dd1b3161f8ab44ffcf5f0ed6da1311997
[]
no_license
datahaven/Project-Euler
f73bcdbd4d15818754d4d6648fa89a6d9b4fb1b5
74fc175fc6c9f18ae9a84585d563212f16ec6958
refs/heads/master
2020-04-21T09:55:25.767633
2019-07-13T21:55:27
2019-07-13T21:55:27
4,118,662
1
0
null
null
null
null
UTF-8
C++
false
false
2,137
cpp
// Project Euler 336 // Adrian Dale // 23/05/2011 // // Answer: CAGBIHEFJDK // // My code cheats a little in that I ran a first pass to find out what the maximum // maximix number is, then I run again counting solutions up to that number. // Not clever or especially efficient, but runs in a couple of seconds. // Not convinced that mixcount is bugfree for all inputs but it works for this puzzle. // Solution relies on next_permutation being able to run through 11! permutations // (ie 39 million) and check each one very easily on a modern computer. Took a few mins // to write code to check that this wouldn't take too long with a bit of string // manipulation for each value and after that it seemed sensible to proceed with this // approach. // Also helpful that next_permutation produces permutations in lexicographical order #include <iostream> #include <algorithm> #include <string> using namespace std; // NB pass by value as code messes with s int mixcount(string s) { string a = "ABCDEFGHIJK"; int mcnt = 0; for( int i=0; i<a.length()-2; ++i ) { // No flipping needed if coach is already in the right place if (a[i] == s[i]) continue; // Find next coach we need string::size_type mpos = s.find(a[i]); // and if it isn't at end of list ... if ( mpos != s.length()-1 ) { reverse( s.begin()+mpos, s.end() ); ++mcnt; reverse(s.begin()+i, s.end()); ++mcnt; } else { // next coach is at end of list reverse( s.begin(), s.end() ); ++mcnt; } } // Last two coaches need swapping if ( a[a.length()-2] != s[a.length()-2] ) { ++mcnt; // Don't need to actually swap the chars, but did it // like this so I could display string whilst testing // reverse(s.begin()+a.length()-2, s.end()); } return mcnt; } int main() { string s = "ABCDEFGHIJK"; int maxmc = 0; int pcnt = 0; do { int mc = mixcount(s); maxmc = max(maxmc, mc); if ( mc == 19 ) // value calculated in previous run { ++pcnt; if ( pcnt == 2011 ) break; } } while (next_permutation( s.begin(), s.end() ) ); cout << "maxmc=" << maxmc << endl; cout << s << endl; return 0; }
[ "adrian@adriandale.com" ]
adrian@adriandale.com
c486164c50cb55c7a4fda2ad991bc89e6abf1ea3
1c9b78abe2d53d4fc2e013bae5596e2449e395dd
/18_String_Process/18_String_Process.ino
148270044c077721a1b1aa43d330c5902ca4bf42
[]
no_license
Altium-Designer-Projects/ESP3212-WS2812
1b5ee2fa68de3a727eec8687f8c157e733e9b172
e04e2206ed840932841aaabd6032c337f485d550
refs/heads/master
2022-11-13T01:04:09.726544
2020-06-27T11:53:13
2020-06-27T11:53:13
274,913,359
1
0
null
null
null
null
UTF-8
C++
false
false
3,364
ino
#include "WiFi.h" #include "ESPAsyncWebServer.h" #include "index.h" #include <WebSocketsServer.h> /* Hello I design developer tools for embedded electronic systems. You can buy my projects design files. https://www.altiumdesignerprojects.com */ AsyncWebServer server(80); WebSocketsServer webSocket = WebSocketsServer(81); const char* ssid = "TP-LINK-MCU"; const char* password = "15253545"; String payloadString = ""; // buffer bool bufferComplete = false; // whether the string is complete String strPart0 = ""; String strPart1 = ""; word firstChar = 0; word secondChar = 0; void setup(){ Serial.begin(115200); payloadString.reserve(256); WiFi.begin(ssid,password); while(WiFi.status() != WL_CONNECTED){ Serial.print("."); delay(500); } Serial.println(""); Serial.print("IP Address: "); Serial.println(WiFi.localIP()); // Route for root / web page server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/html", indexPage); }); server.begin(); webSocket.begin(); webSocket.onEvent(webSocketEvent); } void loop(){ webSocket.loop(); if(bufferComplete == true){ //payloadString = String(payloadBuffer); Serial.println(payloadString); if(payloadString.indexOf("?requestA") > -1){ // requestA&hello# firstChar = payloadString.indexOf('&'); secondChar = payloadString.indexOf('#'); strPart0 = payloadString.substring(firstChar + 1, secondChar); Serial.println("strPart0 ... " + strPart0); } if(payloadString.indexOf("?requestB") > -1){ // requestB&world* firstChar = payloadString.indexOf('&'); secondChar = payloadString.indexOf('*'); strPart1 = payloadString.substring(firstChar + 1, secondChar); Serial.println("strPart1 ... " + strPart1); } payloadString = ""; // clear the string: bufferComplete = false; } } // loop void webSocketEvent(uint8_t client_num, WStype_t type, uint8_t * payload, size_t length){ switch(type){ // Figure out the type of WebSocket event case WStype_DISCONNECTED: // Client has disconnected Serial.printf("..[%u] Disconnected!\n", client_num); // [0] Disconnected! sayfayı kapattığımız zaman break; case WStype_CONNECTED: // New client has connected { IPAddress ip = webSocket.remoteIP(client_num); // bağlanan ip yi öğrendik Serial.printf("..[%u] Connection from ", client_num); // [0] Connection from 192.168.2.103 Serial.println(ip.toString()); } break; case WStype_TEXT: // Handle text messages from client // gelen data //Serial.printf("..[%u] Received text: %s\n", client_num, payload); // Print out raw message if(payload[0] == '?'){ payloadString = (char *)payload; bufferComplete = true; } break; // For everything else: do nothing case WStype_BIN: case WStype_ERROR: case WStype_FRAGMENT_TEXT_START: case WStype_FRAGMENT_BIN_START: case WStype_FRAGMENT: case WStype_FRAGMENT_FIN: default: break; } }
[ "noreply@github.com" ]
Altium-Designer-Projects.noreply@github.com
54ad0d10779dfcbc8509a28b21650256e9850955
eac0bb6459c9d8a2c725263e3352c80e8a102d48
/src/s390/assembler-s390.h
b916884a544c0071031dedfa4594b3673756b6ad
[ "BSD-3-Clause", "bzip2-1.0.6", "SunPro" ]
permissive
Yafei5515/v8
cf3b00daa7cf9a44e2c23477f13c8e33c4b946ac
f1e04dbc0ad5eb6e593735ba98a3bf353af177b8
refs/heads/master
2020-04-14T23:03:22.174990
2019-01-05T03:08:28
2019-01-05T03:49:20
164,188,391
2
0
null
null
null
null
UTF-8
C++
false
false
58,326
h
// Copyright (c) 1994-2006 Sun Microsystems Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // - Redistribution 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 Sun Microsystems or the names of 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. // The original source code covered by the above license above has been // modified significantly by Google Inc. // Copyright 2014 the V8 project authors. All rights reserved. // A light-weight S390 Assembler // Generates user mode instructions for z/Architecture #ifndef V8_S390_ASSEMBLER_S390_H_ #define V8_S390_ASSEMBLER_S390_H_ #include <stdio.h> #if V8_HOST_ARCH_S390 // elf.h include is required for auxv check for STFLE facility used // for hardware detection, which is sensible only on s390 hosts. #include <elf.h> #endif #include <fcntl.h> #include <unistd.h> #include <vector> #include "src/assembler.h" #include "src/external-reference.h" #include "src/label.h" #include "src/objects/smi.h" #include "src/s390/constants-s390.h" #include "src/s390/register-s390.h" #define ABI_USES_FUNCTION_DESCRIPTORS 0 #define ABI_PASSES_HANDLES_IN_REGS 1 // ObjectPair is defined under runtime/runtime-util.h. // On 31-bit, ObjectPair == uint64_t. ABI dictates long long // be returned with the lower addressed half in r2 // and the higher addressed half in r3. (Returns in Regs) // On 64-bit, ObjectPair is a Struct. ABI dictaes Structs be // returned in a storage buffer allocated by the caller, // with the address of this buffer passed as a hidden // argument in r2. (Does NOT return in Regs) // For x86 linux, ObjectPair is returned in registers. #if V8_TARGET_ARCH_S390X #define ABI_RETURNS_OBJECTPAIR_IN_REGS 0 #else #define ABI_RETURNS_OBJECTPAIR_IN_REGS 1 #endif #define ABI_CALL_VIA_IP 1 #define INSTR_AND_DATA_CACHE_COHERENCY LWSYNC namespace v8 { namespace internal { // ----------------------------------------------------------------------------- // Machine instruction Operands // Class Operand represents a shifter operand in data processing instructions // defining immediate numbers and masks class Operand { public: // immediate V8_INLINE explicit Operand(intptr_t immediate, RelocInfo::Mode rmode = RelocInfo::NONE) : rmode_(rmode) { value_.immediate = immediate; } V8_INLINE static Operand Zero() { return Operand(static_cast<intptr_t>(0)); } V8_INLINE explicit Operand(const ExternalReference& f) : rmode_(RelocInfo::EXTERNAL_REFERENCE) { value_.immediate = static_cast<intptr_t>(f.address()); } explicit Operand(Handle<HeapObject> handle); V8_INLINE explicit Operand(Smi value) : rmode_(RelocInfo::NONE) { value_.immediate = static_cast<intptr_t>(value.ptr()); } // rm V8_INLINE explicit Operand(Register rm); static Operand EmbeddedNumber(double value); // Smi or HeapNumber static Operand EmbeddedStringConstant(const StringConstantBase* str); // Return true if this is a register operand. V8_INLINE bool is_reg() const { return rm_.is_valid(); } bool must_output_reloc_info(const Assembler* assembler) const; inline intptr_t immediate() const { DCHECK(!rm_.is_valid()); DCHECK(!is_heap_object_request()); return value_.immediate; } HeapObjectRequest heap_object_request() const { DCHECK(is_heap_object_request()); return value_.heap_object_request; } inline void setBits(int n) { value_.immediate = (static_cast<uint32_t>(value_.immediate) << (32 - n)) >> (32 - n); } Register rm() const { return rm_; } bool is_heap_object_request() const { DCHECK_IMPLIES(is_heap_object_request_, !rm_.is_valid()); DCHECK_IMPLIES(is_heap_object_request_, rmode_ == RelocInfo::EMBEDDED_OBJECT || rmode_ == RelocInfo::CODE_TARGET); return is_heap_object_request_; } RelocInfo::Mode rmode() const { return rmode_; } private: Register rm_ = no_reg; union Value { Value() {} HeapObjectRequest heap_object_request; // if is_heap_object_request_ intptr_t immediate; // otherwise } value_; // valid if rm_ == no_reg bool is_heap_object_request_ = false; RelocInfo::Mode rmode_; friend class Assembler; friend class MacroAssembler; }; typedef int32_t Disp; // Class MemOperand represents a memory operand in load and store instructions // On S390, we have various flavours of memory operands: // 1) a base register + 16 bit unsigned displacement // 2) a base register + index register + 16 bit unsigned displacement // 3) a base register + index register + 20 bit signed displacement class MemOperand { public: explicit MemOperand(Register rx, Disp offset = 0); explicit MemOperand(Register rx, Register rb, Disp offset = 0); int32_t offset() const { return offset_; } uint32_t getDisplacement() const { return offset(); } // Base register Register rb() const { DCHECK(baseRegister != no_reg); return baseRegister; } Register getBaseRegister() const { return rb(); } // Index Register Register rx() const { DCHECK(indexRegister != no_reg); return indexRegister; } Register getIndexRegister() const { return rx(); } private: Register baseRegister; // base Register indexRegister; // index int32_t offset_; // offset friend class Assembler; }; class DeferredRelocInfo { public: DeferredRelocInfo() {} DeferredRelocInfo(int position, RelocInfo::Mode rmode, intptr_t data) : position_(position), rmode_(rmode), data_(data) {} int position() const { return position_; } RelocInfo::Mode rmode() const { return rmode_; } intptr_t data() const { return data_; } private: int position_; RelocInfo::Mode rmode_; intptr_t data_; }; class V8_EXPORT_PRIVATE Assembler : public AssemblerBase { public: // Create an assembler. Instructions and relocation information are emitted // into a buffer, with the instructions starting from the beginning and the // relocation information starting from the end of the buffer. See CodeDesc // for a detailed comment on the layout (globals.h). // // If the provided buffer is nullptr, the assembler allocates and grows its // own buffer, and buffer_size determines the initial buffer size. The buffer // is owned by the assembler and deallocated upon destruction of the // assembler. // // If the provided buffer is not nullptr, the assembler uses the provided // buffer for code generation and assumes its size to be buffer_size. If the // buffer is too small, a fatal error occurs. No deallocation of the buffer is // done upon destruction of the assembler. Assembler(const AssemblerOptions& options, void* buffer, int buffer_size); virtual ~Assembler() {} // GetCode emits any pending (non-emitted) code and fills the descriptor // desc. GetCode() is idempotent; it returns the same result if no other // Assembler functions are invoked in between GetCode() calls. void GetCode(Isolate* isolate, CodeDesc* desc); // Label operations & relative jumps (PPUM Appendix D) // // Takes a branch opcode (cc) and a label (L) and generates // either a backward branch or a forward branch and links it // to the label fixup chain. Usage: // // Label L; // unbound label // j(cc, &L); // forward branch to unbound label // bind(&L); // bind label to the current pc // j(cc, &L); // backward branch to bound label // bind(&L); // illegal: a label may be bound only once // // Note: The same Label can be used for forward and backward branches // but it may be bound only once. void bind(Label* L); // binds an unbound label L to the current code position // Links a label at the current pc_offset(). If already bound, returns the // bound position. If already linked, returns the position of the prior link. // Otherwise, returns the current pc_offset(). int link(Label* L); // Determines if Label is bound and near enough so that a single // branch instruction can be used to reach it. bool is_near(Label* L, Condition cond); // Returns the branch offset to the given label from the current code position // Links the label to the current position if it is still unbound int branch_offset(Label* L) { return link(L) - pc_offset(); } // Puts a labels target address at the given position. // The high 8 bits are set to zero. void label_at_put(Label* L, int at_offset); void load_label_offset(Register r1, Label* L); // Read/Modify the code target address in the branch/call instruction at pc. // The isolate argument is unused (and may be nullptr) when skipping flushing. V8_INLINE static Address target_address_at(Address pc, Address constant_pool); V8_INLINE static void set_target_address_at( Address pc, Address constant_pool, Address target, ICacheFlushMode icache_flush_mode = FLUSH_ICACHE_IF_NEEDED); // Return the code target address at a call site from the return address // of that call in the instruction stream. inline static Address target_address_from_return_address(Address pc); // Given the address of the beginning of a call, return the address // in the instruction stream that the call will return to. V8_INLINE static Address return_address_from_call_start(Address pc); inline Handle<Object> code_target_object_handle_at(Address pc); // This sets the branch destination. // This is for calls and branches within generated code. inline static void deserialization_set_special_target_at( Address instruction_payload, Code code, Address target); // Get the size of the special target encoded at 'instruction_payload'. inline static int deserialization_special_target_size( Address instruction_payload); // This sets the internal reference at the pc. inline static void deserialization_set_target_internal_reference_at( Address pc, Address target, RelocInfo::Mode mode = RelocInfo::INTERNAL_REFERENCE); // Here we are patching the address in the IIHF/IILF instruction pair. // These values are used in the serialization process and must be zero for // S390 platform, as Code, Embedded Object or External-reference pointers // are split across two consecutive instructions and don't exist separately // in the code, so the serializer should not step forwards in memory after // a target is resolved and written. static constexpr int kSpecialTargetSize = 0; // Number of bytes for instructions used to store pointer sized constant. #if V8_TARGET_ARCH_S390X static constexpr int kBytesForPtrConstant = 12; // IIHF + IILF #else static constexpr int kBytesForPtrConstant = 6; // IILF #endif // Distance between the instruction referring to the address of the call // target and the return address. // Offset between call target address and return address // for BRASL calls // Patch will be appiled to other FIXED_SEQUENCE call static constexpr int kCallTargetAddressOffset = 6; // --------------------------------------------------------------------------- // Code generation template <class T, int size, int lo, int hi> inline T getfield(T value) { DCHECK(lo < hi); DCHECK_GT(size, 0); int mask = hi - lo; int shift = size * 8 - hi; uint32_t mask_value = (mask == 32) ? 0xffffffff : (1 << mask) - 1; return (value & mask_value) << shift; } #define DECLARE_S390_RIL_AB_INSTRUCTIONS(name, op_name, op_value) \ template <class R1> \ inline void name(R1 r1, const Operand& i2) { \ ril_format(op_name, r1.code(), i2.immediate()); \ } #define DECLARE_S390_RIL_C_INSTRUCTIONS(name, op_name, op_value) \ inline void name(Condition m1, const Operand& i2) { \ ril_format(op_name, m1, i2.immediate()); \ } inline void ril_format(Opcode opcode, int f1, int f2) { uint32_t op1 = opcode >> 4; uint32_t op2 = opcode & 0xf; emit6bytes( getfield<uint64_t, 6, 0, 8>(op1) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(op2) | getfield<uint64_t, 6, 16, 48>(f2)); } S390_RIL_A_OPCODE_LIST(DECLARE_S390_RIL_AB_INSTRUCTIONS) S390_RIL_B_OPCODE_LIST(DECLARE_S390_RIL_AB_INSTRUCTIONS) S390_RIL_C_OPCODE_LIST(DECLARE_S390_RIL_C_INSTRUCTIONS) #undef DECLARE_S390_RIL_AB_INSTRUCTIONS #undef DECLARE_S390_RIL_C_INSTRUCTIONS #define DECLARE_S390_RR_INSTRUCTIONS(name, op_name, op_value) \ inline void name(Register r1, Register r2) { \ rr_format(op_name, r1.code(), r2.code()); \ } \ inline void name(DoubleRegister r1, DoubleRegister r2) { \ rr_format(op_name, r1.code(), r2.code()); \ } \ inline void name(Condition m1, Register r2) { \ rr_format(op_name, m1, r2.code()); \ } inline void rr_format(Opcode opcode, int f1, int f2) { emit2bytes(getfield<uint16_t, 2, 0, 8>(opcode) | getfield<uint16_t, 2, 8, 12>(f1) | getfield<uint16_t, 2, 12, 16>(f2)); } S390_RR_OPCODE_LIST(DECLARE_S390_RR_INSTRUCTIONS) #undef DECLARE_S390_RR_INSTRUCTIONS #define DECLARE_S390_RRD_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2, class R3> \ inline void name(R1 r1, R3 r3, R2 r2) { \ rrd_format(op_name, r1.code(), r3.code(), r2.code()); \ } inline void rrd_format(Opcode opcode, int f1, int f2, int f3) { emit4bytes(getfield<uint32_t, 4, 0, 16>(opcode) | getfield<uint32_t, 4, 16, 20>(f1) | getfield<uint32_t, 4, 24, 28>(f2) | getfield<uint32_t, 4, 28, 32>(f3)); } S390_RRD_OPCODE_LIST(DECLARE_S390_RRD_INSTRUCTIONS) #undef DECLARE_S390_RRD_INSTRUCTIONS #define DECLARE_S390_RRE_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2> \ inline void name(R1 r1, R2 r2) { \ rre_format(op_name, r1.code(), r2.code()); \ } inline void rre_format(Opcode opcode, int f1, int f2) { emit4bytes(getfield<uint32_t, 4, 0, 16>(opcode) | getfield<uint32_t, 4, 24, 28>(f1) | getfield<uint32_t, 4, 28, 32>(f2)); } S390_RRE_OPCODE_LIST(DECLARE_S390_RRE_INSTRUCTIONS) // Special format void lzdr(DoubleRegister r1) { rre_format(LZDR, r1.code(), 0); } #undef DECLARE_S390_RRE_INSTRUCTIONS #define DECLARE_S390_RX_INSTRUCTIONS(name, op_name, op_value) \ template <class R1> \ inline void name(R1 r1, Register x2, Register b2, const Operand& d2) { \ rx_format(op_name, r1.code(), x2.code(), b2.code(), \ d2.immediate()); \ } \ template <class R1> \ inline void name(R1 r1, const MemOperand& opnd) { \ name(r1, opnd.getIndexRegister(), opnd.getBaseRegister(), \ Operand(opnd.getDisplacement())); \ } inline void rx_format(Opcode opcode, int f1, int f2, int f3, int f4) { DCHECK(is_uint8(opcode)); DCHECK(is_uint12(f4)); emit4bytes(getfield<uint32_t, 4, 0, 8>(opcode) | getfield<uint32_t, 4, 8, 12>(f1) | getfield<uint32_t, 4, 12, 16>(f2) | getfield<uint32_t, 4, 16, 20>(f3) | getfield<uint32_t, 4, 20, 32>(f4)); } S390_RX_A_OPCODE_LIST(DECLARE_S390_RX_INSTRUCTIONS) void bc(Condition cond, const MemOperand& opnd) { bc(cond, opnd.getIndexRegister(), opnd.getBaseRegister(), Operand(opnd.getDisplacement())); } void bc(Condition cond, Register x2, Register b2, const Operand& d2) { rx_format(BC, cond, x2.code(), b2.code(), d2.immediate()); } #undef DECLARE_S390_RX_INSTRUCTIONS #define DECLARE_S390_RXY_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2> \ inline void name(R1 r1, R2 r2, Register b2, const Operand& d2) { \ rxy_format(op_name, r1.code(), r2.code(), b2.code(), d2.immediate()); \ } \ template <class R1> \ inline void name(R1 r1, const MemOperand& opnd) { \ name(r1, opnd.getIndexRegister(), opnd.getBaseRegister(), \ Operand(opnd.getDisplacement())); \ } inline void rxy_format(Opcode opcode, int f1, int f2, int f3, int f4) { DCHECK(is_uint16(opcode)); DCHECK(is_int20(f4)); emit6bytes(getfield<uint64_t, 6, 0, 8>(opcode >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4 & 0x0fff) | getfield<uint64_t, 6, 32, 40>(f4 >> 12) | getfield<uint64_t, 6, 40, 48>(opcode & 0x00ff)); } S390_RXY_A_OPCODE_LIST(DECLARE_S390_RXY_INSTRUCTIONS) void pfd(Condition cond, const MemOperand& opnd) { pfd(cond, opnd.getIndexRegister(), opnd.getBaseRegister(), Operand(opnd.getDisplacement())); } void pfd(Condition cond, Register x2, Register b2, const Operand& d2) { rxy_format(PFD, cond, x2.code(), b2.code(), d2.immediate()); } #undef DECLARE_S390_RXY_INSTRUCTIONS inline void rsy_format(Opcode op, int f1, int f2, int f3, int f4) { DCHECK(is_int20(f4)); DCHECK(is_uint16(op)); uint64_t code = (getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4 & 0x0fff) | getfield<uint64_t, 6, 32, 40>(f4 >> 12) | getfield<uint64_t, 6, 40, 48>(op & 0xff)); emit6bytes(code); } #define DECLARE_S390_RSY_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, Register b2, \ const Operand& d2 = Operand::Zero()) { \ rsy_format(op_name, r1.code(), r3.code(), b2.code(), d2.immediate()); \ } \ void name(Register r1, Register r3, Operand d2) { \ name(r1, r3, r0, d2); \ } \ void name(Register r1, Register r3, const MemOperand& opnd) { \ name(r1, r3, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_RSY_A_OPCODE_LIST(DECLARE_S390_RSY_A_INSTRUCTIONS); #undef DECLARE_S390_RSY_A_INSTRUCTIONS #define DECLARE_S390_RSY_B_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m3, Register b2, const Operand& d2) { \ rsy_format(op_name, r1.code(), m3, b2.code(), d2.immediate()); \ } \ void name(Register r1, Condition m3, const MemOperand& opnd) { \ name(r1, m3, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_RSY_B_OPCODE_LIST(DECLARE_S390_RSY_B_INSTRUCTIONS); #undef DECLARE_S390_RSY_B_INSTRUCTIONS inline void rs_format(Opcode op, int f1, int f2, int f3, const int f4) { uint32_t code = getfield<uint32_t, 4, 0, 8>(op) | getfield<uint32_t, 4, 8, 12>(f1) | getfield<uint32_t, 4, 12, 16>(f2) | getfield<uint32_t, 4, 16, 20>(f3) | getfield<uint32_t, 4, 20, 32>(f4); emit4bytes(code); } #define DECLARE_S390_RS_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, Register b2, const Operand& d2) { \ rs_format(op_name, r1.code(), r3.code(), b2.code(), d2.immediate()); \ } \ void name(Register r1, Register r3, const MemOperand& opnd) { \ name(r1, r3, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_RS_A_OPCODE_LIST(DECLARE_S390_RS_A_INSTRUCTIONS); #undef DECLARE_S390_RS_A_INSTRUCTIONS #define DECLARE_S390_RS_B_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m3, Register b2, const Operand& d2) { \ rs_format(op_name, r1.code(), m3, b2.code(), d2.immediate()); \ } \ void name(Register r1, Condition m3, const MemOperand& opnd) { \ name(r1, m3, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_RS_B_OPCODE_LIST(DECLARE_S390_RS_B_INSTRUCTIONS); #undef DECLARE_S390_RS_B_INSTRUCTIONS #define DECLARE_S390_RS_SHIFT_FORMAT(name, opcode) \ void name(Register r1, Register r2, const Operand& opnd = \ Operand::Zero()) { \ DCHECK(r2 != r0); \ rs_format(opcode, r1.code(), r0.code(), r2.code(), opnd.immediate()); \ } \ void name(Register r1, const Operand& opnd) { \ rs_format(opcode, r1.code(), r0.code(), r0.code(), opnd.immediate()); \ } DECLARE_S390_RS_SHIFT_FORMAT(sll, SLL) DECLARE_S390_RS_SHIFT_FORMAT(srl, SRL) DECLARE_S390_RS_SHIFT_FORMAT(sla, SLA) DECLARE_S390_RS_SHIFT_FORMAT(sra, SRA) DECLARE_S390_RS_SHIFT_FORMAT(sldl, SLDL) DECLARE_S390_RS_SHIFT_FORMAT(srda, SRDA) DECLARE_S390_RS_SHIFT_FORMAT(srdl, SRDL) #undef DECLARE_S390_RS_SHIFT_FORMAT inline void rxe_format(Opcode op, int f1, int f2, int f3, int f4, int f5 = 0) { DCHECK(is_uint12(f4)); DCHECK(is_uint16(op)); uint64_t code = (getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4 & 0x0fff) | getfield<uint64_t, 6, 32, 36>(f5) | getfield<uint64_t, 6, 40, 48>(op & 0xff)); emit6bytes(code); } #define DECLARE_S390_RXE_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register x2, Register b2, const Operand& d2, \ Condition m3 = static_cast<Condition>(0)) { \ rxe_format(op_name, r1.code(), x2.code(), b2.code(), d2.immediate(), \ m3); \ } \ template<class _R1Type> \ void name(_R1Type r1, const MemOperand& opnd) { \ name(Register::from_code(r1.code()), opnd.rx(), opnd.rb(), \ Operand(opnd.offset())); \ } S390_RXE_OPCODE_LIST(DECLARE_S390_RXE_INSTRUCTIONS); #undef DECLARE_S390_RXE_INSTRUCTIONS inline void ri_format(Opcode opcode, int f1, int f2) { uint32_t op1 = opcode >> 4; uint32_t op2 = opcode & 0xf; emit4bytes(getfield<uint32_t, 4, 0, 8>(op1) | getfield<uint32_t, 4, 8, 12>(f1) | getfield<uint32_t, 4, 12, 16>(op2) | getfield<uint32_t, 4, 16, 32>(f2)); } #define DECLARE_S390_RI_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r, const Operand& i2) { \ DCHECK(is_uint12(op_name)); \ DCHECK(is_uint16(i2.immediate()) || is_int16(i2.immediate())); \ ri_format(op_name, r.code(), i2.immediate()); \ } S390_RI_A_OPCODE_LIST(DECLARE_S390_RI_A_INSTRUCTIONS); #undef DECLARE_S390_RI_A_INSTRUCTIONS #define DECLARE_S390_RI_B_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, const Operand& imm) { \ /* 2nd argument encodes # of halfwords, so divide by 2. */ \ int16_t numHalfwords = static_cast<int16_t>(imm.immediate()) / 2; \ Operand halfwordOp = Operand(numHalfwords); \ halfwordOp.setBits(16); \ ri_format(op_name, r1.code(), halfwordOp.immediate()); \ } S390_RI_B_OPCODE_LIST(DECLARE_S390_RI_B_INSTRUCTIONS); #undef DECLARE_S390_RI_B_INSTRUCTIONS #define DECLARE_S390_RI_C_INSTRUCTIONS(name, op_name, op_value) \ void name(Condition m, const Operand& i2) { \ DCHECK(is_uint12(op_name)); \ DCHECK(is_uint4(m)); \ DCHECK(op_name == BRC ? \ is_int16(i2.immediate()) : is_uint16(i2.immediate())); \ ri_format(op_name, m, i2.immediate()); \ } S390_RI_C_OPCODE_LIST(DECLARE_S390_RI_C_INSTRUCTIONS); #undef DECLARE_S390_RI_C_INSTRUCTIONS inline void rrf_format(Opcode op, int f1, int f2, int f3, int f4) { uint32_t code = getfield<uint32_t, 4, 0, 16>(op) | getfield<uint32_t, 4, 16, 20>(f1) | getfield<uint32_t, 4, 20, 24>(f2) | getfield<uint32_t, 4, 24, 28>(f3) | getfield<uint32_t, 4, 28, 32>(f4); emit4bytes(code); } #define DECLARE_S390_RRF_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m4, Register r2, Register r3) { \ rrf_format(op_name, r3.code(), m4, r1.code(), r2.code()); \ } \ void name(Register r1, Register r2, Register r3) { \ name(r1, Condition(0), r2, r3); \ } S390_RRF_A_OPCODE_LIST(DECLARE_S390_RRF_A_INSTRUCTIONS); #undef DECLARE_S390_RRF_A_INSTRUCTIONS #define DECLARE_S390_RRF_B_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m4, Register r2, Register r3) { \ rrf_format(op_name, r3.code(), m4, r1.code(), r2.code()); \ } \ void name(Register r1, Register r2, Register r3) { \ name(r1, Condition(0), r2, r3); \ } S390_RRF_B_OPCODE_LIST(DECLARE_S390_RRF_B_INSTRUCTIONS); #undef DECLARE_S390_RRF_B_INSTRUCTIONS #define DECLARE_S390_RRF_C_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2> \ void name(Condition m3, Condition m4, R1 r1, R2 r2) { \ rrf_format(op_name, m3, m4, r1.code(), r2.code()); \ } \ template <class R1, class R2> \ void name(Condition m3, R1 r1, R2 r2) { \ name(m3, Condition(0), r1, r2); \ } S390_RRF_C_OPCODE_LIST(DECLARE_S390_RRF_C_INSTRUCTIONS); #undef DECLARE_S390_RRF_C_INSTRUCTIONS #define DECLARE_S390_RRF_D_INSTRUCTIONS(name, op_name, op_value) \ template <class R1, class R2> \ void name(Condition m3, Condition m4, R1 r1, R2 r2) { \ rrf_format(op_name, m3, m4, r1.code(), r2.code()); \ } \ template <class R1, class R2> \ void name(Condition m3, R1 r1, R2 r2) { \ name(m3, Condition(0), r1, r2); \ } S390_RRF_D_OPCODE_LIST(DECLARE_S390_RRF_D_INSTRUCTIONS); #undef DECLARE_S390_RRF_D_INSTRUCTIONS #define DECLARE_S390_RRF_E_INSTRUCTIONS(name, op_name, op_value) \ template <class M3, class M4, class R1, class R2> \ void name(M3 m3, M4 m4, R1 r1, R2 r2) { \ rrf_format(op_name, m3, m4, r1.code(), r2.code()); \ } \ template <class M3, class R1, class R2> \ void name(M3 m3, R1 r1, R2 r2) { \ name(m3, Condition(0), r1, r2); \ } S390_RRF_E_OPCODE_LIST(DECLARE_S390_RRF_E_INSTRUCTIONS); #undef DECLARE_S390_RRF_E_INSTRUCTIONS enum FIDBRA_FLAGS { FIDBRA_CURRENT_ROUNDING_MODE = 0, FIDBRA_ROUND_TO_NEAREST_AWAY_FROM_0 = 1, // ... FIDBRA_ROUND_TOWARD_0 = 5, FIDBRA_ROUND_TOWARD_POS_INF = 6, FIDBRA_ROUND_TOWARD_NEG_INF = 7 }; inline void rsi_format(Opcode op, int f1, int f2, int f3) { DCHECK(is_uint8(op)); DCHECK(is_uint16(f3) || is_int16(f3)); uint32_t code = getfield<uint32_t, 4, 0, 8>(op) | getfield<uint32_t, 4, 8, 12>(f1) | getfield<uint32_t, 4, 12, 16>(f2) | getfield<uint32_t, 4, 16, 32>(f3); emit4bytes(code); } #define DECLARE_S390_RSI_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, const Operand& i2) { \ rsi_format(op_name, r1.code(), r3.code(), i2.immediate()); \ } S390_RSI_OPCODE_LIST(DECLARE_S390_RSI_INSTRUCTIONS); #undef DECLARE_S390_RSI_INSTRUCTIONS inline void rsl_format(Opcode op, uint16_t f1, int f2, int f3, int f4, int f5) { DCHECK(is_uint16(op)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 16>(f1) | getfield<uint64_t, 6, 16, 20>(f2) | getfield<uint64_t, 6, 20, 32>(f3) | getfield<uint64_t, 6, 32, 36>(f4) | getfield<uint64_t, 6, 36, 40>(f5) | getfield<uint64_t, 6, 40, 48>(op & 0x00FF); emit6bytes(code); } #define DECLARE_S390_RSL_A_INSTRUCTIONS(name, op_name, op_value) \ void name(const Operand& l1, Register b1, const Operand& d1) { \ uint16_t L = static_cast<uint16_t>(l1.immediate() << 8); \ rsl_format(op_name, L, b1.code(), d1.immediate(), 0, 0); \ } S390_RSL_A_OPCODE_LIST(DECLARE_S390_RSL_A_INSTRUCTIONS); #undef DECLARE_S390_RSL_A_INSTRUCTIONS #define DECLARE_S390_RSL_B_INSTRUCTIONS(name, op_name, op_value) \ void name(const Operand& l2, Register b2, const Operand& d2, \ Register r1, Condition m3) { \ uint16_t L = static_cast<uint16_t>(l2.immediate()); \ rsl_format(op_name, L, b2.code(), d2.immediate(), r1.code(), m3); \ } S390_RSL_B_OPCODE_LIST(DECLARE_S390_RSL_B_INSTRUCTIONS); #undef DECLARE_S390_RSL_B_INSTRUCTIONS inline void s_format(Opcode op, int f1, int f2) { DCHECK_NE(op & 0xff00, 0); DCHECK(is_uint12(f2)); uint32_t code = getfield<uint32_t, 4, 0, 16>(op) | getfield<uint32_t, 4, 16, 20>(f1) | getfield<uint32_t, 4, 20, 32>(f2); emit4bytes(code); } #define DECLARE_S390_S_INSTRUCTIONS(name, op_name, op_value) \ void name(Register b1, const Operand& d2) { \ Opcode op = op_name; \ if ((op & 0xFF00) == 0) { \ op = (Opcode)(op << 8); \ } \ s_format(op, b1.code(), d2.immediate()); \ } \ void name(const MemOperand& opnd) { \ Operand d2 = Operand(opnd.getDisplacement()); \ name(opnd.getBaseRegister(), d2); \ } S390_S_OPCODE_LIST(DECLARE_S390_S_INSTRUCTIONS); #undef DECLARE_S390_S_INSTRUCTIONS inline void si_format(Opcode op, int f1, int f2, int f3) { uint32_t code = getfield<uint32_t, 4, 0, 8>(op) | getfield<uint32_t, 4, 8, 16>(f1) | getfield<uint32_t, 4, 16, 20>(f2) | getfield<uint32_t, 4, 20, 32>(f3); emit4bytes(code); } #define DECLARE_S390_SI_INSTRUCTIONS(name, op_name, op_value) \ void name(const Operand& i2, Register b1, const Operand& d1) { \ si_format(op_name, i2.immediate(), b1.code(), d1.immediate()); \ } \ void name(const MemOperand& opnd, const Operand& i2) { \ name(i2, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_SI_OPCODE_LIST(DECLARE_S390_SI_INSTRUCTIONS); #undef DECLARE_S390_SI_INSTRUCTIONS inline void siy_format(Opcode op, int f1, int f2, int f3) { DCHECK(is_uint20(f3) || is_int20(f3)); DCHECK(is_uint16(op)); DCHECK(is_uint8(f1) || is_int8(f1)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 16>(f1) | getfield<uint64_t, 6, 16, 20>(f2) | getfield<uint64_t, 6, 20, 32>(f3) | getfield<uint64_t, 6, 32, 40>(f3 >> 12) | getfield<uint64_t, 6, 40, 48>(op & 0x00FF); emit6bytes(code); } #define DECLARE_S390_SIY_INSTRUCTIONS(name, op_name, op_value) \ void name(const Operand& i2, Register b1, const Operand& d1) { \ siy_format(op_name, i2.immediate(), b1.code(), d1.immediate()); \ } \ void name(const MemOperand& opnd, const Operand& i2) { \ name(i2, opnd.getBaseRegister(), Operand(opnd.getDisplacement())); \ } S390_SIY_OPCODE_LIST(DECLARE_S390_SIY_INSTRUCTIONS); #undef DECLARE_S390_SIY_INSTRUCTIONS inline void rrs_format(Opcode op, int f1, int f2, int f3, int f4, int f5) { DCHECK(is_uint12(f4)); DCHECK(is_uint16(op)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4) | getfield<uint64_t, 6, 32, 36>(f5) | getfield<uint64_t, 6, 40, 48>(op & 0x00FF); emit6bytes(code); } #define DECLARE_S390_RRS_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r2, Register b4, const Operand& d4, \ Condition m3) { \ rrs_format(op_name, r1.code(), r2.code(), b4.code(), d4.immediate(), \ m3); \ } \ void name(Register r1, Register r2, Condition m3, \ const MemOperand& opnd) { \ name(r1, r2, opnd.getBaseRegister(), \ Operand(opnd.getDisplacement()), m3); \ } S390_RRS_OPCODE_LIST(DECLARE_S390_RRS_INSTRUCTIONS); #undef DECLARE_S390_RRS_INSTRUCTIONS inline void ris_format(Opcode op, int f1, int f2, int f3, int f4, int f5) { DCHECK(is_uint12(f3)); DCHECK(is_uint16(op)); DCHECK(is_uint8(f5)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op >> 8) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 20>(f3) | getfield<uint64_t, 6, 20, 32>(f4) | getfield<uint64_t, 6, 32, 40>(f5) | getfield<uint64_t, 6, 40, 48>(op & 0x00FF); emit6bytes(code); } #define DECLARE_S390_RIS_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Condition m3, Register b4, const Operand& d4, \ const Operand& i2) { \ ris_format(op_name, r1.code(), m3, b4.code(), d4.immediate(), \ i2.immediate()); \ } \ void name(Register r1, const Operand& i2, Condition m3, \ const MemOperand& opnd) { \ name(r1, m3, opnd.getBaseRegister(), \ Operand(opnd.getDisplacement()), i2); \ } S390_RIS_OPCODE_LIST(DECLARE_S390_RIS_INSTRUCTIONS); #undef DECLARE_S390_RIS_INSTRUCTIONS inline void sil_format(Opcode op, int f1, int f2, int f3) { DCHECK(is_uint12(f2)); DCHECK(is_uint16(op)); DCHECK(is_uint16(f3)); uint64_t code = getfield<uint64_t, 6, 0, 16>(op) | getfield<uint64_t, 6, 16, 20>(f1) | getfield<uint64_t, 6, 20, 32>(f2) | getfield<uint64_t, 6, 32, 48>(f3); emit6bytes(code); } #define DECLARE_S390_SIL_INSTRUCTIONS(name, op_name, op_value) \ void name(Register b1, const Operand& d1, const Operand& i2) { \ sil_format(op_name, b1.code(), d1.immediate(), i2.immediate()); \ } \ void name(const MemOperand& opnd, const Operand& i2) { \ name(opnd.getBaseRegister(), Operand(opnd.getDisplacement()), i2); \ } S390_SIL_OPCODE_LIST(DECLARE_S390_SIL_INSTRUCTIONS); #undef DECLARE_S390_SIL_INSTRUCTIONS inline void rie_d_format(Opcode opcode, int f1, int f2, int f3, int f4) { uint32_t op1 = opcode >> 8; uint32_t op2 = opcode & 0xff; uint64_t code = getfield<uint64_t, 6, 0, 8>(op1) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 32>(f3) | getfield<uint64_t, 6, 32, 40>(f4) | getfield<uint64_t, 6, 40, 48>(op2); emit6bytes(code); } #define DECLARE_S390_RIE_D_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, const Operand& i2) { \ rie_d_format(op_name, r1.code(), r3.code(), i2.immediate(), 0); \ } S390_RIE_D_OPCODE_LIST(DECLARE_S390_RIE_D_INSTRUCTIONS) #undef DECLARE_S390_RIE_D_INSTRUCTIONS inline void rie_e_format(Opcode opcode, int f1, int f2, int f3) { uint32_t op1 = opcode >> 8; uint32_t op2 = opcode & 0xff; uint64_t code = getfield<uint64_t, 6, 0, 8>(op1) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 32>(f3) | getfield<uint64_t, 6, 40, 48>(op2); emit6bytes(code); } #define DECLARE_S390_RIE_E_INSTRUCTIONS(name, op_name, op_value) \ void name(Register r1, Register r3, const Operand& i2) { \ rie_e_format(op_name, r1.code(), r3.code(), i2.immediate()); \ } S390_RIE_E_OPCODE_LIST(DECLARE_S390_RIE_E_INSTRUCTIONS) #undef DECLARE_S390_RIE_E_INSTRUCTIONS inline void rie_f_format(Opcode opcode, int f1, int f2, int f3, int f4, int f5) { uint32_t op1 = opcode >> 8; uint32_t op2 = opcode & 0xff; uint64_t code = getfield<uint64_t, 6, 0, 8>(op1) | getfield<uint64_t, 6, 8, 12>(f1) | getfield<uint64_t, 6, 12, 16>(f2) | getfield<uint64_t, 6, 16, 24>(f3) | getfield<uint64_t, 6, 24, 32>(f4) | getfield<uint64_t, 6, 32, 40>(f5) | getfield<uint64_t, 6, 40, 48>(op2); emit6bytes(code); } #define DECLARE_S390_RIE_F_INSTRUCTIONS(name, op_name, op_value) \ void name(Register dst, Register src, const Operand& startBit, \ const Operand& endBit, const Operand& shiftAmt) { \ DCHECK(is_uint8(startBit.immediate())); \ DCHECK(is_uint8(endBit.immediate())); \ DCHECK(is_uint8(shiftAmt.immediate())); \ rie_f_format(op_name, dst.code(), src.code(), startBit.immediate(), \ endBit.immediate(), shiftAmt.immediate()); \ } S390_RIE_F_OPCODE_LIST(DECLARE_S390_RIE_F_INSTRUCTIONS) #undef DECLARE_S390_RIE_F_INSTRUCTIONS inline void ss_a_format(Opcode op, int f1, int f2, int f3, int f4, int f5) { DCHECK(is_uint12(f5)); DCHECK(is_uint12(f3)); DCHECK(is_uint8(f1)); DCHECK(is_uint8(op)); uint64_t code = getfield<uint64_t, 6, 0, 8>(op) | getfield<uint64_t, 6, 8, 16>(f1) | getfield<uint64_t, 6, 16, 20>(f2) | getfield<uint64_t, 6, 20, 32>(f3) | getfield<uint64_t, 6, 32, 36>(f4) | getfield<uint64_t, 6, 36, 48>(f5); emit6bytes(code); } #define DECLARE_S390_SS_A_INSTRUCTIONS(name, op_name, op_value) \ void name(Register b1, const Operand& d1, Register b2, \ const Operand& d2, const Operand& length) { \ ss_a_format(op_name, length.immediate(), b1.code(), d1.immediate(), \ b2.code(), d2.immediate()); \ } \ void name(const MemOperand& opnd1, const MemOperand& opnd2, \ const Operand& length) { \ ss_a_format(op_name, length.immediate(), \ opnd1.getBaseRegister().code(), \ opnd1.getDisplacement(), opnd2.getBaseRegister().code(), \ opnd2.getDisplacement()); \ } S390_SS_A_OPCODE_LIST(DECLARE_S390_SS_A_INSTRUCTIONS) #undef DECLARE_S390_SS_A_INSTRUCTIONS // Helper for unconditional branch to Label with update to save register void b(Register r, Label* l) { int32_t halfwords = branch_offset(l) / 2; brasl(r, Operand(halfwords)); } // Conditional Branch Instruction - Generates either BRC / BRCL void branchOnCond(Condition c, int branch_offset, bool is_bound = false); // Helpers for conditional branch to Label void b(Condition cond, Label* l, Label::Distance dist = Label::kFar) { branchOnCond(cond, branch_offset(l), l->is_bound() || (dist == Label::kNear)); } void bc_short(Condition cond, Label* l, Label::Distance dist = Label::kFar) { b(cond, l, Label::kNear); } // Helpers for conditional branch to Label void beq(Label* l, Label::Distance dist = Label::kFar) { b(eq, l, dist); } void bne(Label* l, Label::Distance dist = Label::kFar) { b(ne, l, dist); } void blt(Label* l, Label::Distance dist = Label::kFar) { b(lt, l, dist); } void ble(Label* l, Label::Distance dist = Label::kFar) { b(le, l, dist); } void bgt(Label* l, Label::Distance dist = Label::kFar) { b(gt, l, dist); } void bge(Label* l, Label::Distance dist = Label::kFar) { b(ge, l, dist); } void b(Label* l, Label::Distance dist = Label::kFar) { b(al, l, dist); } void jmp(Label* l, Label::Distance dist = Label::kFar) { b(al, l, dist); } void bunordered(Label* l, Label::Distance dist = Label::kFar) { b(unordered, l, dist); } void bordered(Label* l, Label::Distance dist = Label::kFar) { b(ordered, l, dist); } // Helpers for conditional indirect branch off register void b(Condition cond, Register r) { bcr(cond, r); } void beq(Register r) { b(eq, r); } void bne(Register r) { b(ne, r); } void blt(Register r) { b(lt, r); } void ble(Register r) { b(le, r); } void bgt(Register r) { b(gt, r); } void bge(Register r) { b(ge, r); } void b(Register r) { b(al, r); } void jmp(Register r) { b(al, r); } void bunordered(Register r) { b(unordered, r); } void bordered(Register r) { b(ordered, r); } // wrappers around asm instr void brxh(Register dst, Register inc, Label* L) { int offset_halfwords = branch_offset(L) / 2; CHECK(is_int16(offset_halfwords)); brxh(dst, inc, Operand(offset_halfwords)); } void brxhg(Register dst, Register inc, Label* L) { int offset_halfwords = branch_offset(L) / 2; CHECK(is_int16(offset_halfwords)); brxhg(dst, inc, Operand(offset_halfwords)); } template <class R1, class R2> void ledbr(R1 r1, R2 r2) { ledbra(Condition(0), Condition(0), r1, r2); } template <class R1, class R2> void cdfbr(R1 r1, R2 r2) { cdfbra(Condition(0), Condition(0), r1, r2); } template <class R1, class R2> void cdgbr(R1 r1, R2 r2) { cdgbra(Condition(0), Condition(0), r1, r2); } template <class R1, class R2> void cegbr(R1 r1, R2 r2) { cegbra(Condition(0), Condition(0), r1, r2); } template <class R1, class R2> void cgebr(Condition m3, R1 r1, R2 r2) { cgebra(m3, Condition(0), r1, r2); } template <class R1, class R2> void cgdbr(Condition m3, R1 r1, R2 r2) { cgdbra(m3, Condition(0), r1, r2); } template <class R1, class R2> void cfdbr(Condition m3, R1 r1, R2 r2) { cfdbra(m3, Condition(0), r1, r2); } template <class R1, class R2> void cfebr(Condition m3, R1 r1, R2 r2) { cfebra(m3, Condition(0), r1, r2); } // --------------------------------------------------------------------------- // Code generation // Insert the smallest number of nop instructions // possible to align the pc offset to a multiple // of m. m must be a power of 2 (>= 4). void Align(int m); // Insert the smallest number of zero bytes possible to align the pc offset // to a mulitple of m. m must be a power of 2 (>= 2). void DataAlign(int m); // Aligns code to something that's optimal for a jump target for the platform. void CodeTargetAlign(); void breakpoint(bool do_print) { if (do_print) { PrintF("DebugBreak is inserted to %p\n", static_cast<void*>(pc_)); } #if V8_HOST_ARCH_64_BIT int64_t value = reinterpret_cast<uint64_t>(&v8::base::OS::DebugBreak); int32_t hi_32 = static_cast<int64_t>(value) >> 32; int32_t lo_32 = static_cast<int32_t>(value); iihf(r1, Operand(hi_32)); iilf(r1, Operand(lo_32)); #else iilf(r1, Operand(reinterpret_cast<uint32_t>(&v8::base::OS::DebugBreak))); #endif basr(r14, r1); } void call(Handle<Code> target, RelocInfo::Mode rmode); void jump(Handle<Code> target, RelocInfo::Mode rmode, Condition cond); // S390 instruction generation #define DECLARE_VRR_A_INSTRUCTIONS(name, opcode_name, opcode_value) \ void name(DoubleRegister v1, DoubleRegister v2, Condition m5, Condition m4, \ Condition m3) { \ uint64_t code = (static_cast<uint64_t>(opcode_value & 0xFF00)) * B32 | \ (static_cast<uint64_t>(v1.code())) * B36 | \ (static_cast<uint64_t>(v2.code())) * B32 | \ (static_cast<uint64_t>(m5 & 0xF)) * B20 | \ (static_cast<uint64_t>(m4 & 0xF)) * B16 | \ (static_cast<uint64_t>(m3 & 0xF)) * B12 | \ (static_cast<uint64_t>(opcode_value & 0x00FF)); \ emit6bytes(code); \ } S390_VRR_A_OPCODE_LIST(DECLARE_VRR_A_INSTRUCTIONS) #undef DECLARE_VRR_A_INSTRUCTIONS #define DECLARE_VRR_C_INSTRUCTIONS(name, opcode_name, opcode_value) \ void name(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3, \ Condition m6, Condition m5, Condition m4) { \ uint64_t code = (static_cast<uint64_t>(opcode_value & 0xFF00)) * B32 | \ (static_cast<uint64_t>(v1.code())) * B36 | \ (static_cast<uint64_t>(v2.code())) * B32 | \ (static_cast<uint64_t>(v3.code())) * B28 | \ (static_cast<uint64_t>(m6 & 0xF)) * B20 | \ (static_cast<uint64_t>(m5 & 0xF)) * B16 | \ (static_cast<uint64_t>(m4 & 0xF)) * B12 | \ (static_cast<uint64_t>(opcode_value & 0x00FF)); \ emit6bytes(code); \ } S390_VRR_C_OPCODE_LIST(DECLARE_VRR_C_INSTRUCTIONS) #undef DECLARE_VRR_C_INSTRUCTIONS // Single Element format void vfa(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3) { vfa(v1, v2, v3, static_cast<Condition>(0), static_cast<Condition>(8), static_cast<Condition>(3)); } void vfs(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3) { vfs(v1, v2, v3, static_cast<Condition>(0), static_cast<Condition>(8), static_cast<Condition>(3)); } void vfm(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3) { vfm(v1, v2, v3, static_cast<Condition>(0), static_cast<Condition>(8), static_cast<Condition>(3)); } void vfd(DoubleRegister v1, DoubleRegister v2, DoubleRegister v3) { vfd(v1, v2, v3, static_cast<Condition>(0), static_cast<Condition>(8), static_cast<Condition>(3)); } // Load Address Instructions void larl(Register r, Label* l); // Exception-generating instructions and debugging support void stop(const char* msg, Condition cond = al, int32_t code = kDefaultStopCode, CRegister cr = cr7); void bkpt(uint32_t imm16); // v5 and above // Different nop operations are used by the code generator to detect certain // states of the generated code. enum NopMarkerTypes { NON_MARKING_NOP = 0, GROUP_ENDING_NOP, DEBUG_BREAK_NOP, // IC markers. PROPERTY_ACCESS_INLINED, PROPERTY_ACCESS_INLINED_CONTEXT, PROPERTY_ACCESS_INLINED_CONTEXT_DONT_DELETE, // Helper values. LAST_CODE_MARKER, FIRST_IC_MARKER = PROPERTY_ACCESS_INLINED }; void nop(int type = 0); // 0 is the default non-marking type. void dumy(int r1, int x2, int b2, int d2); // Check the code size generated from label to here. int SizeOfCodeGeneratedSince(Label* label) { return pc_offset() - label->pos(); } // Record a deoptimization reason that can be used by a log or cpu profiler. // Use --trace-deopt to enable. void RecordDeoptReason(DeoptimizeReason reason, SourcePosition position, int id); // Writes a single byte or word of data in the code stream. Used // for inline tables, e.g., jump-tables. void db(uint8_t data); void dd(uint32_t data); void dq(uint64_t data); void dp(uintptr_t data); // Read/patch instructions SixByteInstr instr_at(int pos) { return Instruction::InstructionBits(buffer_ + pos); } template <typename T> void instr_at_put(int pos, T instr) { Instruction::SetInstructionBits<T>(buffer_ + pos, instr); } // Decodes instruction at pos, and returns its length int32_t instr_length_at(int pos) { return Instruction::InstructionLength(buffer_ + pos); } static SixByteInstr instr_at(byte* pc) { return Instruction::InstructionBits(pc); } static Condition GetCondition(Instr instr); static bool IsBranch(Instr instr); #if V8_TARGET_ARCH_S390X static bool Is64BitLoadIntoIP(SixByteInstr instr1, SixByteInstr instr2); #else static bool Is32BitLoadIntoIP(SixByteInstr instr); #endif static bool IsCmpRegister(Instr instr); static bool IsCmpImmediate(Instr instr); static bool IsNop(SixByteInstr instr, int type = NON_MARKING_NOP); // The code currently calls CheckBuffer() too often. This has the side // effect of randomly growing the buffer in the middle of multi-instruction // sequences. // // This function allows outside callers to check and grow the buffer void EnsureSpaceFor(int space_needed); void EmitRelocations(); void emit_label_addr(Label* label); public: byte* buffer_pos() const { return buffer_; } protected: int buffer_space() const { return reloc_info_writer.pos() - pc_; } // Decode instruction(s) at pos and return backchain to previous // label reference or kEndOfChain. int target_at(int pos); // Patch instruction(s) at pos to target target_pos (e.g. branch) void target_at_put(int pos, int target_pos, bool* is_branch = nullptr); // Record reloc info for current pc_ void RecordRelocInfo(RelocInfo::Mode rmode, intptr_t data = 0); private: // Avoid overflows for displacements etc. static const int kMaximalBufferSize = 512 * MB; // Code generation // The relocation writer's position is at least kGap bytes below the end of // the generated instructions. This is so that multi-instruction sequences do // not have to check for overflow. The same is true for writes of large // relocation info entries. static constexpr int kGap = 32; // Relocation info generation // Each relocation is encoded as a variable size value static constexpr int kMaxRelocSize = RelocInfoWriter::kMaxSize; RelocInfoWriter reloc_info_writer; std::vector<DeferredRelocInfo> relocations_; // The bound position, before this we cannot do instruction elimination. int last_bound_pos_; // Code emission void CheckBuffer() { if (buffer_space() <= kGap) { GrowBuffer(); } } void GrowBuffer(int needed = 0); inline void TrackBranch(); inline void UntrackBranch(); // Helper to emit the binary encoding of a 2 byte instruction void emit2bytes(uint16_t x) { CheckBuffer(); #if V8_TARGET_LITTLE_ENDIAN // We need to emit instructions in big endian format as disassembler / // simulator require the first byte of the instruction in order to decode // the instruction length. Swap the bytes. x = ((x & 0x00FF) << 8) | ((x & 0xFF00) >> 8); #endif *reinterpret_cast<uint16_t*>(pc_) = x; pc_ += 2; } // Helper to emit the binary encoding of a 4 byte instruction void emit4bytes(uint32_t x) { CheckBuffer(); #if V8_TARGET_LITTLE_ENDIAN // We need to emit instructions in big endian format as disassembler / // simulator require the first byte of the instruction in order to decode // the instruction length. Swap the bytes. x = ((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) | ((x & 0xFF000000) >> 24); #endif *reinterpret_cast<uint32_t*>(pc_) = x; pc_ += 4; } // Helper to emit the binary encoding of a 6 byte instruction void emit6bytes(uint64_t x) { CheckBuffer(); #if V8_TARGET_LITTLE_ENDIAN // We need to emit instructions in big endian format as disassembler / // simulator require the first byte of the instruction in order to decode // the instruction length. Swap the bytes. x = (static_cast<uint64_t>(x & 0xFF) << 40) | (static_cast<uint64_t>((x >> 8) & 0xFF) << 32) | (static_cast<uint64_t>((x >> 16) & 0xFF) << 24) | (static_cast<uint64_t>((x >> 24) & 0xFF) << 16) | (static_cast<uint64_t>((x >> 32) & 0xFF) << 8) | (static_cast<uint64_t>((x >> 40) & 0xFF)); x |= (*reinterpret_cast<uint64_t*>(pc_) >> 48) << 48; #else // We need to pad two bytes of zeros in order to get the 6-bytes // stored from low address. x = x << 16; x |= *reinterpret_cast<uint64_t*>(pc_) & 0xFFFF; #endif // It is safe to store 8-bytes, as CheckBuffer() guarantees we have kGap // space left over. *reinterpret_cast<uint64_t*>(pc_) = x; pc_ += 6; } // Labels void print(Label* L); int max_reach_from(int pos); void bind_to(Label* L, int pos); void next(Label* L); void AllocateAndInstallRequestedHeapObjects(Isolate* isolate); int WriteCodeComments(); friend class RegExpMacroAssemblerS390; friend class RelocInfo; friend class EnsureSpace; }; class EnsureSpace { public: explicit EnsureSpace(Assembler* assembler) { assembler->CheckBuffer(); } }; } // namespace internal } // namespace v8 #endif // V8_S390_ASSEMBLER_S390_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1032316f973bc8db22e17c2dca2bf131a635c36d
18e4ea8a882ffd5add41ce001522d60e0ce556e8
/hw6-1/simple_shape_main.cc
121270ed5780549c64c164c17d217d016e37c1f0
[]
no_license
2018008613/CreativeSoftwareProgramming
b36c5f7d992c7b4b5d55dab632c15380191a0605
fddee907bd08772fca0bd9da868474859c671505
refs/heads/master
2022-04-21T09:04:48.937091
2020-04-15T12:43:09
2020-04-15T12:43:09
255,913,012
0
0
null
null
null
null
UTF-8
C++
false
false
492
cc
#include <iostream> #include <string> #include "simple_shape.h" using namespace std; int main() { while (1) { string a; Circle c; Rectangle t; cout << "shape?" << endl; cin >> a; if (a == "C") { c.cgets(); cout << "area: " << c.CircleArea() << ", perimeter: " << c.CirclePerimeter() << endl; } if (a == "R") { t.rgets(); cout << "area: " << t.RectangleArea() << ", perimeter: " << t.RectanglePerimeter() << endl; } if (a == "Q") { break; } } }
[ "picosw@hanyang.ac.kr" ]
picosw@hanyang.ac.kr
28d1c00d0258837e3801155a33077549f1beff26
50b10c0019c0e1a641024c2f1cb1713f57294a4a
/series2_handout/hyp_sys_1d/src/ancse/runge_kutta.cpp
7411835c5db4185a51395321f04ef70d5109ee33
[ "MIT" ]
permissive
BeatHubmann/19H-AdvNCSE
37e2a65f3d2fb90a1685cfb64b1816943d608223
3979f768da933de82bd6ab29bbf31ea9fc31e501
refs/heads/master
2020-07-29T11:10:09.216346
2019-12-08T22:49:42
2019-12-08T22:49:42
209,775,272
1
1
null
null
null
null
UTF-8
C++
false
false
2,020
cpp
#include <ancse/runge_kutta.hpp> #include <ancse/includes.hpp> #include <ancse/config.hpp> #include <fmt/format.h> #define REGISTER_FVM_RUNGE_KUTTA(token, RKType) \ if (rk_key == token) { \ return std::make_shared<RKType>( \ rate_of_change, boundary_condition, nullptr, n_vars, n_cells); \ } /// make Runge Kutta for FVM std::shared_ptr<RungeKutta> make_runge_kutta(const nlohmann::json &config, const std::shared_ptr<RateOfChange> &rate_of_change, const std::shared_ptr<BoundaryCondition> &boundary_condition, int n_vars, int n_cells) { std::string rk_key = config["time_integrator"]; REGISTER_FVM_RUNGE_KUTTA("forward_euler", ForwardEuler) // Register your SSP2 class. throw std::runtime_error( fmt::format("Unknown time-integrator. [{}]", rk_key)); } #undef REGISTER_FVM_RUNGE_KUTTA #define REGISTER_DG_RUNGE_KUTTA(token, RKType) \ if (rk_key == token) { \ return std::make_shared<RKType>( \ rate_of_change, boundary_condition, dg_limiting, n_vars, n_cells); \ } /// make Runge Kutta for DG std::shared_ptr<RungeKutta> make_runge_kutta(const nlohmann::json &config, const std::shared_ptr<RateOfChange> &rate_of_change, const std::shared_ptr<BoundaryCondition> &boundary_condition, const std::shared_ptr<Limiting> &dg_limiting, int n_vars, int n_cells) { std::string rk_key = config["time_integrator"]; REGISTER_DG_RUNGE_KUTTA("forward_euler", ForwardEuler) // Register your SSP2 class. throw std::runtime_error( fmt::format("Unknown time-integrator. [{}]", rk_key)); } #undef REGISTER_DG_RUNGE_KUTTA
[ "BeatHubmann@users.noreply.github.com" ]
BeatHubmann@users.noreply.github.com
064aa3ba8f940a41b6dfd3385812727306567a2c
c11460ee58386012ef30fa4089c43d715e231a4c
/lib/tsan/rtl/relacy/schedulers/tsan_fixed_window_scheduler.h
015b7917888a8ef25d86d2388bd4a8f391639866
[ "NCSA", "MIT" ]
permissive
dorooleg/compiler-rt
5589396b2c74e5e5d7ec82ce9809d2d5f2cb63df
13ea846316c3986099c6a536f1973d75838ad675
refs/heads/schedulers
2022-01-25T14:17:39.004550
2019-07-08T19:37:14
2019-07-08T19:37:14
128,505,427
0
0
NOASSERTION
2019-07-08T19:37:56
2018-04-07T07:13:42
C
UTF-8
C++
false
false
858
h
#ifndef TSAN_FIXED_WINDOW_SCHEDULER_H #define TSAN_FIXED_WINDOW_SCHEDULER_H #include "rtl/relacy/tsan_scheduler.h" #include "rtl/relacy/tsan_shared_vector.h" #include "rtl/relacy/tsan_threads_box.h" namespace __tsan { namespace __relacy { class FixedWindowScheduler : public Scheduler { public: FixedWindowScheduler(ThreadsBox& threads_box, int window_size); ThreadContext* Yield() override; void Start() override; void Finish() override; bool IsEnd() override; void Initialize() override; SchedulerType GetType() override; private: ThreadsBox& threads_box_; SharedVector<int> window_paths_; SharedVector<int> window_border_; uptr offset_; SharedValue<uptr> depth_; SharedValue<int> invalidate_pos_; int window_size_; bool is_end_; uptr iteration_; }; } } #endif //TSAN_FIXED_WINDOW_SCHEDULER_H
[ "dorooleg@yandex.ru" ]
dorooleg@yandex.ru
0705f9f98dee1239960481b1586f85783e301c54
0b68534e02bbcce3b93be85e2b8974a6b224f0cc
/chtho/net/http/HTTPContext.cpp
75a4da904dd26a809aae83e5382ceaca830d496f
[ "MIT" ]
permissive
WineChord/chtho
f2b9ffe1b05faf4276d03cf7864dd3987e71ef38
f43c56a1c2faf83e5f48361ca1b06366ce061aab
refs/heads/main
2023-04-10T18:50:38.818174
2021-04-25T17:21:22
2021-04-25T17:21:22
340,803,506
0
0
null
null
null
null
UTF-8
C++
false
false
2,264
cpp
// Copyright (c) 2021 Qizhou Guo // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #include "HTTPContext.h" #include "net/Buffer.h" namespace chtho { namespace net { /* request structure GET /hello.txt HTTP/1.1 User-Agent: curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3 Host: www.example.com Accept-Language: en, mi */ bool HTTPContext::parse(Buffer* buf, Timestamp rcvTime) { bool ok = true, more = true; while(more) { if(state_ == ExpReq) { const char* crlf = buf->findCRLF(); if(crlf) { ok = procReq(buf->peek(), crlf); if(ok) { request_.setRcvTime(rcvTime); buf->retrieveUntil(crlf+2); state_ = ExpHeader; } else more = false; } else more = false; } else if(state_ == ExpHeader) // retrieve headers { const char* crlf = buf->findCRLF(); if(crlf) { const char* colon = std::find(buf->peek(), crlf, ':'); if(colon != crlf) request_.addHeader(buf->peek(), colon, crlf); else // no more headers { state_ = Done; more = false; } buf->retrieveUntil(crlf+2); } else more = false; } } return ok; } /* request line, something like GET /hello HTTP/1.1 */ bool HTTPContext::procReq(const char* begin, const char* end) { const char* space = std::find(begin, end, ' '); if(space == end) return false; if(!request_.setMethod(begin, space)) return false; begin = space + 1; // move to something like '/hello' space = std::find(begin, end, ' '); if(space == end) return false; const char* question = std::find(begin, space, '?'); if(question != space) { request_.setPath(begin, question); request_.setQuery(question, space); } else { request_.setPath(begin, space); } begin = space + 1; // should be either 'HTTP/1.0' or 'HTTP/1.1' if(end - begin != 8) return false; if(!std::equal(begin, end-1, "HTTP/1.")) return false; if(*(end-1) == '1') request_.setVersion(HTTPRequest::HTTP11); else if(*(end-1) == '0') request_.setVersion(HTTPRequest::HTTP10); else return false; return true; } } // namespace net } // namespace chtho
[ "guoqizhou123123@qq.com" ]
guoqizhou123123@qq.com
31bf6e308cd11ffef511d6c96f843a8e29ec01d5
2fd0fae47b85ce8661edaf2ea4fab2377a69eaf8
/OOPaufgabenblatt2a6.cpp
ddee6c5bc0d645caa2c245270a29197f10748cd1
[]
no_license
Seakuh/OOP
1277bb32a7bb5db09a2e6992ac27fa63efc9e6b0
aa9fe6e88b92126223a4b0c713bbf34d883e93ea
refs/heads/master
2020-12-13T04:06:35.957386
2020-01-16T11:49:19
2020-01-16T11:49:19
234,308,392
0
0
null
null
null
null
UTF-8
C++
false
false
794
cpp
#include <iostream> #include "letzteaufg copy.h" int main() { double k = 50; double j = 0.5; Arraylist<double> neu = Arraylist<double>(k); Arraylist<double> vergleich = Arraylist<double>(7); Arraylist<double> zuweisen = Arraylist<double>(7); Arraylist<double> zuweisen1 = Arraylist<double>(7); Arraylist<float> zuweisen3 = Arraylist<float>(7); //Zuweisungsoperator Test try { for (int i = 0; i < 7; i++) { zuweisen.set(i, i); } } catch (const char *e) { std::cout << e << std::endl; }; std::cout << zuweisen1 << std::endl; zuweisen1 = zuweisen; std::cout << "Zuweisen Test" << std::endl; std::cout << zuweisen << std::endl; std::cout << zuweisen1 << std::endl; }
[ "eteranimal@protonmail.com" ]
eteranimal@protonmail.com
657371e198c8432a210112097386edb68d064c07
f9e2744ff3e630d3416843b243e6451ad2030263
/src/qt/sendcoinsdialog.cpp
bcf7b3e5e15b826ff466a11d8af759e85caa2cea
[ "MIT" ]
permissive
bincoinus/Bincoin
0623e166b288ff7279fe0fa85efd2db66e949a63
6bc3afc8bb03f7eb3c6618ba2303c04b6795619d
refs/heads/master
2020-06-11T23:37:03.614478
2016-12-05T10:15:24
2016-12-05T10:15:24
75,612,846
0
0
null
null
null
null
UTF-8
C++
false
false
17,900
cpp
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "addressbookpage.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QLocale> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a BinCoin address (e.g. 1B4e4ah2nr6nfwYhBmGXcFP2Po1NpRUEiK8km2)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { QApplication::clipboard()->setText(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { QApplication::clipboard()->setText(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: Invalid BinCoin address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
[ "team@bincoin.us" ]
team@bincoin.us
4b8b9a1d08b8e250ce3e81db85c2d097dfa65e4a
2d34422361367d6fb28167c713f689ee7084d5c0
/libraries/reducedElasticForceModel/reducedLinearStVKForceModel.cpp
5b4f42a0a69fca70c6cc5b70dddd20aa643f3a9a
[]
no_license
kengwit/VegaFEM-v3.0
5c307de1f2a2f57c2cc7d111c1da989fe07202f4
6eb4822f8d301d502d449d28bcfb5b9dbb916f08
refs/heads/master
2021-12-10T15:03:14.828219
2016-08-24T12:04:03
2016-08-24T12:04:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,311
cpp
/************************************************************************* * * * Vega FEM Simulation Library Version 3.0 * * * * "elasticForceModel" library , Copyright (C) 2007 CMU, 2009 MIT, * * 2016 USC * * All rights reserved. * * * * Code author: Jernej Barbic * * http://www.jernejbarbic.com/code * * * * Research: Jernej Barbic, Fun Shing Sin, Daniel Schroeder, * * Doug L. James, Jovan Popovic * * * * Funding: National Science Foundation, Link Foundation, * * Singapore-MIT GAMBIT Game Lab, * * Zumberge Research and Innovation Fund at USC * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the BSD-style license that is * * included with this library in the file LICENSE.txt * * * * 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 file * * LICENSE.TXT for more details. * * * *************************************************************************/ #include "matrixMacros.h" #include "reducedLinearStVKForceModel.h" ReducedLinearStVKForceModel::ReducedLinearStVKForceModel(StVKReducedStiffnessMatrix * stVKReducedStiffnessMatrix) { r = stVKReducedStiffnessMatrix->Getr(); K = (double*) malloc (sizeof(double) * r * r); double * zero = (double*) calloc (r, sizeof(double)); stVKReducedStiffnessMatrix->Evaluate(zero,K); free(zero); } ReducedLinearStVKForceModel::ReducedLinearStVKForceModel(int r, double * K) { this->r = r; this->K = (double*) malloc (sizeof(double) * r * r); memcpy(this->K, K, sizeof(double) * r * r); } void ReducedLinearStVKForceModel::GetInternalForce(double * q, double * internalForces) { // internalForces = K * q memset(internalForces, 0, sizeof(double) * r); for(int i=0; i<r; i++) for(int j=0; j<r; j++) internalForces[i] += K[ELT(r,i,j)] * q[j]; } void ReducedLinearStVKForceModel::GetTangentStiffnessMatrix(double * q, double * tangentStiffnessMatrix) { memcpy(tangentStiffnessMatrix, K, sizeof(double) * r * r); } void ReducedLinearStVKForceModel::GetTangentHessianTensor(double * q, double * tangentHessianTensor) { memset(tangentHessianTensor, 0, sizeof(double) * r * r*(r+1)/2); }
[ "jslee02@gmail.com" ]
jslee02@gmail.com
cc92a8aab28153ad880885f9b8bd35adb2e2eff2
c47b47e5768549da37b768ea270abe62db43a390
/Lab6/avltree.h
84b45115ae1c6a22fa51fbcdb7888c262e32cb0a
[]
no_license
tiennm99/CTDL-GT
69ec46eb74618e08acb5e92aa222360b073974c5
9da63ab2407446f8334aff7ed8c75cafe80c6c96
refs/heads/master
2021-10-10T13:53:50.056119
2019-01-11T13:27:28
2019-01-11T13:27:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,175
h
#ifndef AVLTREE_H #define AVLTREE_H #include <stack> #include "avlnode.h" template <class T> class AVLTree { private: AVLNode<T> *root = nullptr; AVLNode<T> *rotateLeft(AVLNode<T> *node); AVLNode<T> *rotateRight(AVLNode<T> *node); int getHeight(AVLNode<T> *node); void rebalance(AVLNode<T> *node); public: AVLTree(); ~AVLTree(); bool insert(AVLNode<T> *newNode); AVLNode<T> *search(T searchData); bool remove(const T removeData); void printAsList(); void printNLR(); template <class U> friend ostream &operator << (ostream &os, AVLTree<U> *tree); }; template <class T> AVLTree<T>::AVLTree() { this->root = nullptr; } template <class T> AVLTree<T>::~AVLTree() { delete this->root; this->root = nullptr; } template <class T> void AVLTree<T>::rebalance(AVLNode<T> *node) { if (node == nullptr) return; node->update(); if (node->balance > 1) { if (node->left->balance < -1) node->left = rotateLeft(node->left); node = rotateRight(node); } else if (node->balance < -1) { if (node->right->balance > 1) node->right = rotateRight(node->right); node = rotateLeft(node); } if (node->parent == nullptr) this->root = node; else rebalance(node->parent); } template <class T> AVLNode<T> *AVLTree<T>::rotateLeft(AVLNode<T> *node) { AVLNode<T> *temp = node->right; AVLNode<T> *tmp = temp->left; AVLNode<T> *parent = node->parent; temp->parent = parent; node->right = tmp; if (tmp != nullptr) { tmp->parent = node; } temp->left = node; node->parent = temp; if (parent != nullptr) { if (parent->left == node) parent->left = temp; else parent->right = temp; } node->update(); temp->update(); return temp; } template <class T> AVLNode<T> *AVLTree<T>::rotateRight(AVLNode<T> *node) { AVLNode<T> *temp = node->left; AVLNode<T> *tmp = temp->right; AVLNode<T> *parent = node->parent; temp->parent = parent; node->left = tmp; if (tmp != nullptr) { tmp->parent = node; } temp->right = node; node->parent = temp; if (parent != nullptr) { if (parent->left == node) parent->left = temp; else parent->right = temp; } node->update(); temp->update(); return temp; } template <class T> int AVLTree<T>::getHeight(AVLNode<T> *node) { if (node == nullptr) return 0; return node->height; } template <class T> bool AVLTree<T>::insert(AVLNode<T> *newNode) { if (newNode == nullptr) return false; if (this->root == nullptr) { this->root = newNode; return true; } AVLNode<T> *temp = this->root; AVLNode<T> *parent; while (true) { if (temp->data == newNode->data) return false; parent = temp; bool goLeft = (newNode->data < temp->data); temp = goLeft ? temp->left : temp->right; if (temp == nullptr) { if (goLeft) { parent->left = newNode; newNode->parent = parent; } else { parent->right = newNode; newNode->parent = parent; } rebalance(parent); return true; } } } template <class T> bool AVLTree<T>::remove(const T removeData) { AVLNode<T> *temp = this->root; while (temp != nullptr) { if (removeData < temp->data) temp = temp->left; else if (removeData > temp->data) temp = temp->right; else break; } if (temp == nullptr) return false; AVLNode<T> *del = temp; if (temp->left != nullptr) { del = temp->left; while (del->right != nullptr) del = del->right; } AVLNode<T> *parent = nullptr; if (del == this->root) { this->root = this->root->right; if (this->root != nullptr) this->root->parent = nullptr; } else if (del != temp) { temp->data = del->data; parent = del->parent; if (parent->left == del) parent->left = del->left; else parent->right = del->left; if (del->left != nullptr) del->left->parent = parent; } else { parent = del->parent; if (parent->left == del) parent->left = del->right; else parent->right = del->right; if (del->right != nullptr) del->right->parent = parent; } if (parent != nullptr) this->rebalance(parent); return true; } template <class T> void AVLTree<T>::printNLR() { stack<AVLNode<T> *> sAVLNode; stack<int> sNodeLevel; sAVLNode.push(this->root); sNodeLevel.push(0); while (!sAVLNode.empty()) { AVLNode<T> *tNode = sAVLNode.top(); sAVLNode.pop(); int tLevel = sNodeLevel.top(); sNodeLevel.pop(); for (int i = 0; i < tLevel; ++i) { cout << " "; } if (tNode == nullptr) { cout << "NULL" << endl; continue; } cout << tNode->data << "(" << tNode->balance << ")" << endl; sAVLNode.push(tNode->right); sNodeLevel.push(tLevel + 1); sAVLNode.push(tNode->left); sNodeLevel.push(tLevel + 1); } } template <class T> AVLNode<T> *AVLTree<T>::search(T searchData) { AVLNode<T> *temp = this->root; while (temp != nullptr) { if (searchData < temp->data) temp = temp->left; else if (searchData > temp->data) temp = temp->right; else return temp; } return nullptr; } template <class T> void printLNR(AVLNode<T> *subroot) { if (subroot == nullptr) return; printLNR(subroot->left); cout << subroot->data << endl; printLNR(subroot->right); } template <class T> void AVLTree<T>::printAsList() { printLNR(this->root); } template <class T> ostream &operator << (ostream &os, AVLTree<T> *tree) { os << tree->root; return os; } #endif // AVLTREE_H
[ "minhtienit99@gmail.com" ]
minhtienit99@gmail.com
6509eb236878baa1f04db93bb63e98630f11813d
f6d498cab468a60e8b03489e2b3fd40588862955
/Figurinhas da Copa.cpp
adc74f457fb9ca013868efececbb10abbfcb0a03
[ "MIT" ]
permissive
VictorCastao/NEPS_Academy-Resolvidos
f66b61f08e76e9e016dfaea39d625567cb9cdbd8
71800aaf24770fde368e62b223bdf2b8099817eb
refs/heads/main
2022-12-22T09:41:41.418522
2020-10-05T16:04:38
2020-10-05T16:04:38
301,462,926
0
0
null
null
null
null
UTF-8
C++
false
false
452
cpp
#include <iostream> #include <set> using namespace std; int main(){ set <int> figurinhas; int espacos, carimbadas, compradas, temp, i; cin >> espacos >> carimbadas >> compradas; for(i=0; i<carimbadas; i++){ cin >> temp; figurinhas.insert(temp); } for(i=0; i<compradas; i++){ cin >> temp; if(figurinhas.find(temp) != figurinhas.end()){ figurinhas.erase(temp); carimbadas--; } } cout << carimbadas << endl; return 0; }
[ "noreply@github.com" ]
VictorCastao.noreply@github.com
0e704dec214cf8eb6cb5a3d2d9197763a2f2e327
cb2fe0a9a10a7418bc683df6eedb238c657f4c8a
/Basics of C++/tutorial_11_do_while.cpp
9c5434620b885770f5311a26932f22777c10a84f
[]
no_license
withoutwaxaryan/programming-basics
bf33c32545e89deba13c6ab33a1568e69f40c693
93c0c57bf36acd1190f65ec3f2b6d316d59eaaf0
refs/heads/master
2023-03-07T04:58:37.451151
2021-02-20T12:26:14
2021-02-20T12:26:14
181,515,433
0
0
null
null
null
null
UTF-8
C++
false
false
147
cpp
#include<iostream> using namespace std; int main() { int x =1; do { cout<<"yo"<<endl; } while (x<1); return 0; }
[ "aryangupta973@gmail.com" ]
aryangupta973@gmail.com