text
stringlengths
8
6.88M
/* ModbusTCP.h - Header for Modbus IP Library Copyright (C) 2015 André Sarmento Barbosa */ #include "mbed.h" #include "Modbus.h" #include "NetworkInterface.h" #ifndef MODBUSTCP_H #define MODBUSTCP_H #define MODBUSTCP_PORT 502 #define MODBUSTCP_MAXFRAME 200 //#define TCP_KEEP_ALIVE class ModbusTCP : public Modbus { private: NetworkInterface* network; TCPServer _server; TCPSocket _socket; SocketAddress _address; byte _MBAP[7]; public: ModbusTCP(NetworkInterface* _net); void server_open(uint16_t port); void server_run(); void server_stop(); }; #endif //MODBUSIP_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef FORMVALUERADIOCHECK_H #define FORMVALUERADIOCHECK_H class HTML_Element; class FormObject; class FramesDocument; class ES_Thread; #include "modules/forms/formvalue.h" /** * Represents a radio button or a checkbox. */ class FormValueRadioCheck : public FormValue { public: FormValueRadioCheck() : FormValue(VALUE_RADIOCHECK) {}; // Use base class documentation virtual FormValue* Clone(HTML_Element *he); static OP_STATUS ConstructFormValueRadioCheck(HTML_Element* he, FormValue*& out_value); /** * "Cast" the FormValue to this class. This asserts in debug * builds if done badly. This should be inlined and be as * cheap as a regular cast. If it turns out it's not we * might have to redo this design. * * @param val The FormValue pointer that really is a pointer to * an object of this class. */ static FormValueRadioCheck* GetAs(FormValue* val) { OP_ASSERT(val->GetType() == VALUE_RADIOCHECK); return static_cast<FormValueRadioCheck*>(val); } /** * "Cast" the FormValue to this class. This asserts in debug * builds if done badly. This should be inlined and be as * cheap as a regular cast. If it turns out it's not we * might have to redo this design. * * @param val The FormValue pointer that really is a pointer to * an object of this class. */ static const FormValueRadioCheck* GetAs(const FormValue* val) { OP_ASSERT(val->GetType() == VALUE_RADIOCHECK); return static_cast<const FormValueRadioCheck*>(val); } // Use base class documentation virtual OP_STATUS ResetToDefault(HTML_Element* he); // Use base class documentation virtual OP_STATUS GetValueAsText(HTML_Element* he, OpString& out_value) const; // Use base class documentation virtual OP_STATUS SetValueFromText(HTML_Element* he, const uni_char* in_value); // Use base class documentation virtual BOOL Externalize(FormObject* form_object_to_seed); // Use base class documentation virtual void Unexternalize(FormObject* form_object_to_replace); /** * Set this radio button or checkbox checked or unchecked. * * @param he The HTML element this FormValue belongs to. * * @param is_checked If TRUE the element will be marked checked, * if FALSE it will be marked unchecked. * * @param doc The element's document, needed if * "process_full_radiogroup" is set. Otherwise it can be NULL. The * presence of this parameter is controlled by the capability * * @param process_full_radiogroup TRUE if any side effects (such * as unchecking other radio buttons) should be performed. If TRUE * is used, doc mustn't be NULL. * * @param interrupt_thread The thread causing the change. Needed * to get events correct. */ void SetIsChecked(HTML_Element* he, BOOL is_checked, FramesDocument* doc = NULL, BOOL process_full_radiogroup = FALSE, ES_Thread* interrupt_thread = NULL); /** * If this is a radio button in a radio group, then this method will make * every other radio button in that group unchecked without sending any * events. * * @param radio_elm The HTML element this FormValue belongs to. * @param doc The document * @param thread The thread initiating this action or NULL. */ void UncheckRestOfRadioGroup(HTML_Element* radio_elm, FramesDocument* doc, ES_Thread* thread) const; /** * Returns TRUE if this is checked. * * @param he The HTML element this FormValue belongs to. */ BOOL IsChecked(HTML_Element* he) const; /** * Returns TRUE if this is checked by default. * * @param he The HTML element this FormValue belongs to. */ BOOL IsCheckedByDefault(HTML_Element* he) const; /** * Checks if the "is in checked radio group" flag is set, and * returns TRUE in that case. This is O(1) but possibly not 100% reliable. */ BOOL IsInCheckedRadioGroup(); /** * Marks this radio button as being in a group of radio buttons where * at least one is selected. This is used for the :indeterminate * pseudo class. ONLY FOR FORMS INTERNAL USE. */ void SetIsInCheckedRadioGroup(BOOL value); /** * When a click on a checkbox happens the value should be changed * before event handlers. Then if the click event was cancelled, * then the original value should be restored. otherwise a change * event should be sent. So this has to be called before the onclick * event. * * @param he The HTML element this FormValue belongs to. */ void SaveStateBeforeOnClick(HTML_Element* he); /** * See the SaveStateBeforeOnClick documentation. * * @param he The HTML element this FormValue belongs to. * * @param onclick_cancelled TRUE if the onclick event was * cancelled. * * @returns TRUE if the value was changed by the onclick. If * onclick_cancelled is TRUE, then it will always return FALSE. */ BOOL RestoreStateAfterOnClick(HTML_Element* he, BOOL onclick_cancelled); // Used in FormManager. Should not be used anywhere else. Especially not from outside the forms module /** * Iterates through the form and makes sure the IsInCheckedGroup flag is * correct on all radio buttons that doesn't belong to a form. * Method internal to the forms module. */ static OP_STATUS UpdateFreeButtonsCheckedInGroupFlags(FramesDocument* frames_doc); // Used in FormManager. Should not be used anywhere else. Especially not from outside the forms module /** * Iterates through the form and makes sure the IsInCheckedGroup flag is * correct on all radio buttons. Method internal to the forms module. * * @param frames_doc The document with the radio button. * @param form_element The form to iterate through. */ static OP_STATUS UpdateCheckedInGroupFlags(FramesDocument* frames_doc, HTML_Element* form_element); /** * Tells the FormValue that a recent change was made * from a script setting the .checked property or * from a click by the user. * That will block future changes from the changed attribute */ void SetWasChangedExplicitly(FramesDocument* frames_doc, HTML_Element* form_element); /** * Returns whether setting the checked property also will check * the checkbox/radio button. */ BOOL IsCheckedAttrChangingState(FramesDocument* frames_doc, HTML_Element* form_element) const; private: /** * Unchecks and previous set radio buttons in the radio group. */ void UncheckPrevRadioButtons(FramesDocument* frames_doc, HTML_Element* radio_elm); /** * @param names_with_check Really a OpStringSet, but that didn't * exist so we use a dummy hash table with only NULL as data. */ static OP_STATUS UpdateCheckedInGroupFlagsHelper(FramesDocument* frames_doc, HTML_Element* fhe, OpStringHashTable<uni_char>& names_with_check, int mode); /** * Accesses the base class storage as our "IsChecked" data. */ unsigned char& GetIsCheckedBool() { return GetReservedChar1(); } const unsigned char& GetIsCheckedBool() const { return GetReservedChar1(); } }; #endif // FORMVALUERADIOCHECK_H
/*In this program we will be seeing all the Misc Operators like Sizeof, Adress , pointer , Conditional Expression avaliable in C++*/ /*including preprocessor in the program*/ #include <iostream> /*using namespace*/ using namespace std ; /*creating a main() function of the program*/ int main() { /*Declaring Variable 'a=10' of data type int ,creating a Variable 'b' with no initial value with datatype float and creating a Variable 'c' with no initial value with datatype double is declared and pointer is created*/ /*Note: No worries about pointer , address and conditional Expression, it will explained later on */ int a = 10; float b; double c; int* ptr; /* example of sizeof operator */ cout<<"\nSize of variable 'a' of data type int = " << sizeof(a) << endl ; cout<<"\nSize of variable 'b' of data type float = " << sizeof(b) << endl ; cout<<"\nSize of variable 'c' of data type double = "<< sizeof(c) << endl ; /* example of & and * operators */ /*Address(&) is used to return the address of a variable stored*/ ptr = &a; /* 'ptr' now contains the address of 'a'*/ cout<<"\nValue of a is " << a <<endl ; cout<<"\nAddress of a is " << &a << endl ; cout<<"\nValue of *ptr is " << ptr << endl ; cout<<"\n*ptr is " << *ptr << endl ; /* example of ternary operator */ /*conditional operator is also known as Ternary Operator it is defined as when the condition is true then first expression will excuted , if the condition fails then second expression will be excuted . Syntax for Ternary Operator is "Variable = Condition ? Expression 1 :Expression2;"*/ int x = 10; int y = 30; int z = ( x < y ) ? x : y ; cout<< "\nValue of z is " << z << endl ; }
#ifndef CDT_CORE_ASINGLETON_IMPL_HPP #define CDT_CORE_ASINGLETON_IMPL_HPP #include <memory> namespace cdt { template<class T> std::shared_ptr<T> ASingleton<T>::instance() { auto result = mp_inst.lock(); if (!result) { result.reset(new T, deleteFxn); mp_inst = result; } return result; } template<class T> void ASingleton<T>::deleteFxn(T* ptr) { delete ptr; } template<class T> std::weak_ptr<T> ASingleton<T>::mp_inst; template<class T> ASingleton<T>::~ASingleton<T>() {}; } // cdt #endif // CDT_CORE_ASINGLETON_HPP
#include "Display.h" #include <Arduino.h> Display::Display() { for (int i = 0; i < CONFIG_MAP_SIZE; i++) { color[i] = 0; type[i] = 0; } } uint32_t Display::rgb2hex(byte R, byte G, byte B) { return (R << 16) | (G << 8) | B; } void Display::add_dot(byte position, uint32_t rgb_hex) { /* * add pixel one in postion x */ pos[position] = position; color[position] = rgb_hex; } void Display::add_dot(byte position, byte rgb_color[]) { /* * add pixel one in postion x */ pos[position] = position; color[position] = rgb2hex(rgb_color[0], rgb_color[1], rgb_color[2]); ; } void Display::add_pixel(byte value[], int arrSize) { /* * add pixel by position array and fill by defualt color */ for (int i = 0; i < arrSize; i++) { pos[value[i]] = value[i]; // White color color[value[i]] = rgb2hex(255, 50, 0); } } void Display::add_pixel(byte value[], uint32_t rgb_hex, int arrSize) { /* * add pixel by position array and color mapping */ for (int i = 0; i < arrSize; i++) { pos[value[i]] = value[i]; color[value[i]] = rgb_hex; } } void Display::add_pixel(byte value[], byte rgb_color[], int arrSize) { /* * add pixel by position array and color mapping */ for (int i = 0; i < arrSize; i++) { pos[value[i]] = value[i]; color[value[i]] = rgb2hex(rgb_color[0], rgb_color[1], rgb_color[2]); //memo:\ Fix color[] to One ring system not } } void Display::add_pixel_clear(byte value[]) { /* * add pixel by position array and color mapping */ for (int i = 0; i < 16; i++) { if (value[i] != 0) { pos[i] = value[i]; color[i] = rgb2hex(255, 50, 0); } else { pos[i] = 0; color[i] = rgb2hex(0, 0, 0); } } } void Display::set_color_n(uint16_t _position, uint32_t _color) { color[_position] = _color; } template <typename rotate_arr_pos> void Display::rotation(rotate_arr_pos arrValue) { byte temp_pos[CONFIG_MAP_SIZE]; int temp_color[CONFIG_MAP_SIZE]; char temp_type[CONFIG_MAP_SIZE]; for (int i = 0; i < CONFIG_MAP_SIZE; i++) { // Algo; In position 1 goto see box 13 and write down to temp temp_pos[i] = pos[arrValue[i]]; //Serial.print(pos[i]); //Serial.print("n="); //Serial.print(temp_pos[i]); temp_color[i] = color[arrValue[i]]; temp_type[i] = type[arrValue[i]]; } for (int i = 0; i < CONFIG_MAP_SIZE; i++) { // Algo; In position 1 goto see box 13 and write down to temp pos[i] = temp_pos[i]; color[i] = temp_color[i]; type[i] = temp_type[i]; } //Serial.print("_________________"); /*for (int i = 0; i < CONFIG_MAP_SIZE; i++) { //Serial.print(temp_pos[i]); } //Serial.println();*/ } void Display::rotate_left() { rotation(rotation_left_grid); } void Display::rotate_right() { rotation(rotation_left_grid); } void Display::clear_pixel() { for (int i = 0; i < CONFIG_MAP_SIZE; i++) { pos[i] = 0; color[i] = 0; type[i] = 0; } } void Display::set_fade_from_pos(byte pos, uint8_t _value, uint8_t _start, uint8_t _end) { // stupid function because you can use hsl color system to fade L // first uint32 to RGB RGB __rgb = RGB(0, 0, 0); __rgb = __rgb.hex2rgb(color[pos]); // Secound RGB to hsl and set light with light_value uint8_t _val = constrain(_value, _start, _end); __rgb.rgb2hsl_convert(); __rgb = __rgb.hsl2rgb(__rgb.get_h(), __rgb.get_s(), _val); set_color_n(pos, __rgb.toInt32()); }
#include "babel.h" #include <QtGui/QApplication> #include "QNetwork.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Babel w; // QNetwork net; // quint16 port = 20701; // net.socketConnection("127.0.0.1", port); w.show(); // if (net.getSocketStatus()) // net.disconnect(); return a.exec(); }
#include <iostream> #include <cstdlib> using namespace std; void burbuja(int [], int); int main() { srand(time(0)); const int tamanio = 10; int t[tamanio] = {1+rand()%100, 1+rand()%100, 1+rand()%100, 1+rand()%100, 1+rand()%100, 1+rand()%100, 1+rand()%100, 1+rand()%100, 1+rand()%100, 1+rand()%100 }; for(int i=0; i<tamanio; i++) cout << t[i] << "\t"; cout << endl; burbuja(t, tamanio); for(int i=0; i<tamanio; i++) cout << t[i] << "\t"; cout << endl; } void burbuja(int a[], int tam) { bool fin = false; int temp=0; int tam2=tam-1; while(!fin) { fin = true; for(int i=0; i<tam2; i++) if( a[i] > a[i+1]) { temp = a[i+1]; a[i+1] = a[i]; a[i] = temp; fin = false; } tam2--; } }
#include <iostream> #include <vector> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <string> #include <cstdio> using namespace std; int strToTime(string s) { return ((s[0] - '0') * 10 + s[1] - '0') * 3600 + ((s[3] - '0') * 10 + s[4] - '0') * 60 + (s[6] - '0') * 10 + s[7] - '0'; } int main() { int N, K; string arrTime; int cost; while (cin >> N >> K) { map<int, int> m; vector<int> sum(K, 8*3600); for (int i = 0; i < N; i++) { cin >> arrTime >> cost; m[strToTime(arrTime)] = cost * 60; } int count = 0; int total = 0; for (auto it = m.begin(); it != m.end(); it++) { if (it->first > 17 * 3600) break; auto minIt = min_element(sum.begin(), sum.end()); total += it->first < *minIt ? *minIt - it->first : 0; *minIt = max(*minIt, it->first) + it->second; count++; } printf("%.1f\n", total / 60.0 / count); } return 0; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: vector<vector<int>> res; vector<int> cur; vector<vector<int>> combinationSum3(int k, int n) { //基本思想:递归回溯,深度优先搜索 dfs( k, n, 1); return res; } void dfs(int k, int n, int num) { if (k == 0) { if (n == 0) res.push_back(cur); return; } for (int i = num; i < 10 && n - i >= 0; i++) { cur.push_back(i); dfs(k - 1, n - i, i + 1); cur.pop_back(); } return; } }; int main() { Solution solute; int k = 5, n = 27; vector<vector<int>> res = solute.combinationSum3(k, n); for (int i = 0; i < res.size(); i++) { for_each(res[i].begin(), res[i].end(), [](const auto v) {cout << v << " "; }); cout << endl; } return 0; }
#include <bits/stdc++.h> using namespace std; class Trie { public: bool isEnd; vector<Trie *> nodes; Trie() { nodes.resize(26, nullptr); isEnd = false; } void insert(string word) { Trie *next = this; for (auto ch : word) { ch -= 'a'; if (!next->nodes[ch]) next->nodes[ch] = new Trie(); next = next->nodes[ch]; } next->isEnd = true; } }; class Solution { public: vector<string> findWords(vector<vector<char>> &board, vector<string> &words) { int n = board.size(); if (n == 0) return vector<string>(); int m = board[0].size(); Trie *root = new Trie(); for (auto str : words) root->insert(str); vector<int> dx = {-1, 0, 0, 1}; vector<int> dy = {0, -1, 1, 0}; vector<vector<bool>> vis(n, vector<bool>(m, false)); set<string> hs; function<void(Trie *, int, int, string)> dfs = [&](Trie *head, int i, int j, string word) { if (head == nullptr || head->nodes[board[i][j] - 'a'] == nullptr) return; word.push_back(board[i][j]); if (head->nodes[board[i][j] - 'a']->isEnd) { hs.insert(word); head->isEnd = false; } vis[i][j] = true; for (int k = 0; k < 4; k++) { int x = i + dx[k]; int y = j + dy[k]; if (x < 0 || y < 0 || x >= n || y >= m) continue; if (!vis[x][y]) { dfs(head->nodes[board[i][j] - 'a'], x, y, word); } } vis[i][j] = false; }; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dfs(root, i, j, ""); } } vector<string> vec(hs.begin(), hs.end()); return vec; } }; // using trie(searching for all words with prefix, for a ch in board) // not using trie - brute force, every ch in board, dfs for every word O(n*m*(wordlist length)*dfs time*) //
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution1 { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(!root || (!p && !q)) return root; if(!p || !q) return !p ? q:p; if(p->val > q->val) swap(p,q); TreeNode *temp = root; while(temp && !(temp->val >= p->val && temp->val <= q->val)){ if(temp->val > q->val){ temp = temp->left; }else{ temp = temp->right; } } return temp; } }; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution2 { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(!root || root == p || root == q) return root; TreeNode *leftAncestor = lowestCommonAncestor(root->left,p,q); TreeNode *rightAncestor = lowestCommonAncestor(root->right,p,q); if(leftAncestor && rightAncestor) return root; return leftAncestor ? leftAncestor : rightAncestor; } };
#include <iostream> using namespace std; int main() { int N; cin >> N; int pa = 0, pb = 0, ans = 1; for (int i = 0; i < N; ++i) { int a, b; cin >> a >> b; ans += max(0, min(a, b) - max(pa, pb) + 1); if (pa == pb) --ans; pa = a, pb = b; } cout << ans << endl; return 0; }
#include "chercheurMot.hpp" #include <regexBuilder.hpp> #include <utilitaires/fonctionsClasseString.hpp> #include <utilitaires/recupPageHTML.hpp> #include <boost/regex.hpp> #include <sstream> namespace { std::string createURL( const std::string & inMotARechercher ) { std::ostringstream url; url << "http://www.dictionnaire-japonais.com/search.php?w="; url << inMotARechercher; url << "&t=1"; return url.str(); } int extractNbResultats( const std::string & inCodePage ) { int nbResultats = -1; RegexBuilder regexBuilder( "./regex/DictionnaireJaponais.regex" ); std::string regExpStr = regexBuilder.getRegex( "nombre_resultat" ); boost::regex regExp( regExpStr ); boost::smatch resultats; if( boost::regex_match( inCodePage, resultats, regExp, boost::match_extra ) ) { std::istringstream iss( resultats[ 1 ] ); iss >> nbResultats; } return nbResultats; } std::vector< std::string > * parserMot( const std::string & inMotsFrancais ) { std::vector< std::string > * outListeMotsFrancais = new std::vector< std::string >(); std::istringstream issMotsFrancais( inMotsFrancais ); std::string motFrancais; while ( std::getline( issMotsFrancais, motFrancais, ',' ) ) { outListeMotsFrancais->push_back( trim( motFrancais ) ); } return outListeMotsFrancais; } std::vector< Mot > extractMots( const std::string & inCodePage ) { std::vector< Mot > outListeMots; RegexBuilder regexBuilder( "./regex/DictionnaireJaponais.regex" ); std::string regExpStr = regexBuilder.getRegex( "liste_mots" ); boost::regex regExp( regExpStr ); boost::smatch resultats; if( boost::regex_match( inCodePage, resultats, regExp, boost::match_extra ) ) { for( unsigned int i = 0; i < resultats.captures( 1 ).size(); ++i ) { std::string harakata = resultats.captures( 1 )[ i ]; std::string kanji = resultats.captures( 2 )[ i ]; std::string romanji = resultats.captures( 3 )[ i ]; std::string francais = resultats.captures( 4 )[ i ]; outListeMots.push_back( Mot( harakata, romanji, parserMot( francais ) ) ); } } return outListeMots; } std::vector< Mot > parser( const std::string & inCodePage ) { std::vector< Mot > outListeMots; try { int nbResultats = extractNbResultats( inCodePage ); if ( nbResultats > 0 ) { outListeMots = extractMots( inCodePage ); } } catch (std::exception e) { } return outListeMots; } } // unnamed namespace std::vector< Mot > ChercheurMot::Chercher( const std::string & inMotARechercher ) { RecupPageHTML recupPageHTML; std::string codePage = recupPageHTML.recuperationSynchrone( createURL( inMotARechercher ) ); return parser( codePage ); }
/** * Copyright (C) Omar Thor, Aurora Hernandez - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * * Written by * Omar Thor <omar@thorigin.com>, 2018 * Aurora Hernandez <aurora@aurorahernandez.com>, 2018 */ #ifndef DMTK_ALGORITHM_KNN_HPP #define DMTK_ALGORITHM_KNN_HPP #include "dmtk/element.hpp" #include <unordered_set> #include <unordered_map> #include <limits> DMTK_NAMESPACE_BEGIN /** * Predict the label of the row by using k samples from the model provided * * @param model * @param row * @param k * @return the predicated label */ template<typename Container> auto predict_by_knn( const Container& sample_model, const typename Container::value_type& test_element, const size_t& k) -> std::decay_t<decltype(get_label(test_element))> { std::unordered_set<size_t> used_rows; using label_type = std::decay_t<decltype(get_label(test_element))>; std::unordered_map<label_type, size_t> counters; //Test every row for every other row, at current K //Check if k closest rows are above the threshold //First, find the k closest auto sample_size = sample_model.size(); //Find K closest points and store accuracy for (size_t k_sample_idx = 0; k_sample_idx < k; ++k_sample_idx) { /** * The closest sample row index and distance that is unused */ auto closest_sample_row_dist = euclidean_distance(test_element, sample_model[0]); size_t closest_sample_row_idx = 0; for (size_t sample_row_idx = 1; sample_row_idx < sample_size; ++sample_row_idx) { //Check if row has not already been sampled if(used_rows.find(sample_row_idx) == used_rows.end()) { auto temp_sample_dist = euclidean_distance(test_element, sample_model[sample_row_idx]); if(closest_sample_row_dist > temp_sample_dist) { closest_sample_row_dist = temp_sample_dist; closest_sample_row_idx = sample_row_idx; } } } //Mark closest sample_row as used used_rows.emplace(closest_sample_row_idx); //Increment hit counter for label const auto& label = get_label(sample_model[closest_sample_row_idx]); ++counters[label]; } auto counters_it = counters.begin(), counters_end = counters.end(); if(counters_it != counters_end) { auto guess = (*counters_it++).first; size_t guess_freq = (*counters_it++).second; for (; counters_it != counters_end; ++counters_it) { const auto& c = (*counters_it); if(c.second > guess_freq) { guess = c.first; guess_freq = c.second; } } if(guess.empty()) { throw std::runtime_error("No labels matched"); } return guess; } else { throw std::runtime_error("Prediction not possible"); } } /** * Sample various knn values by splitting a input container into two parts and sampling the statistical success rate of it * * @param test_runs * @return */ template<size_t SkipLastN = 1, typename Container> std::unordered_map<size_t, float> sample_knn_values(Container& cont, size_t test_runs = 1, float split_dataset = 0.75, size_t max_k_test = std::numeric_limits<size_t>::max()) { std::unordered_map<size_t, std::vector<float>> test_model_predictions; for(size_t i = 0; i < test_runs; ++i) { auto [sample_data, test_data] = split(cont, split_dataset); auto sample_data_size = sample_data.size(); auto test_data_size = test_data.size(); auto k_max = std::min(max_k_test, sample_data_size); //For every K for(size_t k = 1; k < k_max; k+=2) { //test only odd numbers size_t correct_labels = 0; //Test every row for the value K for(size_t test_idx = 0, test_count = test_data_size; test_idx < test_count; ++test_idx) { //Attempt to predict test_row with k nearest neighbours const auto& predicated_label = predict_by_knn(sample_data, test_data[test_idx], k); const auto& expected_label = get_label(test_data[test_idx]); if(predicated_label == expected_label) { ++correct_labels; } } // Save the correctness of the training test_model_predictions[k].push_back(static_cast<float>(correct_labels) / static_cast<float>(test_data_size)); } } std::unordered_map<size_t, float> ret; for(auto& res : test_model_predictions) { float mean = 0; for(const auto& a : res.second) { mean += a; } ret[res.first] = mean / res.second.size(); } return ret; } /** * Maximizes the K-NN of sample test runs over the provided data set */ template<size_t SkipLastN = 1, typename Container> auto maximize_knn (Container& cont, size_t test_runs = 1, float split_dataset = 0.75, size_t max_k_test = std::numeric_limits<size_t>::max()) { auto opt = sample_knn_values(cont, test_runs, split_dataset, max_k_test); auto res_it = std::max_element(opt.begin(), opt.end(), [](const auto& left, const auto& right) { return left.first > right.first; }); return *res_it; } DMTK_NAMESPACE_END #endif /* DMTK_ALGORITHM_KNN_HPP */
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int MAXN = 2e5 + 100; double a[MAXN]; int main() { int n;double w,sum; scanf("%d%lf",&n,&w); for (int i = 0;i < n+n; i++) scanf("%lf",&a[i]); sort(a,a+n+n); if (a[0]*2 <= a[n]) sum = a[0]*3*n; else sum = a[n]*1.5*n; printf("%lf",min(sum,w)); return 0; }
#include "../src/Dvector.h" #include <iostream> #include <cassert> #include <sstream> int main(){ Dvector v0 = Dvector(); Dvector v = Dvector(3,10); Dvector v2 = Dvector(4,10); Dvector v3 = Dvector(3,11); assert(v3.size() == 3); bool faux = (v == v2); assert(faux == false ); bool faux2 = (v == v3); assert (faux2 == false); }
/* * Program: Warping.cpp * Usage: Implement warping logics */ #include "Warping.h" Warper::Warper(){ this->ut = Utils(); } // Start-up of warping, using homography void Warper::warpImage(CImg<unsigned char> &src, CImg<unsigned char> &dst, Axis ax, int offset_x, int offset_y){ cimg_forXY(dst, x, y){ int src_x = getXAfterWarping(x + offset_x, y + offset_y, ax), src_y = getYAfterWarping(x + offset_x, y + offset_y, ax); if(src_x >= 0 && src_x < src.width() && src_y >= 0 && src_y < src.height()){ for(int i=0; i<src.spectrum(); i++) dst(x, y, i) = ut.bilinearInterpolate(src, src_x, src_y, i); } } } // Warping tools functions float Warper::getMaxXAfterWarping(CImg<unsigned char> &input, Axis ax_){ float result = getXAfterWarping(0, 0, ax_); if(getXAfterWarping(input.width()-1, 0, ax_) > result){ result = getXAfterWarping(input.width()-1, 0, ax_); } if(getXAfterWarping(0, input.height()-1, ax_) > result){ result = getXAfterWarping(0, input.height()-1, ax_); } if(getXAfterWarping(input.width()-1, input.height()-1, ax_) > result){ result = getXAfterWarping(input.width()-1, input.height()-1, ax_); } return result; } float Warper::getMinXAfterWarping(CImg<unsigned char> &input, Axis ax_){ float result = getXAfterWarping(0, 0, ax_); if(getXAfterWarping(input.width()-1, 0, ax_) < result){ result = getXAfterWarping(input.width()-1, 0, ax_); } if(getXAfterWarping(0, input.height()-1, ax_) < result){ result = getXAfterWarping(0, input.height()-1, ax_); } if(getXAfterWarping(input.width()-1, input.height()-1, ax_) < result){ result = getXAfterWarping(input.width()-1, input.height()-1, ax_); } return result; } float Warper::getMaxYAfterWarping(CImg<unsigned char> &input, Axis ax_){ float result = getYAfterWarping(0, 0, ax_); if(getYAfterWarping(input.width()-1, 0, ax_) > result){ result = getYAfterWarping(input.width()-1, 0, ax_); } if(getYAfterWarping(0, input.height()-1, ax_) > result){ result = getYAfterWarping(0, input.height()-1, ax_); } if(getYAfterWarping(input.width()-1, input.height()-1, ax_) > result){ result = getYAfterWarping(input.width()-1, input.height()-1, ax_); } return result; } float Warper::getMinYAfterWarping(CImg<unsigned char> &input, Axis ax_){ float result = getYAfterWarping(0, 0, ax_); if(getYAfterWarping(input.width()-1, 0, ax_) < result){ result = getYAfterWarping(input.width()-1, 0, ax_); } if(getYAfterWarping(0, input.height()-1, ax_) < result){ result = getYAfterWarping(0, input.height()-1, ax_); } if(getYAfterWarping(input.width()-1, input.height()-1, ax_) < result){ result = getYAfterWarping(input.width()-1, input.height()-1, ax_); } return result; } int Warper::getHeightAfterWarping(CImg<unsigned char> &input, Axis ax_){ int max_height = getMaxYAfterWarping(input, ax_), min_height = getMinYAfterWarping(input, ax_); return max_height - min_height; } int Warper::getWidthAfterWarping(CImg<unsigned char> &input, Axis ax_){ int max_width = getMaxXAfterWarping(input, ax_), min_width = getMinXAfterWarping(input, ax_); return max_width - min_width; } // Must move images to fix best after warping void Warper::moveImageByOffset(CImg<unsigned char> &src, CImg<unsigned char> &dst, float offset_x, float offset_y){ cimg_forXY(dst, x, y){ int src_x = x + offset_x, src_y = y + offset_y; if(src_x >= 0 && src_x < src.width() && src_y >= 0 && src_y < src.height()){ for(int i=0; i<src.spectrum(); i++) dst(x, y, i) = src(src_x, src_y, i); } } }
#include <iostream> #include "nrainhas.h" using namespace std; int main(int argc, char *argv[ ]){ string cmd = ""; cmd = argv[1]; NRainhas nR = NRainhas(cmd); nR.gegarArquivo(); return 0; }
#pragma once class PostProccessing { public: PostProccessing(); };
// Created on: 1991-04-15 // Created by: Philippe DAUTRY // Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GccEnt_QualifiedLin_HeaderFile #define _GccEnt_QualifiedLin_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <GccEnt_Position.hxx> #include <gp_Lin2d.hxx> #include <Standard_Boolean.hxx> //! Describes a qualified 2D line. //! A qualified 2D line is a line (gp_Lin2d line) with a //! qualifier which specifies whether the solution of a //! construction algorithm using the qualified line (as an argument): //! - is 'enclosed' by the line, or //! - is built so that both the line and it are external to one another, or //! - is undefined (all solutions apply). //! Note: the interior of a line is defined as the left-hand //! side of the line in relation to its orientation (i.e. when //! moving from the start to the end of the curve). class GccEnt_QualifiedLin { public: DEFINE_STANDARD_ALLOC //! Constructs a qualified line by assigning the qualifier //! Qualifier to the line Qualified. //! Qualifier may be: //! - GccEnt_enclosed if the solution is enclosed by the line, or //! - GccEnt_outside if both the solution and the line are external to one another, or //! - GccEnt_unqualified if all solutions apply. //! Note : the interior of a line is defined as the left-hand //! side of the line in relation to its orientation. Standard_EXPORT GccEnt_QualifiedLin(const gp_Lin2d& Qualified, const GccEnt_Position Qualifier); //! Returns a 2D line to which the qualifier is assigned. Standard_EXPORT gp_Lin2d Qualified() const; //! Returns the qualifier of this qualified line, if it is "enclosed" or //! "outside", or //! - GccEnt_noqualifier if it is unqualified. Standard_EXPORT GccEnt_Position Qualifier() const; //! Returns true if the solution is unqualified and false in //! the other cases. Standard_EXPORT Standard_Boolean IsUnqualified() const; //! Returns true if the solution is Enclosed in the Lin2d and false in //! the other cases. Standard_EXPORT Standard_Boolean IsEnclosed() const; //! Returns true if the solution is Outside the Lin2d and false in //! the other cases. Standard_EXPORT Standard_Boolean IsOutside() const; protected: private: GccEnt_Position TheQualifier; gp_Lin2d TheQualified; }; #endif // _GccEnt_QualifiedLin_HeaderFile
#include "Racional.h" Racional::Racional(){ } Racional::Racional(int num,int den){ this->numerador = num; this->denominador = den; } int Racional::getNumerador(){ return numerador; } void Racional::setNumerador(int num){ numerador = num; } int Racional::getDenominador(){ return denominador; } void Racional::setDenominador(int den){ denominador = den; }
// // main.cpp // VectorClass // // Created by Vincent Liang on 12/15/19. // Copyright © 2019 Vincent Liang. All rights reserved. // #include "Vector.hpp" #include <iostream> int main(int argc, const char * argv[]) { Vector<int> hi(1,0); hi.push_back(25); hi.push_back(50); hi.push_back(75); hi.push_back(100); hi.push_back(125); for(int i = 0; i < hi.size(); ++i) { std::cout << hi.at(i) << " "; } std::cout << std::endl; hi.insert(3,150); for(int i = 0; i < hi.size(); ++i) { std::cout << hi.at(i) << " "; } std::cout << std::endl; hi.erase(3); for(int i = 0; i < hi.size(); ++i) { std::cout << hi.at(i) << " "; } std::cout << std::endl; Vector<int> bye; //= hi; bye = hi; for(int i = 0; i < bye.size(); ++i) { std::cout << bye.at(i) << " "; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2005-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef SVG_MANAGER_H #define SVG_MANAGER_H #ifdef SVG_SUPPORT class VisualDevice; class OpBitmap; class LayoutProperties; class URL; class SVGContext; class SVGPath; class TempBuffer; class ComplexAttr; class OpInputAction; class LogicalDocument; class SVGImage; class HTML_Element; class OpRect; class SVGImageRef; class SVGTreeIterator; class OpFile; class SVGFilterInputImageGenerator; class SvgProperties; class CSS_property_list; #include "modules/svg/svg_external_types.h" // for SVGUrlReference #include "modules/logdoc/logdocenum.h" #include "modules/logdoc/namespace.h" #include "modules/dom/domeventtypes.h" #include "modules/display/cursor.h" #include "modules/inputmanager/inputmanager.h" #include "modules/doc/html_doc.h" // For HTML_Document::SCROLL_ALIGN, not really needed soon #include "modules/doc/doctypes.h" #ifndef SVG_DOCUMENT_CLASS # define SVG_DOCUMENT_CLASS FramesDocument #endif // !SVG_DOCUMENT_CLASS class SVG_DOCUMENT_CLASS; /** * Main SVG external API. This is the entry point for most SVG * operations. * * @section conventions Conventions used in this interface * * If a method accepts a argument of type HTML_Element named 'root' * then the Type() of the HTML_Element must be Markup::SVGE_SVG. If a method * accepts a argument of type HTML_Element named 'element' then the * namespace of the HTML_Element must be svg (HTML_Element::GetNsType() * == NS_SVG). * * @author Erik Dahlstrom (ed@opera.com) & David Vest (davve@opera.com) * */ class SVGManager { public: /** * This is needed for destruction to work */ virtual ~SVGManager() {} /** * This class is a container for events that is sent to the SVG module. */ class EventData { public: /** * Constructor. Initializes all members to zero or default * values. */ EventData(); /** * This is the DOM_EventType enumerator representing the event if one * exists. */ DOM_EventType type; HTML_Element *target; /**< Target. */ SVG_DOCUMENT_CLASS* frm_doc; /**< The current frames document of the target */ int modifiers; /**< Shift key state. */ /* UIEvent */ int detail; /**< Detail (repeat count for ONCLICK). */ /* MouseEvent */ int screenX; /**< MouseEvent: screen X position. */ int screenY; /**< MouseEvent: screen Y position. */ int offsetX; /**< MouseEvent: offset X position. */ int offsetY; /**< MouseEvent: offset Y position. */ int clientX; /**< MouseEvent: client X position. */ int clientY; /**< MouseEvent: client Y position. */ int button; /**< MouseEvent: button. */ }; /** * Initiate the handling of an event. * @param data The data of the event. @see EventData. * * @return OpBoolean::IS_TRUE means that the event has been * handled. OpBoolean::IS_FALSE means that the event hasn't been * handled. OpStatus::ERR_NO_MEMORY is return if a OOM occurs. */ virtual OP_BOOLEAN HandleEvent(const EventData& data) = 0; /** * Initialize a root element to be a SVG root. * * Must be called on every SVG root node before rendering it. * * @param root The root element of the SVG. Should not be NULL. * @param logdoc The document containing the SVG. Should not be NULL. */ virtual SVGContext* CreateDocumentContext(HTML_Element* root, LogicalDocument* logdoc) = 0; /** * Parse a SVG attribute * * This method parses a string attribute into the corresponding SVG object * @param element The element the attribute is associated to * @param doc The current frames document * @param attr_name The attribute type * @param ns The attribute namespace index * @param str The string to parser * @param strlen The length of the string to parse * @param outValue The resulting value * @param outValueType The type of the resulting value * @return OpBoolean::IS_TRUE if the attribute was parsed * successfully. OpBoolean::IS_FALSE if the string couldn't be * parsed. OpStatus::ERR_NO_MEMORY if OOM occured. */ virtual OP_BOOLEAN ParseAttribute(HTML_Element* element, SVG_DOCUMENT_CLASS* doc, int attr_name, int ns, const uni_char* str, unsigned strlen, void** outValue, ItemType &outValueType) = 0; /** * Navigate to element. If the URL is external to the SVG * document, the URL is saved in outurl and expected to be * navigated to by the caller. * * @param elm The element to get the URL for. Can be any SVG element. * @param doc The current frames document * @param outurl A pointer to a pointer where the external URL will be * saved if that is the case. It will be set to NULL otherwise. * @param event The event that has trigged the navigation. * @param window_target The adress of a pointer that will point to * the name of the window that should be target of the link, for * instance _blank or _parent. Can be NULL. * @param modifiers The current modifier keys * @return OpBoolean::IS_TRUE if it was an internal URL. * OpBoolean::IS_FALSE If it is an external url OR the url could * not be retreived. Note that OpBoolean::IS_FALSE is not a * guarantee that the URL was external only that it wasn't * internal. OpStatus::ERR_NO_MEMORY if OOM occured */ virtual OP_BOOLEAN NavigateToElement(HTML_Element *elm, SVG_DOCUMENT_CLASS* doc, URL** outurl, DOM_EventType event = ONCLICK, const uni_char** window_target = NULL, ShiftKeyState modifiers = SHIFTKEY_NONE) = 0; /** * Ask the SVG module what graphic element, if any, is intersected * at a coordinate (x, y). The coordinates are relative to * upper-right corner of the SVG image. 'target' is set to NULL if * no graphical element matches the coordinates. This variant will * save the offset of the element within the viewport. * * @param root The root element of the SVG to find the element in * @param doc The current frames document * @param x The x coordinate @param y The y coordinate * @param element The matched element is saved here. It is set to * NULL if no graphics element matches. * @param offset_x Reference to where the offset in x will be saved * @param offset_y Reference to where the offset in y will be saved */ virtual OP_BOOLEAN FindSVGElement(HTML_Element* root, SVG_DOCUMENT_CLASS* doc, int x, int y, HTML_Element** element, int& offset_x, int& offset_y) = 0; /** * Transform coordinates from the SVGDocument coordinate system to the element coordinate system. * The element coordinate system's origo is at its boundingbox top-left corner. * * @param element The element to transform coordinates to * @param doc The frames document that has the element * @param io_x The x coordinate (in SVGDocument coordinates, out element coordinates) * @param io_y The y coordinate (in SVGDocument coordinates, out element coordinates) */ virtual OP_BOOLEAN TransformToElementCoordinates(HTML_Element* element, SVG_DOCUMENT_CLASS* doc, int& io_x, int& io_y) = 0; /** * Invalidate element * * The element to invalidate caches for. This removes cached data * as bounding boxes and other temporal calculations. * * @param element The element to invalidate caches for. * @param doc The current frames document */ virtual void InvalidateCaches(HTML_Element* element, SVG_DOCUMENT_CLASS* doc = NULL) = 0; /** * Start an animation * * @param root The root element * @param doc The current frames document * @return OpStatus::ERR_NO_MEMORY if OOM. OpStatus::OK otherwise. */ virtual OP_STATUS StartAnimation(HTML_Element* root, SVG_DOCUMENT_CLASS* doc) = 0; /** * Stop an animation * * @param root The root element * @param doc The current frames document * @return OpStatus::ERR_NO_MEMORY if OOM. OpStatus::OK otherwise. */ virtual OP_STATUS StopAnimation(HTML_Element* root, SVG_DOCUMENT_CLASS* doc) = 0; /** * Pause an animation * * @param root The root element * @param doc The current frames document * @return OpStatus::ERR_NO_MEMORY if OOM. OpStatus::OK otherwise. */ virtual OP_STATUS PauseAnimation(HTML_Element* root, SVG_DOCUMENT_CLASS* doc) = 0; /** * Pause an animation * * @param root The root element * @param doc The current frames document * @return OpStatus::ERR_NO_MEMORY if OOM. OpStatus::OK otherwise. */ virtual OP_STATUS UnpauseAnimation(HTML_Element* root, SVG_DOCUMENT_CLASS* doc) = 0; #ifdef ACCESS_KEYS_SUPPORT /** * Process the press of an access key on a element * * @param doc The current frames document * @param element The element that was activated * @param key The access key used */ virtual OP_STATUS HandleAccessKey(SVG_DOCUMENT_CLASS* doc, HTML_Element* element, uni_char access_key) = 0; #endif // ACCESS_KEYS_SUPPORT /** * Allocate and create an SVGPath. * * @param path The path will be returned here * @return OpStatus::ERR_NO_MEMORY if OOM. OpStatus::OK otherwise. */ virtual OP_STATUS CreatePath(SVGPath** path) = 0; /** * Handle a specific action, returns TRUE if handled by svg. * * @param action The action * @param clicked_element The svg element that the action is related to * @param doc The Document that the svg root element is in * @return TRUE if handled, FALSE otherwise */ virtual BOOL OnInputAction(OpInputAction* action, HTML_Element* clicked_element, SVG_DOCUMENT_CLASS* doc) = 0; /** * Called when something has changed in an SVG document. * * @param is_addition TRUE if node was just inserted, FALSE if node will be removed. * @param doc The document where the SVG resides. * @param parent The parent of the element that was changed (needed since the child may have been removed already). * @param child The element that changed. * @param is_addition TRUE if the child was added to the tree, FALSE otherwise. */ virtual OP_STATUS OnSVGDocumentChanged(SVG_DOCUMENT_CLASS *doc, HTML_Element *parent, HTML_Element *child, BOOL is_addition) = 0; /** * This function must be called when styles change on an SVG element. This can for instance be caused by * applying new pseudo classes as when hovering the element. * * @param doc The document where the SVG resides. * @param element The element that have had new CSS styles applied. * @param changes Change flags generated during property loading. SVG has its special PROPS_CHANGED_SVG_* namespace. * * @return OpStatus::OK if there was no problem, OpStatus::ERR_NO_MEMORY if an OOM situation was encountered. */ virtual OP_STATUS HandleStyleChange(SVG_DOCUMENT_CLASS *doc, HTML_Element* element, unsigned int changes) = 0; /** * This function must be called when a SVG or XLink attribute changes on a SVG element. * * @param doc The document where the SVG resides. * @param element The element whose attribute has changed. * @param attr The attribute that has changed. It's exact type depends on the namespace. See ns. * @param ns The namespace of the attribute in attr. Must be NS_SVG or NS_XLINK. * @param was_removed TRUE if the attribute was removed (and thus cannot be read on the element). FALSE if it was added or modified. * * @return OpStatus::OK if there was no problem, OpStatus::ERR_NO_MEMORY if an OOM situation was encountered. */ virtual OP_STATUS HandleSVGAttributeChange(SVG_DOCUMENT_CLASS *doc, HTML_Element* element, Markup::AttrType attr, NS_Type ns, BOOL was_removed) = 0; /** * This function must be called when text in a SVG document changes. * * @param doc The document where the SVG resides. * @param element The element * * @return OpStatus::OK if there was no problem, OpStatus::ERR_NO_MEMORY if an OOM situation was encountered. */ virtual OP_STATUS HandleCharacterDataChanged(SVG_DOCUMENT_CLASS *doc, HTML_Element* element) = 0; /** * This function must be called when an inline object inside an SVG document is ignored. * Inline objects include for example raster images and foreignObject elements. * * @param doc The document where the SVG resides. * @param element The element corresponding to the ignored inline (resource) * * @return OpStatus::OK if there was no problem, OpStatus::ERR_NO_MEMORY if an OOM situation was encountered. */ virtual OP_STATUS HandleInlineIgnored(SVG_DOCUMENT_CLASS* doc, HTML_Element* element) = 0; /** * This function must be called when an inline object inside an SVG document changes. * Inline objects include for example raster images and foreignObject elements. * * @param doc The document where the SVG resides. * @param element The changed element * @param is_content_changed Content changed flag, used to decide for example if shadow trees need to be recreated * * @return OpStatus::OK if there was no problem, OpStatus::ERR_NO_MEMORY if an OOM situation was encountered. */ virtual OP_STATUS HandleInlineChanged(SVG_DOCUMENT_CLASS* doc, HTML_Element* element, BOOL is_content_changed=FALSE) = 0; /** * This function repaints the given element if it's inside an svg document fragment. Only the area which the * element was last painted to is repainted. This can be used for e.g text selections where nothing changed * except the selection, and the painted area is unaffected. * * @param doc The document where the SVG resides * @param element The element to repaint * * @return OpStatus::OK if there was no problem, OpStatus::ERR_NO_MEMORY if an OOM situation was encountered. */ virtual OP_STATUS RepaintElement(SVG_DOCUMENT_CLASS* doc, HTML_Element* element) = 0; /** * Informs the svg module that a font is about to be deleted so * that data related to it can be removed from internal caches. * * @param font_about_to_be_deleted The OpFont that is going to be deleted */ virtual void HandleFontDeletion(OpFont* font_about_to_be_deleted) = 0; /** * Returns the element that has the event handlers for a svg node. This is normally the node * itself, except when having use tags. This method never returns NULL. * * @param element The traversed node that an event should pass. Must not be null. * @return The event target element */ virtual HTML_Element* GetEventTarget(HTML_Element* element) = 0; /** * This calculates the effective cursor for an element and should only * be called when the HasCursor flag is set on the HTML_Element. * * @param elm The element that may have a cursor set * @return The cursortype to use */ virtual CursorType GetCursorForElement(HTML_Element* elm) = 0; /** * Get an URL from a xlink::href attribute * * @param elm The element to extract the url from * @param root_url The document's URL. Needed for correct resolving of relative URLs. * @return A pointer to the URL. NULL if no URL was found. */ virtual URL* GetXLinkURL(HTML_Element* elm, URL* root_url = NULL) = 0; /** * Check if the given svg element is visible. The element must have been layouted * and must have a trustworthy/non-dirty non-empty screen boundingbox to be considered * visible. * * @param element The element to check * @return TRUE if the element is visible, FALSE otherwise */ virtual BOOL IsVisible(HTML_Element* element) = 0; /** * Checks whether the element is one of the text class elements * * @param element The element to be checked, must not be NULL. * @return TRUE if the element is a text content element, FALSE otherwise. */ virtual BOOL IsTextContentElement(HTML_Element* element) = 0; /** * Given a LogicalDocument and a svg:svg node in that document, * this returns the SVGImage for that SVG or NULL if it wasn't a * real SVG image. * * @param log_doc The LogicalDocument to look in * @param element The root svg element * @return The corresponding SVGImage, or NULL */ virtual SVGImage* GetSVGImage(LogicalDocument* log_doc, HTML_Element* element) = 0; /** * Check if the SVGManager is currently selecting text. * * @return TRUE if selecting text, FALSE otherwise */ virtual BOOL IsInTextSelectionMode() const = 0; /** * If the element is contained in an SVG fragment with a non-empty * text selection, clear out the selection. * * @param element The element, assumed to be non-NULL and in the SVG namespace. */ virtual void ClearTextSelection(HTML_Element* element) = 0; /** * If the element is editable and has non-empty text selection, deletes the selected content. * * @param element The element, assumed to be non-NULL and in the SVG namespace. */ virtual void RemoveSelectedContent(HTML_Element* element) = 0; /** * If the element under the cursor is editable, shows the caret at cursor position. * This should be used if the caret should be shown without focusing the element * (focusing the element would cause the caret to show). * * @param doc The document where the SVG resides * @param element The element, assumed to be non-NULL and in the SVG namespace. */ virtual void ShowCaret(SVG_DOCUMENT_CLASS* doc, HTML_Element* element) = 0; /** * Hides the editable element's caret. * * @param doc The document where the SVG resides * @param element The element containing the caret, assumed to be non-NULL and in the SVG namespace. */ virtual void HideCaret(SVG_DOCUMENT_CLASS* doc, HTML_Element* element) = 0; /** * If the element is editable inserts the given text at the caret position. * * @param element the element, assumed to be non-NULL and in the SVG namespace. * @param text The text to be inserted. */ virtual void InsertTextAtCaret(HTML_Element* element, const uni_char* text) = 0; /** * Checks if given point (in document coordinates) is over a text selection. * * @param doc The document the element with selection is within. * @param elm The element containing the selection. * @param doc_point - The point to be checked if it's over the selection. */ virtual BOOL IsWithinSelection(SVG_DOCUMENT_CLASS* doc, HTML_Element* elm, const OpPoint& doc_point) = 0; /** * If the element is contained in an SVG fragment with a non-empty * text selection, assign 'length' the character length of that * text selection and return TRUE. * * @param element The element, assumed to be non-NULL and in the SVG namespace. * @param length The result length, altered iff the method succeeds. * @return TRUE if there is a valid text selection, FALSE otherwise */ virtual BOOL GetTextSelectionLength(HTML_Element* element, unsigned& length) = 0; /** * If the element is contained in an SVG fragment with a non-empty * text selection, copy the text selection to 'buffer' and return * TRUE. * * @param element The element, assumed to be non-NULL and in the SVG namespace. * @param buffer The result buffer, altered iff the method succeeds. * @return TRUE if there is a valid text selection and copying of * the selected text to 'buffer' is successful, FALSE otherwise. */ virtual BOOL GetTextSelection(HTML_Element* element, TempBuffer& buffer) = 0; /** * If the element is contained in an SVG fragment with a non-empty * text selection, retrieves a list of rectangles enclosing the selection. * * @param element The element, assumed to be non-NULL and in the SVG namespace. * @param list A list of rectangles to be filled in (rectangles are in document coordinates). */ virtual void GetSelectionRects(SVG_DOCUMENT_CLASS* doc, HTML_Element* element, OpVector<OpRect>& list) = 0; /** * Returns a tooltip for a node in the string, or leaves it empty * if there is none suitable. This is basically the textcontent of * any existing title element. * * @param elm The element to get a svg tooltip for. * @param result The string object to insert the tooltip into. * @return OpStatus::OK normally, or OpStatus::ERR_NO_MEMORY if OOM. */ virtual OP_STATUS GetToolTip(HTML_Element* elm, OpString& result) = 0; /** * Returns TRUE if the given element is focusable. * To be used for tabbing among elements inside an SVG. * * Does not consider the visibility of the element (e.g. display:none) * * @param doc The SVG_DOCUMENT_CLASS that contains the element * @param elm The element to check * @return TRUE if the element is focusable, FALSE if not. */ virtual BOOL IsFocusableElement(SVG_DOCUMENT_CLASS* doc, HTML_Element* elm) = 0; /** * Returns TRUE if the given element is editable. * * Does not consider the visibility of the element (e.g. display:none) * * @param doc The SVG_DOCUMENT_CLASS that contains the element * @param elm The element to check * @return TRUE if the element is editable, FALSE if not. */ virtual BOOL IsEditableElement(SVG_DOCUMENT_CLASS* doc, HTML_Element* elm) = 0; /** * Enter editing mode for the specified element. * * @param doc The SVG_DOCUMENT_CLASS that contains the element * @param elm Root element for the editing operation */ virtual void BeginEditing(SVG_DOCUMENT_CLASS* doc, HTML_Element* elm, FOCUS_REASON reason) = 0; /** * Get navigation data for element. * The navigation rectangle is relative to SVG root element's content box. * * @param elm Element to query for navigational data. * @param elm_box If successful, contains a rect describing the extents of the element. * @return OpStatus::OK if navigational data could be acquired. */ virtual OP_STATUS GetNavigationData(HTML_Element* elm, OpRect& elm_box) = 0; /** * Get element's rectangle. The rectangle is in document coordinates. * * @param elm Element to query for the rectangle. * @param elm_box If successful, contains a rect describing the extents of the element. * @return OpStatus::OK if the rectangle could be acquired. */ virtual OP_STATUS GetElementRect(HTML_Element* elm, OpRect& elm_box) = 0; /** * Query element for navigational target (AKA. userspecified navigation/nav-*). * * @param elm Element to query. * @param direction Direction of interrest in degrees (0=right,90=up, etc). * @param nway Number of directions to consider (2, 4, etc). * @param preferred_next_elm If TRUE is returned, contains target element. * @return TRUE if a specified target (in the direction) was found, otherwise FALSE */ virtual BOOL HasNavTargetInDirection(HTML_Element* elm, int direction, int nway, HTML_Element*& preferred_next_elm) = 0; /** * Get an iterator that will iterate through the navigatable element in a SVG document. * * When done with the iterator, release it with the ReleaseIterator() method. * * @param elm Element where iteration will start. * @param search_area Document area to consider when looking for navigatable elements. If NULL, all elements are considered. * @param layout_props LayoutProperties corresponding to elm, or NULL if none available. * @param nav_iterator The returned iterator. * @return OpStatus::OK if successful. */ virtual OP_STATUS GetNavigationIterator(HTML_Element* elm, const OpRect* search_area, LayoutProperties* layout_props, SVGTreeIterator** nav_iterator) = 0; #ifdef SEARCH_MATCHES_ALL /** * Get an iterator that will iterate through the highlightable elements in a SVG document. * * When done with the iterator, release it with the ReleaseIterator() method. * * @param elm Element where iteration will start. * @param layout_props LayoutProperties corresponding to elm, or NULL if none available. * @param first_hit The first selection element * @param iterator The returned iterator. * @return OpStatus::OK if successful. */ virtual OP_STATUS GetHighlightUpdateIterator(HTML_Element* elm, LayoutProperties* layout_props, SelectionElm* first_hit, SVGTreeIterator** iterator) = 0; #endif // SEARCH_MATCHES_ALL #ifdef RESERVED_REGIONS /** * Get an iterator that will iterate through the elements of an SVG document * that define reserved regions. A reserved region is an area of the document * where the document reacts to a subset of DOM events. This subset is defined * by tweaks, but is usually restricted to touch events. * * This iterator is used by layout to capture the bounding boxes of these * elements on requests from platforms that would like to know which input * events they need to send to document, and which they can handle without * synchronizing with Core. * * When done with the iterator, release it with the ReleaseIterator() method. * * @param elm Element where iteration will start. * @param search_area Area to consider when looking for navigatable elements, * in document coordinates. If NULL, all elements are considered. * @param region_iterator The returned iterator. * @return OpStatus::OK if successful. */ virtual OP_STATUS GetReservedRegionIterator(HTML_Element* elm, const OpRect* search_area, SVGTreeIterator** region_iterator) = 0; #endif // RESERVED_REGIONS /** * Release a SVGTreeIterator. * * @param iter Iterator to release. */ virtual void ReleaseIterator(SVGTreeIterator* iter) = 0; /** * Scroll to the given rect. * * @param rect The rect to scroll to * @param align How to align the rect * @param scroll_to The element that is being scrolled to */ virtual void ScrollToRect(OpRect rect, SCROLL_ALIGN align, HTML_Element *scroll_to) = 0; /** * Instruct the SVG module to update the highlight information for an element. * * @param vd VisualDevice where updating will take place. * @param elm Element to update. * @param in_paint Specify whether to paint (TRUE) or invalidate (FALSE) the highlight. */ virtual void UpdateHighlight(VisualDevice* vd, HTML_Element* elm, BOOL in_paint) = 0; /** * Handle event finished, also see FramesDocument::HandleEventFinished. * * @param event The event that finished * @param target The target element */ virtual void HandleEventFinished(DOM_EventType event, HTML_Element *target) = 0; /** * Returns TRUE if the given element is allowed to create a frame (see FramesDocument::GetNewIFrame). * For elements that aren't in the svg namespace this method will return FALSE. * * @param elm The element to check * @return TRUE if a frame is allowed to be created for the given element, FALSE if not */ virtual BOOL AllowFrameForElement(HTML_Element* elm) = 0; /** * Returns TRUE if the given element may receive events (see for instance HTML_Document::MouseAction and MouseListener::GetMouseHitView). * For elements that aren't in the svg namespace this method will return FALSE. * * @param elm The element to check * @return TRUE if a the element may receive events, FALSE if not */ virtual BOOL AllowInteractionWithElement(HTML_Element* elm) = 0; /** * Checks if scripting should be enabled for the given document. * This is meant to be used to prevent script execution on svg and any embedded content inside * an svg when the svg is referenced from an html:img element. * * @param doc The SVG_DOCUMENT_CLASS to check * @return TRUE if scripting should be enabled, FALSE if not */ virtual BOOL IsEcmaScriptEnabled(SVG_DOCUMENT_CLASS* doc) = 0; /** * Gets the string from the SVG class attribute. * * @param elm The element to read from * @param baseVal If TRUE then the base value will be returned, otherwise the animated value will be returned * @return The ClassAttribute representation of the class attribute */ virtual const ClassAttribute* GetClassAttribute(HTML_Element* elm, BOOL baseVal) = 0; /** * This is a hook from HLDocProfile::InsertElement. * * @param elm The element that was inserted * @return The status */ virtual OP_STATUS InsertElement(HTML_Element* elm) = 0; /** * This is a hook from HLDocProfile::EndElement. * * @param elm The element that was ended * @return The status */ virtual OP_STATUS EndElement(HTML_Element* elm) = 0; /** * This applies an svg filter chain using the given filter input image generator which must be implemented * by the caller, see svg_filters.h. Requires VegaOpPainter. * * @param ref The SVGURLReference from the CSS cascade (or otherwise) that points to a <filter> element * @param doc The FramesDocument that wants to resolve the URL reference, may be the same as the document that contains the <filter> element, but need not be. * @param generator The input image generator, memory is owned by the caller * @param screen_targetbbox The boundingbox in screen units of the content to filter * @param painter The painter that will be used to apply the filter effect * @param affected_area The area that the painter touched, in screen units * @return The status */ virtual OP_STATUS ApplyFilter(SVGURLReference ref, SVG_DOCUMENT_CLASS* doc, SVGFilterInputImageGenerator* generator, const OpRect& screen_targetbbox, OpPainter* painter, OpRect& affected_area) = 0; /** * Creates the OpFont that corresponds to the given OpFontInfo. * * @param doc The SVG_DOCUMENT_CLASS that contains the element * @param out_opfont A newly allocated OpFont that corresponded to the OpFontInfo * @return OpStatus::ERR_NO_MEMORY for OOM, OpStatus::ERR_NULL_POINTER if any of the parameters were NULL, * OpStatus::ERR if other errors such as wrong type of element or parsing errors. * OpStatus::OK if successful. The OpFontInfo is only set if the return value was successful. */ virtual OP_STATUS GetOpFont(HTML_Element* fontelm, UINT32 size, OpFont** out_opfont) = 0; /** * Gets the OpFontInfo that corresponds to the given SVGFont. * * @param doc The SVG_DOCUMENT_CLASS that contains the element * @param font_element The element that is the root of the SVGFont, must be of type Markup::SVGE_FONT or Markup::SVGE_FONT_FACE * @param out_fontinfo A newly allocated OpFontInfo that describes the font, the caller of the method owns this memory * @return OpStatus::ERR_NO_MEMORY for OOM, OpStatus::ERR_NULL_POINTER if any of the parameters were NULL, * OpStatus::ERR if other errors such as wrong type of element or parsing errors. * OpStatus::OK if successful. The OpFontInfo is only set if the return value was successful. */ virtual OP_STATUS GetOpFontInfo(HTML_Element* font_element, OpFontInfo** out_fontinfo) = 0; /** * Draw a string to the VisualDevice. */ virtual OP_STATUS DrawString(VisualDevice* vis_dev, OpFont* font, int x, int y, const uni_char* txt, int len, int char_spacing_extra = 0) = 0; #ifdef SVG_GET_PRESENTATIONAL_ATTRIBUTES /** * Get the equivalent CSS properties for the presentational attributes * of an SVG element. * * @param [in] elm The SVG element to to get attributes for. May not be NULL, and must * be in the SVG namespace. * @param [in] hld_profile The HLDocProfile for the document the element belongs to. * @param [out] list CSS declarations will be stored here. May not be NULL. * @return OpStatus::OK on success, or OpStatus::ERR_NO_MEMORY. */ virtual OP_STATUS GetPresentationalAttributes(HTML_Element* elm, HLDocProfile* hld_profile, CSS_property_list* list) = 0; #endif // SVG_GET_PRESENTATIONAL_ATTRIBUTES /** * Switch the LogicalDocument associated with an SVG root's SVGDocumentContext. * * If the SVGDocumentContext of @c root is already associated with the * specified LogicalDocument, nothing happens. * * @param logdoc The LogicalDocument to switch to. May not be NULL. * @param root The root of the SVG fragment. May not be NULL. */ virtual void SwitchDocument(LogicalDocument* logdoc, HTML_Element* root) = 0; #ifdef USE_OP_CLIPBOARD /** * If the element is a SVG editable element it should paste the contents * of the clipboard at the current caret position. * * @param element The element, assumed to be non-NULL and in the SVG namespace. * @param clipboard The instance of the clipboard the data from should be pasted. */ virtual void Paste(HTML_Element* elm, OpClipboard* clipboard) = 0; /** * If the element is a SVG editable element and has a non-empty selection it * should place the selected content in the clipboard and then remove it from * itself. * * @param element The element, assumed to be non-NULL and in the SVG namespace. * @param clipboard The instance of the clipboard the data from should be placed in. */ virtual void Cut(HTML_Element* elm, OpClipboard* clipboard) = 0; /** * If the element is a SVG element and has a non-empty selection it * should place the selected content in the clipboard. This operation must not * affect the selection in any way. * * @param element The element, assumed to be non-NULL and in the SVG namespace. * @param clipboard The instance of the clipboard the data from should be placed in. */ virtual void Copy(HTML_Element* elm, OpClipboard* clipboard) = 0; /** * If the element is a SVG editable element it should be informed about the end * of the clipboard operation. * * @param element The element, assumed to be non-NULL and in the SVG namespace. */ virtual void ClipboardOperationEnd(HTML_Element* elm) = 0; #endif // USE_OP_CLIPBOARD }; #endif // SVG_SUPPORT #endif // _SVG_MANAGER_
#include <iostream> #include <cmath> #include <string> #include <unistd.h> #include <fcntl.h> #include <error.h> #include <cstring> #include <fstream> #include <deque> #include "./Node.hpp" #define LEFT 0 #define RIGHT 1 using std::getline; using std::cout; using std::endl; using std::string; using std::ifstream; using std::deque; class Tree{ public: Tree(int n, string treeFileName); Tree() = delete; ~Tree(); Node* MakeTreeNode(int n); void Insert(int n); void Insert(Node** treeRoot, int n); void Clear(); void _clear(Node* node); void ReadTree(string fileName); void _toFileHelper(int fd, Node* node); void ToFile(); void BFT(Node* node); void PostOrder(); void _post(Node* node); void PreOrder(); void _pre(Node* node); void InOrder(); void _in(Node* node); int fd; int size; string fileName; Node* root; };
// #include <boost/multiprecision/cpp_int.hpp> // using boost::multiprecision::cpp_int; #include <bits/stdc++.h> using namespace std; // ¯\_(ツ)_/¯ #define f first #define s second #define p push #define mp make_pair #define pb push_back #define eb emplace_back #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define foi(i, a, n) for (i = (a); i < (n); ++i) #define foii(i, a, n) for (i = (a); i <= (n); ++i) #define fod(i, a, n) for (i = (a); i > (n); --i) #define fodd(i, a, n) for (i = (a); i >= (n); --i) #define debug(x) cout << '>' << #x << ':' << x << endl; #define all(v) v.begin(), v.end() #define sz(x) ((int)(x).size()) #define endl " \n" #define newl cout<<"\n" #define MAXN 100005 #define MOD 1000000007LL #define EPS 1e-13 #define INFI 1000000000 // 10^9 #define INFLL 1000000000000000000ll //10^18 // ¯\_(ツ)_/¯ //#define l long int //#define d double #define ll long long int #define ull unsigned long long int #define ld long double #define vi vector<int> #define vll vector<long long> #define vvi vector<vector<int>> #define vvll vector<vll> #define vvld vector<vector<ld>> //vector<vector<int>> v(10, vector<int>(20,500)); 2d vector initialization. of 10 rows and 20 columns, with value 500. #define mii map<int, int> #define mll map<long long, long long> #define pii pair<int, int> #define pll pair<long long, long long> #define fast_io() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); ll tc, n, m, k; // ll ans = 0, c = 0; // ll i, j; // ll a, b; // ll x, y; // stackoverflow code for typename info, including compile time info, for c++ 11/14 // begin #include <cstddef> #include <stdexcept> #include <cstring> #include <ostream> #ifndef _MSC_VER # if __cplusplus < 201103 # define CONSTEXPR11_TN # define CONSTEXPR14_TN # define NOEXCEPT_TN # elif __cplusplus < 201402 # define CONSTEXPR11_TN constexpr # define CONSTEXPR14_TN # define NOEXCEPT_TN noexcept # else # define CONSTEXPR11_TN constexpr # define CONSTEXPR14_TN constexpr # define NOEXCEPT_TN noexcept # endif #else // _MSC_VER # if _MSC_VER < 1900 # define CONSTEXPR11_TN # define CONSTEXPR14_TN # define NOEXCEPT_TN # elif _MSC_VER < 2000 # define CONSTEXPR11_TN constexpr # define CONSTEXPR14_TN # define NOEXCEPT_TN noexcept # else # define CONSTEXPR11_TN constexpr # define CONSTEXPR14_TN constexpr # define NOEXCEPT_TN noexcept # endif #endif // _MSC_VER class static_string { const char* const p_; const std::size_t sz_; public: typedef const char* const_iterator; template <std::size_t N> CONSTEXPR11_TN static_string(const char(&a)[N]) NOEXCEPT_TN : p_(a) , sz_(N-1) {} CONSTEXPR11_TN static_string(const char* p, std::size_t N) NOEXCEPT_TN : p_(p) , sz_(N) {} CONSTEXPR11_TN const char* data() const NOEXCEPT_TN {return p_;} CONSTEXPR11_TN std::size_t size() const NOEXCEPT_TN {return sz_;} CONSTEXPR11_TN const_iterator begin() const NOEXCEPT_TN {return p_;} CONSTEXPR11_TN const_iterator end() const NOEXCEPT_TN {return p_ + sz_;} CONSTEXPR11_TN char operator[](std::size_t n) const { return n < sz_ ? p_[n] : throw std::out_of_range("static_string"); } }; inline std::ostream& operator<<(std::ostream& os, static_string const& s) { return os.write(s.data(), s.size()); } template <class T> CONSTEXPR14_TN static_string type_name() { #ifdef __clang__ static_string p = __PRETTY_FUNCTION__; return static_string(p.data() + 31, p.size() - 31 - 1); #elif defined(__GNUC__) static_string p = __PRETTY_FUNCTION__; # if __cplusplus < 201402 return static_string(p.data() + 36, p.size() - 36 - 1); # else return static_string(p.data() + 46, p.size() - 46 - 1); # endif #elif defined(_MSC_VER) static_string p = __FUNCSIG__; return static_string(p.data() + 38, p.size() - 38 - 7); #endif } // end // for testing purposes namespace funuser::superuser { struct batman { float arr[100]; }; } using namespace funuser::superuser; int main() { fast_io(); #ifndef ONLINE_JUDGE freopen("../input.txt", "r", stdin); freopen("../output.txt", "w", stdout); #endif auto bruce = batman(); vector<ll> ahah; auto ci = make_tuple(ahah, 04.0, "hola", 'a', bruce.arr, bruce); debug(type_name<decltype(ci)>()); debug(type_name<decltype(mp(bruce, 10))>()); debug(type_name<decltype(ahah)>()); debug(type_name<decltype(100)>()); return 0; } /* the output >type_name<decltype(ci)>(): std::tuple<std::vector<long long int, std::allocator<long long int> >, double, const char*, char, float*, funuser::superuser::batman> >type_name<decltype(mp(bruce, 10))>(): std::pair<funuser::superuser::batman, int> >type_name<decltype(ahah)>(): std::vector<long long int> >type_name<decltype(100)>(): int */
// ДАННЫЙ ПРИМЕР ОТОБРАЖАЕТ СОСТОЯНИЯ КЛАВИШ НА ИХ СВЕТОДИОДАХ: // * Строки со звёздочкой являются необязательными. // (нажимайте удерживайте и отпускайте кнопки клавиатуры) // // #include "../iarduino_I2C_Keyboard.h" // Подключаем библиотеку для работы с клавиатурой I2C-flash. #include "Serial.h" iarduino_I2C_Keyboard kbd(0x09,4,2); // Объявляем объект kbd для работы с функциями и методами библиотеки iarduino_I2C_Keyboard, указывая адрес модуля на шине I2C, количество кнопок в линии, количество линий с кнопками. // Если объявить объект без указания адреса (iarduino_I2C_Keyboard kbd(false,4,2);), то адрес будет найден автоматически. void setup(){ // delay(500); // * Ждём завершение переходных процессов связанных с подачей питания. kbd.begin(); // Инициируем работу с клавиатурой. kbd.setEncoding(4,2,'d'); // * Присваиваем 4 кнопке в 2 ряду символ 'd'. } // (по умолчанию кнопкам присвоены символы "12345678"). // void loop(){ // // Выполняем действия по изменению состояния клавиш: // kbd.setLed(1,1, kbd.getKey(1,1,KEY_PUSHED ) ); // Включаем 1 светодиод 1 ряда если его кнопка нажимается. kbd.setLed(2,1, kbd.getKey(2,1,KEY_RELEASED) ); // Включаем 2 светодиод 1 ряда если его кнопка отпускается. kbd.setLed(3,1, kbd.getKey(3,1,KEY_CHANGED ) ); // Включаем 3 светодиод 1 ряда если его кнопка нажимается или отпускается. kbd.setLed(4,1, kbd.getKey(4,1,KEY_STATE ) ); // Включаем 4 светодиод 1 ряда пока его кнопка нажата. kbd.setLed(1,2, kbd.getKey(1,2,KEY_TRIGGER ) ); // Включаем 1 светодиод 2 ряда по состоянию его кнопки в режиме переключателя. kbd.setLed(2,2, kbd.getKey(2,2,KEY_HOLD_05 )>0 ); // Включаем 2 светодиод 2 ряда если его кнопка удерживается дольше 0,5 сек. kbd.setLed(3,2, kbd.getKey(3,2,KEY_HOLD_05 )>1 ); // Включаем 3 светодиод 2 ряда если его кнопка удерживается дольше 1,0 сек. kbd.setLed('d', kbd.getKey('d',KEY_HOLD_05 )>2 ); // Включаем 4 светодиод 2 ряда если его кнопка удерживается дольше 1,5 сек. } // // // ПРИМЕЧАНИЕ: // // Так как функцией setEncoding(), в коде Setup(), 4 кнопке 2 ряда // // был присвоен символ 'd', то обращаться к кнопке и её светодиоду // // можно либо по номеру и ряду, либо по привоенному ей символу. // // // // Функция getKey() вызванная с параметром KEY_HOLD_05 возвращает // // время удержания кнопки в 1/2 долях секунд (число от 0 до 7): // // 0 - кнопка не удерживается или удерживается менее 1/2 секунды. // // 1...7 - кнопка удерживается 1...7 * 1/2 секунд. // // Более точное время удержания можно получить функцией getTime() // int main() { setup(); for (;;) { loop(); } }
#pragma once #include "QuestionStateImpl.h" class CQuestionStateForTesting : public qp::CQuestionState { public: LOKI_DEFINE_VISITABLE() CQuestionStateForTesting(qp::CConstQuestionPtr const& question) :qp::CQuestionState(question) ,doSubmitCallCounter(0) { } int doSubmitCallCounter; protected: void DoSubmit()override { ++doSubmitCallCounter; } };
#pragma once namespace aeEngineSDK { /*************************************************************************************************/ /* Forward declarations needed /*************************************************************************************************/ struct aeVector3; struct aeMatrix3; /*************************************************************************************************/ /* @struct aeQuaternion /* /* @brief A quaternion. /*************************************************************************************************/ struct AE_UTILITY_EXPORT aeQuaternion { /*************************************************************************************************/ /* Variables /*************************************************************************************************/ public: float x, y, z, w; /*************************************************************************************************/ /* Constructors /*************************************************************************************************/ public: aeQuaternion() : w(1.0f), x(), y(), z() {} aeQuaternion(float x, float y, float z, float w) : w(w), x(x), y(y), z(z) { } ~aeQuaternion(); aeQuaternion(const aeQuaternion& Q); /*************************************************************************************************/ /* @fn aeQuaternion(float RotX, float RotY, float RotZ); /* /* @brief Construct from Euler angles /* /* @param RotX The pitch angle. /* @param RotY The yaw angle. /* @param RotZ The roll angle. /*************************************************************************************************/ aeQuaternion(float RotX, float RotY, float RotZ); /*************************************************************************************************/ /* @fn aeQuaternion(aeVector3 Axis, float Angle); /* /* @brief Construct from an axis-angle pair /* /* @param Axis The axis. /* @param Angle The angle. /*************************************************************************************************/ aeQuaternion(const aeVector3& Axis, float Angle); /*************************************************************************************************/ /* @fn aeQuaternion(const aeVector3& LookAt, aeVector3 Up = aeVector3 /* /* @brief Constructor. /* /* @param LookAt The look at. /*************************************************************************************************/ aeQuaternion(const aeVector3& LookAt, aeVector3 Up); /*************************************************************************************************/ /* @fn explicit aeQuaternion(aeVector3 Normalized); /* /* @brief Construct from a normalized quaternion stored in a vec3 /* /* @param Normalized The normalized. /*************************************************************************************************/ explicit aeQuaternion(aeVector3 Normalized); /*************************************************************************************************/ /* Boolean operations /*************************************************************************************************/ public: bool operator== (const aeQuaternion& o) const; bool operator!= (const aeQuaternion& o) const; bool Equal(const aeQuaternion& o, float epsilon = aeMath::FLOAT_EPSILON) const; public: aeQuaternion operator+ (const aeQuaternion& Q); aeQuaternion operator- (const aeQuaternion& Q); aeQuaternion operator* (const aeQuaternion& Q); aeQuaternion operator/ (const aeQuaternion& Q); aeQuaternion operator* (const float& F); aeVector3 operator* (const aeVector3& V); public: aeQuaternion& operator+= (const aeQuaternion& Q); aeQuaternion& operator-= (const aeQuaternion& Q); aeQuaternion& operator*= (const aeQuaternion& Q); aeQuaternion& operator/= (const aeQuaternion& Q); aeQuaternion& operator*= (const float& F); /*************************************************************************************************/ /* Functions /*************************************************************************************************/ public: /*************************************************************************************************/ /* @fn aeMatrix3 GetMatrix() const; /* /* @brief Returns a matrix representation of the quaternion /* /* @return The matrix. /*************************************************************************************************/ aeMatrix3 GetMatrix() const; /*************************************************************************************************/ /* @fn aeMatrix3 GetTransposedMatrix() const; /* /* @brief Gets transposed matrix. /* /* @return The transposed matrix. /*************************************************************************************************/ aeMatrix3 GetTransposedMatrix() const; /*************************************************************************************************/ /* @fn aeVector3 GetEulerAngles() const; /* /* @brief Returns the Euler angles. /* /* @return The Euler angles. /*************************************************************************************************/ aeVector3 GetEulerAngles() const; /*************************************************************************************************/ /* @fn float Norm(); /* /* @brief Gets the norm. /* /* @return A float. /*************************************************************************************************/ float Norm() const; /*************************************************************************************************/ /* @fn float Magnitude(); /* /* @brief Gets the magnitude. /* /* @return A float. /*************************************************************************************************/ float Magnitude(); /*************************************************************************************************/ /* @fn void Normalize(); /* /* @brief Normalizes this object. /*************************************************************************************************/ void Normalize(); /*************************************************************************************************/ /* @fn aeQuaternion Normalized(); /* /* @brief Returns a copy of the normalized quaternion. /* /* @return An aeQuaternion. /*************************************************************************************************/ aeQuaternion Normalized(); /*************************************************************************************************/ /* @fn aeQuaternion Scale(float s); /* /* @brief Scales. /* /* @param s The float to process. /* /* @return An aeQuaternion. /*************************************************************************************************/ aeQuaternion Scale(float s) const; /*************************************************************************************************/ /* @fn aeQuaternion Inverse(); /* /* @brief Gets the inverse. /* /* @return An aeQuaternion. /*************************************************************************************************/ aeQuaternion Inverse() const; /*************************************************************************************************/ /* @fn void Conjugate(); /* /* @brief Conjugates this object. /*************************************************************************************************/ void Conjugate(); /*************************************************************************************************/ /* @fn aeQuaternion Conjugate(); /* /* @brief Returns a copy of the quaternion conjugate. /* /* @return An aeQuaternion. /*************************************************************************************************/ aeQuaternion Conjugated() const; /*************************************************************************************************/ /* @fn aeVector3 Rotate(const aeVector3& in); /* /* @brief Rotate a point by this quaternion /* /* @param in The vector rotate. /* /* @return An aeVector3. /*************************************************************************************************/ aeVector3 Rotate(const aeVector3& in); /*************************************************************************************************/ /* @fn aeVector3 GetDirection(); /* /* @brief Gets the direction. /* /* @return The direction. /*************************************************************************************************/ aeVector3 GetDirection(); public: /*************************************************************************************************/ /* @fn static void Interpolate(aeQuaternion& pOut, const aeQuaternion& pStart, const aeQuaternion& pEnd, float pFactor); /* /* @brief Performs a spherical interpolation between two quaternions and writes the result into /* the third. /* /* @param [in,out] pOut Target object to received the interpolated rotation. /* @param pStart Start rotation of the interpolation at factor == 0. /* @param pEnd End rotation, factor == 1. /* @param pFactor Interpolation factor between 0 and 1. Values outside of this range /* yield undefined results. /*************************************************************************************************/ static void Interpolate(aeQuaternion& pOut, const aeQuaternion& pStart, const aeQuaternion& pEnd, float pFactor); }; }
#ifndef MYTCPSERVER_H #define MYTCPSERVER_H #include <QObject> #include <QtNetwork/QTcpServer> #include "mytcpsocket.h" #include "waitqueue.h" #include <QVector> class gameServer; class MyTCPServer : public QTcpServer { public: MyTCPServer(gameServer *gs_); ~MyTCPServer(); void incomingConnection(qintptr); void Read_Data(MyTCPSocket*); void Send_Data(MyTCPSocket* client, QString msg); //void Disconnect(MyTCPSocket*); //QVector<MyTCPSocket*> clients; gameServer *gs; signals: void readyReadClient(MyTCPSocket*); }; #endif // MYTCPSERVER_H
// // buffer.hpp // // // Created by Six on 1/9/2020. // Copyright 1/9/2020 Six. All rights reserved. // #ifndef _GJ_MESSAGES_BUFFER_HPP #define _GJ_MESSAGES_BUFFER_HPP #include <string.h> // for memcpy #include <vector> // for um...vector. #include <functional> // for std::function #include <stdint.h> // for int types like uint8_t /// /// @class Buffer /// @brief Manages a buffer of memory /// @tparam T The type of data this buffer represents, must be a built-in /// data type or an aggregate of built-in data types. In other words, /// memcpy() must work on T. /// @details Buffer helps manage memory for data that needs to be aliased, /// copied, shared, transmitted, and received. It supports a variety of /// operations that help get these jobs done. /// template<typename T> class Buffer { public: // type aids typedef T value_type; //!< The value type typedef value_type* pointer; //!< Pointer to the value type typedef const value_type* const_pointer; //!< Pointer to constant value type typedef value_type& reference; //!< Reference to value type typedef const value_type& const_reference; //!< Constant reference to value type typedef std::vector<uint8_t> storage_t; //!< Used to store the data typedef typename storage_t::iterator iterator; //!< Used to iterate over the buffer typedef typename storage_t::const_iterator const_iterator; //!< Used to iterate over the buffer typedef typename storage_t::reverse_iterator reverse_iterator; //!< Used to iterate backwards over the buffer typedef typename storage_t::const_reverse_iterator const_reverse_iterator; //!< Used to iterate backwards over the buffer typedef typename storage_t::difference_type difference_type; //!< The difference type /// /// @brief construct an instance, the buffer will not be wrapped /// Buffer(void) : m_Data(), m_WrapData(NULL), m_WrapDataLen(0), m_Wrapped(false) { } /// /// @brief copy an instance, the buffer will not be wrapped /// @param[in] right The data to copy /// Buffer(const_reference right) : m_Data(sizeof(value_type)), m_WrapData(NULL), m_WrapDataLen(0), m_Wrapped(false) { memcpy(&m_Data.at(0), &right, sizeof(value_type)); } /// /// @brief copy an instance, the buffer will not be wrapped /// @param[in] right The buffer to copy from /// Buffer(const Buffer& right) : m_Data(right.m_Data), m_WrapData(NULL), m_WrapDataLen(0), m_Wrapped(false) { } /// /// @brief construct an instance, the buffer will not be wrapped /// @param[in] buf The location of the data to copy /// @param[in] len The length of data to copy /// Buffer(const void* buf,size_t len) : m_Data(len), m_WrapData(NULL), m_WrapDataLen(0), m_Wrapped(false) { memcpy(&m_Data.at(0), buf, len); } /// /// @brief construct an instance and hint at the buffer's size /// @param[in] len Hint to how big the buffer will need to be (bytes) /// @details This will cause the buffer to be created empty, but /// give a hint to the underlying system of how much memory the buffer /// will eventually need. /// explicit Buffer(size_t len) : m_Data(), m_WrapData(NULL), m_WrapDataLen(0), m_Wrapped(false) { m_Data.reserve(len); } /// /// @brief destroy an instance /// ~Buffer(void) {} /// /// @brief assign a buffer, a complete duplication is made /// @param[in] right The buffer to assign from /// @return reference to self /// Buffer& operator=(const Buffer& right) { if(this != &right) { m_Data = right.m_Data; m_WrapData = right.m_WrapData; m_WrapDataLen = right.m_WrapDataLen; m_Wrapped = right.m_Wrapped; unwrapcopy(); } return *this; } /// /// @brief assign a buffer, a copy is made /// @param[in] right The data to assign from /// @return reference to self /// Buffer& operator=(const_reference right) { m_Data.resize(sizeof(value_type)); memcpy(&m_Data.at(0), &right, sizeof(value_type)); return *this; } /// /// @brief wrap a buffer /// @details Wrapping a buffer does not copy memory, it allows this /// buffer to reference the memory of another buffer, possibly of a /// different type.\n /// A wrapped buffer requires the lifetime of the wrapped memory to be /// longer than it's own. Also, wrapped buffers do not provide some of /// the memory overwrite/overread protection that unwrapped buffers have. /// @warning do not resize the source buf in any way until you unwrap /// this buffer. /// @param[in] buf The buffer to wrap template<typename other_t>void wrap(Buffer<other_t>& buf) { if(reinterpret_cast<void*>(&buf) == reinterpret_cast<void*>(this)) { return; } wrap(buf.ptr(), buf.size()); } /// /// @brief wrap a buffer /// @see template<typename other_t>void wrap(Buffer<other_t>& buf) /// @tparam other_t The type of the supplied buffer /// @warning The supplied buffer is const but this class is not, const /// correctness is up to the caller. /// @param[in] buf The buffer to wrap /// template<typename other_t>void wrap(const Buffer<other_t>& buf) { if((const void*)&buf == (void*)this) { return; } wrap(buf.ptr(), buf.size()); } /// /// @brief wrap a buffer around some raw memory /// @param[in] data Pointer to memory to wrap /// @param[in] len The length (bytes) of the memory /// void wrap(void* data, size_t len) { unwrap(); m_Wrapped = true; m_WrapData = reinterpret_cast<uint8_t*>(data); m_WrapDataLen = len; } /// /// @brief wrap a buffer around some raw memory /// @see void wrap(void*, size_t) /// @param[in] data Pointer to memory to wrap /// @param[in] len The length (bytes) of the memory /// @warning The supplied pointer is const but this class is not, const /// correctness is up to the caller. /// void wrap(const void* data, size_t len) { wrap(const_cast<void*>(data), len); } /// /// @brief unwrap the buffer /// void unwrap(void) { m_Wrapped = false; m_WrapData = NULL; m_WrapDataLen = 0; } /// /// @brief unwrap the buffer and copy the data /// @details This will copy the wrapped data to internal storage and /// unwrap the buffer. /// void unwrapcopy(void) { if(iswrapped()) { m_Data.resize(m_WrapDataLen); memcpy(&m_Data.at(0), m_WrapData, m_WrapDataLen); } unwrap(); } /// /// @brief Determine if the buffer is wrapped /// @return @li true if wrapped, @li false if not wrapped /// bool iswrapped(void) const { return m_Wrapped; } /// /// @brief alias an offset in the buffer /// @details This allows the buffer to be treated as a different type /// based on a byte offset. If this is being used as part of an /// accumulation system (like extracting a buffer from a network socket), /// then the accumulated parameter is incremented by the size of the /// aliased type. /// @tparam other_t The aliased type /// @param[in] offsetBytes The byte offset into the buffer at which to alias /// @param[in,out] accumulated The number of bytes accumulated so far, if not /// NULL then this will be incrememted by sizeof(other_t). /// @return Pointer to the aliased type template<typename other_t> other_t* alias(size_t offsetBytes=0, size_t* accumulated=NULL) { if(accumulated) { *accumulated += sizeof(other_t); } if (iswrapped()) { return reinterpret_cast<other_t*>(&m_WrapData[offsetBytes]); } else { return reinterpret_cast<other_t*>(&m_Data.at(offsetBytes)); } } /// /// @brief Const version to alias an offset in the buffer /// @details This allows the buffer to be treated as a different type /// based on a byte offset. If this is being used as part of an /// accumulation system (like extracting a buffer from a network socket), /// then the accumulated parameter is incremented by the size of the /// aliased type. /// @tparam other_t The aliased type /// @param[in] offsetBytes The byte offset into the buffer at which to alias /// @param[in] accumulated The number of bytes accumulated so far, if not /// NULL then this will be incrememted by sizeof(other_t). /// @return Pointer to the aliased type /// template<typename other_t> const other_t* alias(size_t offsetBytes=0, size_t* accumulated=NULL) const { if(accumulated) { *accumulated += sizeof(other_t); } if (iswrapped()) { return reinterpret_cast<const other_t*>(&m_WrapData[offsetBytes]); } else { return reinterpret_cast<const other_t*>(&m_Data.at(offsetBytes)); } } /// /// @brief Realign the buffer to have a new beginning /// @details Moves the buffer memory starting at new_beginning to the /// front of the buffer and shrinks the buffer size accordingly. Has no /// effect on wrapped buffers. /// @param[in] new_beginning The byte offset of the new beginning of the /// buffer. /// void realign(size_t new_beginning) { if(iswrapped()) { return; } const size_t new_size = size() - new_beginning; if(0 == new_size) { clear(); return; } memmove(&m_Data[0], &m_Data[new_beginning], new_size); resize(new_size); } // end realign /// /// @brief Copy bytes from the buffer /// @param[out] dest The destination pointer /// @param[in] amount The number of bytes to copy /// @param[in] offsetBytes The byte offset at which to start copying /// @param[in] accumulated The number of bytes accumulated so far, if not /// NULL then this will be incremented by amount. /// @warning Range checking is not performed by this function. /// void copybytes(void* dest, size_t amount, size_t offsetBytes=0, size_t* accumulated=NULL) const { if(accumulated) { *accumulated += amount; } if(iswrapped()) { memcpy(dest, &m_WrapData[offsetBytes], amount); } else { memcpy(dest, &m_Data.at(offsetBytes), amount); } } /// /// @brief Get a raw pointer to the buffer /// @return Raw pointer to the buffer /// pointer ptr(void) { return reinterpret_cast<pointer>(alias<uint8_t>(0)); } /// /// @brief Get a raw pointer to the buffer /// @return Raw pointer to the buffer /// const_pointer ptr(void) const { return reinterpret_cast<const_pointer>(alias<uint8_t>(0)); } /// /// @brief Get a reference to the buffer /// @return Reference to the buffer /// reference ref(void) { return *alias<value_type>(); } /// /// @brief Get a reference to the buffer /// @return Reference to the buffer /// const_reference ref(void) const { return *alias<value_type>(); } /// /// @brief Treat the buffer as an array and get a reference at an index /// @details This will treat the buffer as though it is an array of /// value_type and return the value_type at the requested index. /// @param[in] index The array index /// @returns Reference to the item at array offset index /// reference array(size_t index) { return reinterpret_cast<reference>(ptr()[index]); } /// /// @brief Treat the buffer as an array and get a reference at an index /// @details This will treat the buffer as though it is an array of /// value_type and return the value_type at the requested index. /// @param[in] index The array index /// @returns Reference to the item at array offset index /// const_reference array(size_t index) const { return reinterpret_cast<const_reference>(ptr()[index]); } /// /// @brief Treat the buffer as an array and get a pointer at an index /// @details This will treat the buffer as though it is an array of /// value_type and return the value_type* at the requested index. /// @param[in] index The array index /// @returns Pointer to the item at array offset index /// pointer arrayptr(size_t index) { return reinterpret_cast<pointer>(&(ptr()[index])); } /// /// @brief Treat the buffer as an array and get a pointer at an index /// @details This will treat the buffer as though it is an array of /// value_type and return the value_type* at the requested index. /// @param[in] index The array index /// @returns Pointer to the item at array offset index /// const_pointer arrayptr(size_t index) const { return reinterpret_cast<const_pointer>(&(ptr()[index])); } /// /// @brief Pointer operator /// @return a pointer to the start of the buffer /// const_pointer operator->(void) const { return ptr(); } /// /// @brief Pointer operator /// @return a pointer to the start of the buffer /// pointer operator->(void) { return ptr(); } /// /// @brief Dereference operator /// @return a reference to the start of the buffer /// const_reference operator*(void) const { return ref(); } /// /// @brief Dereference operator /// @return a reference to the start of the buffer /// reference operator*(void) { return ref(); } /// /// @brief Append to the end of the buffer /// @param[in] data Pointer to the data to append /// @param[in] len Length of the data to append (bytes) /// @return Reference to self /// Buffer& appendbytes(const void* data,size_t len) { const size_t startSize = size(); resize(startSize + len); memcpy(alias<uint8_t>(startSize),data,len); return *this; } /// /// @brief Append to the end of the buffer /// @tparam other_t Type of the data to append, used to determine the /// length to copy /// @param[in] data Pointer to the data to append /// @return Reference to self /// template <typename other_t> Buffer& append(const other_t* data) { return appendbytes(data,sizeof(other_t)); } /// /// @brief Append to the end of the buffer /// @tparam other_t Type of the data to append, used to determine the /// length to copy /// @param[in] data Reference to the data to append /// @return Reference to self /// template <typename other_t> Buffer& append(const other_t& data) { return appendbytes(&data,sizeof(other_t)); } /// /// @brief Get the size of the buffer /// @return Size of the buffer in bytes /// size_t size(void) const { if (iswrapped()) { return m_WrapDataLen; } else { return m_Data.size(); } } /// /// @brief Resize the buffer /// @param[in] size The new size of the buffer (bytes) /// @note This does nothing to a wrapped buffer /// void resize(size_t size) { if(!iswrapped()) { // can't resize wrapped buffer m_Data.resize(size); } } /// /// @brief Get the capacity of the buffer /// @returns Maximum number of bytes that the buffer can hold without /// suffering a memory reallocation penalty /// @note This is not useful for wrapped buffers /// size_t capacity(void) const { return m_Data.capacity(); } /// /// @brief Reserve memory for the buffer /// @details This hints to the underlying system how big the buffer /// will eventually need to be and reserves memory for that size. /// @param[in] size The size (bytes) to reserve /// void reserve(size_t size) { m_Data.reserve(size); } /// /// @brief Unwrap and empty the buffer /// void clear(void) { m_Data.clear(); unwrap(); } /// /// @brief Determine if the buffer is empty /// @return @li true if empty, @li false if not empy /// bool empty(void) const { if(!iswrapped()) { return m_Data.empty(); } else { return m_WrapDataLen == 0; } } /// /// @brief Iterate the buffer byte-by-byte with a callback /// @param[in] f The callback function, also supports C++11 lambdas /// void for_each(std::function<void(uint8_t)> f) { for(size_t ndx = 0; ndx < size(); ++ndx) { f(*alias<uint8_t>(ndx)); } } /// /// @brief Get an iterator to the start of the buffer /// @note Wrapped buffers do not support iterators /// @return iterator /// iterator begin(void) { if(iswrapped()) { return m_Data.end(); } return m_Data.begin(); } /// /// @brief Get a constant iterator to the start of the buffer /// @note Wrapped buffers do not support iterators /// @return const_iterator /// const_iterator begin(void) const { if(iswrapped()) { return m_Data.end(); } return m_Data.begin(); } /// /// @brief Get an iterator to the end of the buffer /// @return iterator /// iterator end(void) { return m_Data.end(); } /// /// @brief Get a constant iterator to the end of the buffer /// @return const_iterator /// const_iterator end(void) const { return m_Data.end(); } private: storage_t m_Data; uint8_t* m_WrapData; size_t m_WrapDataLen; bool m_Wrapped; }; // end class Buffer #endif // not defined _GJ_MESSAGES_BUFFER_HPP
//camera_control.cpp #include "camera_control.h" //define IO
#include <QHostAddress> #include "gateadapter.h" GateAdapter::GateAdapter(QObject *parent) : AdapterBase(parent) { setDataPort(&m_tcpSocket); } void GateAdapter::setAddress(QString address) { if (m_address == address) return; m_tcpSocket.connectToHost(QHostAddress(address), 5555); if(m_tcpSocket.waitForConnected(2000)) getStatus(); m_address = address; emit addressChanged(m_address); } void GateAdapter::setLightState(GateAdapter::LightState lightState) { if (m_lightState == lightState) return; MessageLight message; message.type = MESSAGE_SET_LIGHT_STATUS; message.state = lightState; char *tmp = reinterpret_cast<char*>(&message); QByteArray result = sendMessage(tmp, sizeof(message)); if(result.length() > 0) { if(result.length() != sizeof(MessageResult)) return; MessageResult answer; memcpy(reinterpret_cast<char*>(&answer), result.data(), sizeof(MessageResult)); if(answer.result == 1) { m_lightState = lightState; emit lightStateChanged(m_lightState); } } } void GateAdapter::setGateState(GateAdapter::GateState gateState) { if (m_gateState == gateState) return; MessageGate message; message.type = MESSAGE_SET_GATE_STATUS; message.status = gateState; char *tmp = reinterpret_cast<char*>(&message); QByteArray result = sendMessage(tmp, sizeof(message)); if(result.length() > 0) { if(result.length() != sizeof(MessageResult)) return; MessageResult answer; memcpy(reinterpret_cast<char*>(&answer), result.data(), sizeof(MessageResult)); if(answer.result == 1) { m_gateState = gateState; emit gateStateChanged(m_gateState); } } } void GateAdapter::setTemperature(float temperature) { if (qAbs(static_cast<double>(m_temperature) - static_cast<double>(temperature)) < 0.1) return; m_temperature = temperature; emit temperatureChanged(m_temperature); } void GateAdapter::setHumidity(float humidity) { if (qAbs(static_cast<double>(m_humidity) - static_cast<double>(humidity)) < 0.1) return; m_humidity = humidity; emit humidityChanged(m_humidity); } void GateAdapter::customProcessMessage(QByteArray message) { Q_UNUSED(message) } void GateAdapter::open(QString portName) { Q_UNUSED(portName) } void GateAdapter::close() { } QString GateAdapter::address() const { return m_address; } GateAdapter::LightState GateAdapter::lightState() const { return m_lightState; } GateAdapter::GateState GateAdapter::gateState() const { return m_gateState; } int GateAdapter::pulseDoor() { MessageCommand message; message.type = MESSAGE_PULSE_DOOR; char *tmp = reinterpret_cast<char*>(&message); QByteArray result = sendMessage(tmp, sizeof(message)); if(result.length() > 0) { if(result.length() != sizeof(MessageResult)) return -1; MessageResult answer; memcpy(reinterpret_cast<char*>(&answer), result.data(), sizeof(MessageResult)); return answer.result; } return -1; } int GateAdapter::pulseLight() { MessageCommand message; message.type = MESSAGE_PULSE_LIGHT; char *tmp = reinterpret_cast<char*>(&message); QByteArray result = sendMessage(tmp, sizeof(message)); if(result.length() > 0) { if(result.length() != sizeof(MessageResult)) return -1; MessageResult answer; memcpy(reinterpret_cast<char*>(&answer), result.data(), sizeof(MessageResult)); return answer.result; } return -1; } int GateAdapter::pulseGate() { MessageCommand message; message.type = MESSAGE_PULSE_GATE; char *tmp = reinterpret_cast<char*>(&message); QByteArray result = sendMessage(tmp, sizeof(message)); if(result.length() > 0) { if(result.length() != sizeof(MessageResult)) return -1; MessageResult answer; memcpy(reinterpret_cast<char*>(&answer), result.data(), sizeof(MessageResult)); return answer.result; } return -1; } QJSValue GateAdapter::getStatus() { QJSValue status; MessageCommand message; message.type = MESSAGE_GET_STATUS; char *tmp = reinterpret_cast<char*>(&message); QByteArray result = sendMessage(tmp, sizeof(message)); if(result.length() == 0) m_errorTransmitCounter++; else m_errorTransmitCounter = 0; setIsConnected(m_errorTransmitCounter < 3); if(result.length() > 0) { if(result.length() != sizeof(MessageStatus)) return status; MessageStatus answer; memcpy(reinterpret_cast<char*>(&answer), result.data(), sizeof(MessageStatus)); status.setProperty("light", answer.lightStatus); status.setProperty("gate", answer.gateStatus); status.setProperty("temperature", static_cast<double>(answer.temperature)); status.setProperty("humidity", static_cast<double>(answer.humidity)); if(m_lightState != static_cast<GateAdapter::LightState>(answer.lightStatus)) { m_lightState = static_cast<GateAdapter::LightState>(answer.lightStatus); emit lightStateChanged(m_lightState); } if(m_gateState != static_cast<GateAdapter::GateState>(answer.gateStatus)) { m_gateState = static_cast<GateAdapter::GateState>(answer.gateStatus); emit gateStateChanged(m_gateState); } setTemperature(answer.temperature); setHumidity(answer.humidity); return status; } return status; } float GateAdapter::temperature() const { return m_temperature; } float GateAdapter::humidity() const { return m_humidity; }
/*-------------------------------------------------------------------- This file is part of the Adafruit NeoMatrix library. This has been ported to the Spark. NeoMatrix is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NeoMatrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NeoMatrix. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------*/ #ifndef SPARK_NEOMATRIX_H #define SPARK_NEOMATRIX_H #include "Particle.h" #include "Adafruit_GFX.h" #include "neopixel.h" // Matrix layout information is passed in the 'matrixType' parameter for // each constructor (the parameter immediately following is the LED type // from NeoPixel.h). // These define the layout for a single 'unified' matrix (e.g. one made // from NeoPixel strips, or a single NeoPixel shield), or for the pixels // within each matrix of a tiled display (e.g. multiple NeoPixel shields). #define NEO_MATRIX_TOP 0x00 // Pixel 0 is at top of matrix #define NEO_MATRIX_BOTTOM 0x01 // Pixel 0 is at bottom of matrix #define NEO_MATRIX_LEFT 0x00 // Pixel 0 is at left of matrix #define NEO_MATRIX_RIGHT 0x02 // Pixel 0 is at right of matrix #define NEO_MATRIX_CORNER 0x03 // Bitmask for pixel 0 matrix corner #define NEO_MATRIX_ROWS 0x00 // Matrix is row major (horizontal) #define NEO_MATRIX_COLUMNS 0x04 // Matrix is column major (vertical) #define NEO_MATRIX_AXIS 0x04 // Bitmask for row/column layout #define NEO_MATRIX_PROGRESSIVE 0x00 // Same pixel order across each line #define NEO_MATRIX_ZIGZAG 0x08 // Pixel order reverses between lines #define NEO_MATRIX_SEQUENCE 0x08 // Bitmask for pixel line order // These apply only to tiled displays (multiple matrices): #define NEO_TILE_TOP 0x00 // First tile is at top of matrix #define NEO_TILE_BOTTOM 0x10 // First tile is at bottom of matrix #define NEO_TILE_LEFT 0x00 // First tile is at left of matrix #define NEO_TILE_RIGHT 0x20 // First tile is at right of matrix #define NEO_TILE_CORNER 0x30 // Bitmask for first tile corner #define NEO_TILE_ROWS 0x00 // Tiles ordered in rows #define NEO_TILE_COLUMNS 0x40 // Tiles ordered in columns #define NEO_TILE_AXIS 0x40 // Bitmask for tile H/V orientation #define NEO_TILE_PROGRESSIVE 0x00 // Same tile order across each line #define NEO_TILE_ZIGZAG 0x80 // Tile order reverses between lines #define NEO_TILE_SEQUENCE 0x80 // Bitmask for tile line order class Adafruit_NeoMatrix : public Adafruit_GFX, public Adafruit_NeoPixel { public: // Constructor for single matrix: // The pixel type is set because you'll probably only be using the WS2812B Adafruit_NeoMatrix(int w, int h, uint8_t pin = 6, uint8_t matrixType = NEO_MATRIX_TOP + NEO_MATRIX_LEFT + NEO_MATRIX_ROWS, uint8_t ledType = WS2812B); // Constructor for tiled matrices: // The pixel type is set because you'll probably only be using the WS2812B Adafruit_NeoMatrix(uint8_t matrixW, uint8_t matrixH, uint8_t tX, uint8_t tY, uint8_t pin = 6, uint8_t matrixType = NEO_MATRIX_TOP + NEO_MATRIX_LEFT + NEO_MATRIX_ROWS + NEO_TILE_TOP + NEO_TILE_LEFT + NEO_TILE_ROWS, uint8_t ledType = WS2812B); void drawPixel(int16_t x, int16_t y, uint16_t color), fillScreen(uint16_t color), setPassThruColor(uint32_t c), setPassThruColor(void), setRemapFunction(uint16_t (*fn)(uint16_t, uint16_t)); static uint16_t Color(uint8_t r, uint8_t g, uint8_t b); private: const uint8_t type; const uint8_t matrixWidth, matrixHeight, tilesX, tilesY; uint16_t (*remapFn)(uint16_t x, uint16_t y); uint32_t passThruColor; boolean passThruFlag = false; }; #endif // SPARK_NEOMATRIX_H
#include <iostream> #include<queue> using namespace std; /*IDEA: *if eventually you get a negative current petrol then that means that you cant start from where you started. Therefore you remove that pump out from queue and remove the petrol count of it too. In such a case you keep removing till you get a positive petrol count or else when the queue becomes empty. */ int circularTour(int petrol[],int dist[],int n){ queue<int> q; int curr=0; for(int start=0;start<n;start++){ q.push(start); curr+=petrol[start]-dist[start]; while(curr<0 && !q.empty() ){ curr=curr-(petrol[q.front()]-dist[q.front()]); q.pop(); } } if(!q.empty()) return q.front()+1; return -1; } int main(){ int petrol[]={60,10,140,80}; int dist[]={30,20,100,10}; int n=sizeof(petrol)/sizeof(petrol[0]); cout<<circularTour(petrol,dist,n); return 0; }
/** @file Decoration.cxx ** Visual elements added over text. **/ // Copyright 1998-2007 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstddef> #include <cstdlib> #include <cstring> #include <cstdio> #include <cstdarg> #include <stdexcept> #include <vector> #include <algorithm> #include <memory> #include "Platform.h" #include "Scintilla.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "Decoration.h" using namespace Scintilla; Decoration::Decoration(int indicator_) : indicator(indicator_) { } Decoration::~Decoration() { } bool Decoration::Empty() const { return (rs.Runs() == 1) && (rs.AllSameAs(0)); } DecorationList::DecorationList() : currentIndicator(0), currentValue(1), current(nullptr), lengthDocument(0), clickNotified(false) { } DecorationList::~DecorationList() { current = nullptr; } Decoration *DecorationList::DecorationFromIndicator(int indicator) { for (const std::unique_ptr<Decoration> &deco : decorationList) { if (deco->Indicator() == indicator) { return deco.get(); } } return nullptr; } Decoration *DecorationList::Create(int indicator, Sci::Position length) { currentIndicator = indicator; std::unique_ptr<Decoration> decoNew = std::make_unique<Decoration>(indicator); decoNew->rs.InsertSpace(0, length); std::vector<std::unique_ptr<Decoration>>::iterator it = std::lower_bound( decorationList.begin(), decorationList.end(), decoNew, [](const std::unique_ptr<Decoration> &a, const std::unique_ptr<Decoration> &b) { return a->Indicator() < b->Indicator(); }); std::vector<std::unique_ptr<Decoration>>::iterator itAdded = decorationList.insert(it, std::move(decoNew)); SetView(); return itAdded->get(); } void DecorationList::Delete(int indicator) { decorationList.erase(std::remove_if(decorationList.begin(), decorationList.end(), [=](const std::unique_ptr<Decoration> &deco) { return deco->Indicator() == indicator; }), decorationList.end()); current = nullptr; SetView(); } void DecorationList::SetCurrentIndicator(int indicator) { currentIndicator = indicator; current = DecorationFromIndicator(indicator); currentValue = 1; } void DecorationList::SetCurrentValue(int value) { currentValue = value ? value : 1; } bool DecorationList::FillRange(Sci::Position &position, int value, Sci::Position &fillLength) { if (!current) { current = DecorationFromIndicator(currentIndicator); if (!current) { current = Create(currentIndicator, lengthDocument); } } const bool changed = current->rs.FillRange(position, value, fillLength); if (current->Empty()) { Delete(currentIndicator); } return changed; } void DecorationList::InsertSpace(Sci::Position position, Sci::Position insertLength) { const bool atEnd = position == lengthDocument; lengthDocument += insertLength; for (const std::unique_ptr<Decoration> &deco : decorationList) { deco->rs.InsertSpace(position, insertLength); if (atEnd) { deco->rs.FillRange(position, 0, insertLength); } } } void DecorationList::DeleteRange(Sci::Position position, Sci::Position deleteLength) { lengthDocument -= deleteLength; for (const std::unique_ptr<Decoration> &deco : decorationList) { deco->rs.DeleteRange(position, deleteLength); } DeleteAnyEmpty(); if (decorationList.size() != decorationView.size()) { // One or more empty decorations deleted so update view. current = nullptr; SetView(); } } void DecorationList::DeleteLexerDecorations() { decorationList.erase(std::remove_if(decorationList.begin(), decorationList.end(), [=](const std::unique_ptr<Decoration> &deco) { return deco->Indicator() < INDIC_CONTAINER; }), decorationList.end()); current = nullptr; SetView(); } void DecorationList::DeleteAnyEmpty() { if (lengthDocument == 0) { decorationList.clear(); } else { decorationList.erase(std::remove_if(decorationList.begin(), decorationList.end(), [=](const std::unique_ptr<Decoration> &deco) { return deco->Empty(); }), decorationList.end()); } } void DecorationList::SetView() { decorationView.clear(); for (const std::unique_ptr<Decoration> &deco : decorationList) { decorationView.push_back(deco.get()); } } int DecorationList::AllOnFor(Sci::Position position) const { int mask = 0; for (const std::unique_ptr<Decoration> &deco : decorationList) { if (deco->rs.ValueAt(position)) { if (deco->Indicator() < INDIC_IME) { mask |= 1 << deco->Indicator(); } } } return mask; } int DecorationList::ValueAt(int indicator, Sci::Position position) { const Decoration *deco = DecorationFromIndicator(indicator); if (deco) { return deco->rs.ValueAt(position); } return 0; } Sci::Position DecorationList::Start(int indicator, Sci::Position position) { const Decoration *deco = DecorationFromIndicator(indicator); if (deco) { return deco->rs.StartRun(position); } return 0; } Sci::Position DecorationList::End(int indicator, Sci::Position position) { const Decoration *deco = DecorationFromIndicator(indicator); if (deco) { return deco->rs.EndRun(position); } return 0; }
// Tutorial task 1 #include "mbed.h" // Green LED DigitalOut led1(LED1); // Blue LED DigitalOut led2(LED2); // Red LED DigitalOut led3(LED3); void select_led(int l) { if (l==1) { led1 = true; led2 = false; led3 = false; } else if (l==2) { led1 = false; led2 = true; led3 = false; } else if (l==3) { led1 = false; led2 = false; led3 = true; } else if (l==0) { led1 = false; led2 = false; led3 = false; } else { led1 = true; led2 = true; led3 = true; } } int main() { int t=0, f=0; while(true) { f=(t%5)-1; select_led(f); wait(0.5); t++; } } // Tutorial task 2 #include "mbed.h" DigitalIn button(USER_BUTTON); DigitalOut led1(LED1); DigitalOut led2(LED2); DigitalOut led3(LED3); int main() { led1 = 1; led2 = 0; led3 = 1; while(true) { led1 = button == 0; led2 = !(button == 0); led3 = button == 0; wait(0.02); // 20 ms } }
/* * This node is to indicate the whole parking lot status * for example: idle for parking, fault at maintenance, car permitted, car rejected, ... * Inputs: * ROS message(string) * Outputs: * hardware modbus operation */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/time.h> #include <modbus/modbus.h> #include <iconv.h> #include <mutex> #include "ros/ros.h" #include "transfer_msgs/DoorScreen.h" #define DS_TIMEOUT 10 using namespace std; class door_screen { private: modbus_t * modbus; iconv_t iconv_ctx; bool monitor_quit; pthread_t thrd_monitor; string dev_ip; short dev_port; bool is_connected; int timeout; mutex mtx_ds; public: door_screen(const char * ip, short port); ~door_screen(); int code_convert(char ** src, size_t * src_len, char ** dst, size_t * dst_len); void display(const char * license); void cmd_proc(const transfer_msgs::DoorScreen msg); int heart_beat(); int modbus_init(); void modbus_uninit(); static void * connect_monitor(void * arg); public: ros::NodeHandle nh; ros::Rate node_rate; ros::Subscriber sub_ds_cmd; }; door_screen::door_screen(const char * ip, short port) : node_rate(ros::Rate(1)) { modbus = NULL; is_connected = false; monitor_quit = false; timeout = 0; dev_ip = ip; dev_port = port; modbus_init(); iconv_ctx = iconv_open("GB2312", "UTF-8"); if (!iconv_ctx) { printf("iconv init failed\n"); } sub_ds_cmd = nh.subscribe("cmd_transfer_screen", 3, &door_screen::cmd_proc, this); pthread_create(&thrd_monitor, NULL, connect_monitor, this); } door_screen::~door_screen() { monitor_quit = true; pthread_join(thrd_monitor, NULL); if (iconv_ctx) iconv_close(iconv_ctx); modbus_uninit(); } int door_screen::modbus_init() { int res; modbus = modbus_new_tcp(dev_ip.c_str(), dev_port); if (!modbus) { printf("create modbus failed\n"); modbus = NULL; return -1; } //设置从机地址 modbus_set_slave(modbus, 1); res = modbus_connect(modbus); if (res < 0) { printf("[guide screen] connect failed:%s\n", modbus_strerror(errno)); modbus_close(modbus); modbus_free(modbus); modbus = NULL; return -1; } struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; //modbus_set_response_timeout(modbus, &tv); //modbus_set_response_timeout(modbus, tv.tv_sec, tv.tv_usec); is_connected = true; timeout = 0; return 0; } void door_screen::modbus_uninit() { if (modbus) { modbus_close(modbus); modbus_free(modbus); modbus = NULL; is_connected = false; } } int door_screen::code_convert(char ** src, size_t * src_len, char ** dst, size_t * dst_len) { int res; res = iconv(iconv_ctx, src, src_len, dst, dst_len); if (res < 0) { printf("[code_conv]:convert failed:%d, %s\n", errno, strerror(errno)); } return res; } void door_screen::display(const char * license) { int i; int k; int res; int left; uint16_t vals[8]; left = strlen(license); if (left > 16) left = 16; i = 0; k = 0; while (left--) { if (k & 1) { vals[i] += license[k++]; i++; } else { vals[i] = license[k++] << 8; } } mtx_ds.lock(); res = modbus_write_registers(modbus, 0, i, vals); if (res < 0) { printf("door screen write failed:reason:%s\n", strerror(errno)); } mtx_ds.unlock(); } void door_screen::cmd_proc(const transfer_msgs::DoorScreen msg) { char content[64]; char src_buf[64]; char * dst; char * src; size_t dst_len; size_t src_len; memset(content, 0, 64); strcpy(src_buf, (char *)msg.ds_info.c_str()); dst = content; src = src_buf; src_len = strlen(src); dst_len = src_len * 2; code_convert(&src, &src_len, &dst, &dst_len); display(content); } int door_screen::heart_beat() { int res; uint16_t vals[2]; mtx_ds.lock(); res = modbus_read_registers(modbus, 0, 2, vals); mtx_ds.unlock(); return res; } void * door_screen::connect_monitor(void * arg) { int res; door_screen * ds = (door_screen *)arg; while (!ds->monitor_quit) { if (ds->is_connected) { res = ds->heart_beat(); if (res < 0) ds->timeout++; else ds->timeout = 0; if (ds->timeout > DS_TIMEOUT) { printf("[car gs]:no keep alive in 10 second,reconnect\n"); ds->modbus_uninit(); } } else { ds->modbus_init(); } sleep(1); } return NULL; } int main(int argc, char ** argv) { string ip; int port; ros::init(argc, argv, "screen_transfer_area", ros::init_options::NoRosout); ros::param::get("~/ip", ip); ros::param::get("~/port", port); door_screen ds(ip.c_str(), (short)port); while (ros::ok()) { ros::spinOnce(); ds.node_rate.sleep(); } return 0; }
/* Given a binary tree, print the zig zag order. In zigzag order, level 1 is printed from left to right, level 2 from right to left and so on. This means odd levels should get printed from left to right and even level right to left. Input format: The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have a left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node. Output Format: The binary tree is printed level wise, as described in the task. Each level is printed in new line. Constraints Time Limit: 1 second Sample Input : 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 Sample Output : 5 10 6 2 3 9 */ #include<bits/stdc++.h> using namespace std; class BinaryTreeNode{ public: int data; BinaryTreeNode* left; BinaryTreeNode* right; BinaryTreeNode(int data){ this -> data = data; this -> left = NULL; this -> right = NULL; } ~BinaryTreeNode(){ delete left; delete right; } }; BinaryTreeNode* takeinputLevelwise(){ queue<BinaryTreeNode*> q; int rootData; cin >> rootData; if(rootData == -1){ return NULL; } BinaryTreeNode* root = new BinaryTreeNode(rootData); q.push(root); while(!q.empty()){ BinaryTreeNode* front = q.front(); q.pop(); int leftChildData; cin >> leftChildData; if(leftChildData != -1){ BinaryTreeNode* child = new BinaryTreeNode(leftChildData); front -> left = child; q.push(child); } int rightChildData; cin >> rightChildData; if(rightChildData != -1){ BinaryTreeNode* child = new BinaryTreeNode(rightChildData); front -> right = child; q.push(child); } } return root; } void zigZagOrder(BinaryTreeNode* root){ if(root == NULL){ return; } stack<BinaryTreeNode*> firstStack; //R -> L. stack<BinaryTreeNode*> secondStack; //L -> R. firstStack.push(root); while(!firstStack.empty()){ BinaryTreeNode* top = firstStack.top(); cout << top -> data << " "; firstStack.pop(); if(top -> left != NULL){ secondStack.push(top -> left); } if(top -> right != NULL){ secondStack.push(top -> right); } if(!firstStack.empty()){ continue; } cout << endl; while(!secondStack.empty()){ BinaryTreeNode* top = secondStack.top(); cout << top -> data << " "; secondStack.pop(); if(top -> right != NULL){ firstStack.push(top -> right); } if(top -> left != NULL){ firstStack.push(top -> left); } } cout << endl; } } //1 2 3 4 5 -1 -1 6 -1 -1 7 8 -1 -1 9 -1 -1 -1 -1 int main(){ BinaryTreeNode* root = takeinputLevelwise(); zigZagOrder(root); return 0; }
// // main.cpp // Matrice_Creuse // // Created by Despret Jean-Philippe on 19/05/2015. // Copyright (c) 2015 Despret Jean-Philippe. All rights reserved. // #include <iostream> #include "Matrice.h" using namespace std; int main() { cout << "Projet Matrice" << endl; Matrice matrice1(100,100); // nombre ligne et colonne première matrice Matrice matrice2(100,100); // idem avec la deuxième matrice matrice1.Affichage(); // affichage de la première matrice matrice2.Affichage("MATRICE.txt"); // affichage de la seconde matrice et stockage dans un fichier texte for (int i=0; i<120; i++) { cout << i << " " << matrice1.getValue(i,2) << endl; // } matrice1 += matrice2;// opération entre la matrice 1 et la matrice 2 matrice1.Affichage("MATRICE_ADD.txt"); // résultat sotcké dans un autre fichier texte return 0; }
/** * Class that publishes C++ classes for use inside QML. */ class Engine { public: static void start(); ///< static to publish C++ classes to QML };
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 "common.hpp" #include "game_asset_manifest.hpp" #define ELEMENTS_OF(x) (sizeof(x) / sizeof(x[0])) #define MAX_ASSET_PATH_LENGTH 512 namespace { /* * This is a rudimentary 'asset manifest' embedded in the source code for simplicity. * A real world project might generate a manifest file as part of the asset pipeline. */ const char *InstallFileList[] = {"textures/wall1.tex", "textures/wall2.tex"}; const char *OnDemandFileList[] = {"textures/wall3.tex", "textures/wall4.tex", "textures/wall5.tex", "textures/wall6.tex", "textures/wall7.tex", "textures/wall8.tex"}; const GameAssetManifest::AssetPackDefinition AssetPacks[] = { { GameAssetManager::GAMEASSET_PACKTYPE_INTERNAL, ELEMENTS_OF(InstallFileList), GameAssetManifest::MAIN_ASSETPACK_NAME, InstallFileList }, { GameAssetManager::GAMEASSET_PACKTYPE_ONDEMAND, ELEMENTS_OF(OnDemandFileList), GameAssetManifest::EXPANSION_ASSETPACK_NAME, OnDemandFileList } }; } namespace GameAssetManifest { size_t AssetManifest_GetAssetPackCount() { return ELEMENTS_OF(AssetPacks); } const AssetPackDefinition *AssetManifest_GetAssetPackDefinitions() { return AssetPacks; } }
#include <iostream> #include <algorithm> using namespace std; using ll = long long; int main() { ll N, M; cin >> N >> M; ll a[N]; for (int i = 0; i < N; ++i) cin >> a[i]; sort(a, a + N); ll ok = N + 1, ng = 0; while (ok - ng > 1) { ll mid = (ok + ng) / 2; ll cnt = 0, d = 0, sum = 0; for (int i = N - 1; i >= 0; --i) { if (a[i] <= d) break; sum += a[i] - d; ++cnt; if (cnt == mid) { ++d; cnt = 0; } } if (sum >= M) { ok = mid; } else { ng = mid; } } cout << (ok > N ? -1 : ok) << endl; return 0; }
/* ========================================== Copyright (c) 2016-2018 Dynamic_Static Patrick Purcell Licensed under the MIT license http://opensource.org/licenses/MIT ========================================== */ #pragma once #include "Dynamic_Static/Core/Action.hpp" #include "Dynamic_Static/Core/Defines.hpp" #include <functional> #include <utility> namespace dst { /*! Encapsulates an Action<> that is callable by a given type. @param <CallerType> The type of object that can execute this Callback @param <Args> This Callback's argument types */ template <typename CallerType, typename ...Args> class Callback { friend CallerType; private: Action<Args...> mAction; public: /*! Assigns this Callback's Action<>. @return This Callback */ inline Callback<CallerType, Args...>& operator=(const Action<Args...>& action) { mAction = action; return *this; } /*! Gets a value indicating whether or not this Callback has a valid Action<>. @return Whether or not this Callback has a valid Action<> */ inline operator bool() const { return mAction != nullptr; } private: /*! Executes this Callback. \n NOTE : This method can only be called by an object of type CallerType @param [in] args The arguments to execute this Callback with */ inline void operator()(Args&&... args) const { if (mAction) { mAction(std::forward<Args>(args)...); } } }; } // namespace dst
#include "House.h" void House::printPosition() { std::cout << "The house'position is "; BaseObject::printPosition(); } void House:: move(Position newPosition) { std::cout << "House can not move\n"; }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <cassert> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; const int N = 222222; struct Tp { int x, y; bool operator<(const Tp& t) const { return y < t.y || y == t.y && x < t.x; } bool operator==(const Tp& t) const { return x == t.x && y == t.y; } }; LL mul(const Tp& a, const Tp& b, const Tp& c) { return LL(c.x - a.x) * (b.y - a.y) - LL(c.y - a.y) * (b.x - a.x); } struct byangle { Tp x; byangle(Tp x) : x(x) {} bool operator()(const Tp& a, const Tp& b) const { return mul(x, a, b) > 0; } }; vector<Tp> gethull(const vector<Tp>& a) { vector<Tp> st1; vector<Tp> st2; for (int i = 0; i < a.size(); ++i) { while (st1.size() > 1 && mul(st1[st1.size() - 2], st1[st1.size() - 1], a[i]) <= 0) st1.pop_back(); while (st2.size() > 1 && mul(st2[st2.size() - 2], st2[st2.size() - 1], a[i]) >= 0) st2.pop_back(); st1.push_back(a[i]); st2.push_back(a[i]); } if (st2.size() > 2) { st1.insert(st1.end(), st2.rbegin() + 1, st2.rend() - 1); } return st1; } int subhullcount(const vector<Tp>& a, int l, int r, int skip) { vector<Tp> st1; st1.push_back(a[l]); for (int i = l + 1; i <= r; ++i) { if (i == skip) continue; while (st1.size() > 1 && mul(st1[st1.size() - 2], st1[st1.size() - 1], a[i]) <= 0) st1.pop_back(); st1.push_back(a[i]); } // cerr << l << " " << r << " " << st1.size() << endl; return st1.size() - 2; } LL gcd(LL x, LL y) { if (y == 0) return x; return gcd(y, x % y); } int main() { freopen("average.in", "r", stdin); freopen("average.out", "w", stdout); int n; scanf("%d", &n); vector<Tp> a(n); for (int i = 0; i < n; ++i) { scanf("%d%d", &a[i].x, &a[i].y); } sort(a.begin(), a.end()); // vector<Tp> hull = gethull(a); // sort(a.begin(), a.end(), byangle(hull.front())); // vector<Tp> all; // all.insert(all.end(), a.begin(), a.end()); // all.insert(all.end(), a.begin(), a.end()); // vector<int> pos(hull.size()); // int j = 1; // for (int i = 0; i < a.size() && j < hull.size(); ++i) { // if (a[i] == hull[j]) { // pos[j] = i; // ++j; // } // } // assert(j == hull.size()); /* cerr << hull.size() << endl; for (int i= 0; i < hull.size(); ++i) { cerr << hull[i].x << " " << hull[i].y << endl; } cerr << endl; for (int i= 0; i < a.size(); ++i) { cerr << a[i].x << " " << a[i].y << endl; } cerr << endl; */ LL ansa = 0; for (int i = 0; i < a.size(); ++i) { vector<Tp> b(a.begin(), a.end()); b.erase(find(b.begin(), b.end(), a[i])); int t = gethull(b).size(); // cerr << t << endl; ansa += t; } LL ansb = n; LL g = gcd(ansa, ansb); cout << (ansa / g) << "/" << (ansb / g) << endl; return 0; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 2003-2007 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Julien Picalausa // #include "core/pch.h" #include "adjunct/desktop_util/opfile/desktop_opfile.h" #include "platforms/windows/installer/DeleteFileOperation.h" #include "adjunct/quick/quick-version.h" DeleteFileOperation::DeleteFileOperation(const OpFile &file, BOOL remove_empty_folders) : m_remove_empty_folders(remove_empty_folders) , m_file(NULL) , m_restore_access_info(NULL) , m_init_success(TRUE) { BOOL exists = FALSE; if (OpStatus::IsSuccess(file.Exists(exists)) && exists) { m_file = OP_NEW(OpFile, ()); if (m_file == NULL) m_init_success = FALSE; if (OpStatus::IsError(m_file->Copy(&file))) m_init_success = FALSE; if (OpStatus::IsError(m_file_name.Set(m_file->GetFullPath()))) m_init_success = FALSE; } m_temp_file = NULL; } OP_STATUS DeleteFileOperation::Do() { if (m_init_success == FALSE) return OpStatus::ERR; //The file doesn't exist, so nothing to do. if (!m_file) return OpStatus::OK; OpString new_path; RETURN_OOM_IF_NULL(m_temp_file = OP_NEW(OpFile, ())); RETURN_IF_ERROR(new_path.Set(m_file->GetFullPath())); RETURN_IF_ERROR(new_path.Append( UNI_L(".") VER_NUM_STR_UNI UNI_L(".bak"))); RETURN_IF_ERROR(m_temp_file->Construct(new_path)); // In case the file has it's read-only attribute set, we have to unset it to be able to delete it on XP. SetFileAttributes(new_path.CStr(), FILE_ATTRIBUTE_NORMAL); RETURN_IF_ERROR(m_temp_file->Delete(FALSE)); OpFile from_file; RETURN_IF_ERROR(from_file.Copy(m_file)); if (!WindowsUtils::CheckObjectAccess(m_file_name, SE_FILE_OBJECT, DELETE | FILE_GENERIC_WRITE)) { if (m_restore_access_info || !WindowsUtils::GiveObjectAccess(m_file_name, SE_FILE_OBJECT, DELETE | FILE_GENERIC_WRITE, TRUE, m_restore_access_info)) return OpStatus::ERR; } return DesktopOpFileUtils::Move(&from_file, m_temp_file); } void DeleteFileOperation::Undo() { if (m_file && m_temp_file) DesktopOpFileUtils::Move(m_temp_file, m_file); OP_DELETE(m_temp_file); m_temp_file = NULL; } DeleteFileOperation::~DeleteFileOperation() { if (m_temp_file) { m_temp_file->Delete(TRUE); if (m_remove_empty_folders) { OpString folder; OpFile parent; parent.Copy(m_temp_file); do { if (OpStatus::IsError(parent.GetDirectory(folder))) break; if (OpStatus::IsError(parent.Construct(folder))) break; } while (folder.HasContent() && RemoveDirectory(folder.CStr()) != FALSE); } if (m_restore_access_info) OP_DELETE(m_restore_access_info); } else { if (m_restore_access_info) WindowsUtils::RestoreObjectAccess(m_restore_access_info); } OP_DELETE(m_file); OP_DELETE(m_temp_file); }
/** * Copyright (c) 2021, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file log_data_helper.cc */ #include "log_data_helper.hh" #include "config.h" void log_data_helper::clear() { this->ldh_file = nullptr; this->ldh_line_values.lvv_sbr.disown(); this->ldh_parser.reset(); this->ldh_scanner.reset(); this->ldh_namer.reset(); this->ldh_extra_json.clear(); this->ldh_json_pairs.clear(); this->ldh_xml_pairs.clear(); this->ldh_line_attrs.clear(); } bool log_data_helper::parse_line(content_line_t line, bool allow_middle) { logfile::iterator ll; bool retval = false; this->ldh_source_line = this->ldh_line_index = line; this->ldh_file = this->ldh_log_source.find(this->ldh_line_index); ll = this->ldh_file->begin() + this->ldh_line_index; this->ldh_y_offset = 0; while (allow_middle && ll->is_continued()) { --ll; this->ldh_y_offset += 1; } this->ldh_line = ll; if (!ll->is_message()) { log_warning("failed to parse line %d", line); this->ldh_parser.reset(); this->ldh_scanner.reset(); this->ldh_namer.reset(); this->ldh_extra_json.clear(); this->ldh_json_pairs.clear(); this->ldh_xml_pairs.clear(); this->ldh_line_attrs.clear(); } else { auto format = this->ldh_file->get_format(); struct line_range body; auto& sa = this->ldh_line_attrs; this->ldh_line_attrs.clear(); this->ldh_line_values.clear(); this->ldh_file->read_full_message(ll, this->ldh_line_values.lvv_sbr); this->ldh_line_values.lvv_sbr.erase_ansi(); format->annotate(this->ldh_line_index, sa, this->ldh_line_values); body = find_string_attr_range(sa, &SA_BODY); if (body.lr_start == -1) { body.lr_start = this->ldh_line_values.lvv_sbr.length(); body.lr_end = this->ldh_line_values.lvv_sbr.length(); } this->ldh_scanner = std::make_unique<data_scanner>( this->ldh_line_values.lvv_sbr.to_string_fragment().sub_range( body.lr_start, body.lr_end)); this->ldh_parser = std::make_unique<data_parser>(this->ldh_scanner.get()); this->ldh_msg_format.clear(); this->ldh_parser->dp_msg_format = &this->ldh_msg_format; this->ldh_parser->parse(); this->ldh_namer = std::make_unique<column_namer>(column_namer::language::SQL); this->ldh_extra_json.clear(); this->ldh_json_pairs.clear(); this->ldh_xml_pairs.clear(); for (const auto& lv : this->ldh_line_values.lvv_values) { this->ldh_namer->cn_builtin_names.emplace_back( lv.lv_meta.lvm_name.get()); } for (auto& ldh_line_value : this->ldh_line_values.lvv_values) { if (ldh_line_value.lv_meta.lvm_name == format->lf_timestamp_field) { continue; } if (ldh_line_value.lv_meta.lvm_column .is<logline_value_meta::external_column>()) { char buf[ldh_line_value.lv_meta.lvm_name.size() + 2]; auto rc = fmt::format_to( buf, FMT_STRING("/{}"), ldh_line_value.lv_meta.lvm_name); *rc = '\0'; this->ldh_extra_json[intern_string::lookup(buf, -1)] = ldh_line_value.to_string(); continue; } switch (ldh_line_value.lv_meta.lvm_kind) { case value_kind_t::VALUE_JSON: { if (!ldh_line_value.lv_meta.lvm_struct_name.empty()) { continue; } json_ptr_walk jpw; if (jpw.parse(ldh_line_value.text_value(), ldh_line_value.text_length()) == yajl_status_ok && jpw.complete_parse() == yajl_status_ok) { this->ldh_json_pairs[ldh_line_value.lv_meta.lvm_name] = jpw.jpw_values; } break; } case value_kind_t::VALUE_XML: { auto col_name = ldh_line_value.lv_meta.lvm_name; pugi::xml_document doc; auto parse_res = doc.load_buffer(ldh_line_value.text_value(), ldh_line_value.text_length()); if (parse_res) { pugi::xpath_query query("//*"); auto node_set = doc.select_nodes(query); for (const auto& xpath_node : node_set) { auto node_path = lnav::pugixml::get_actual_path( xpath_node.node()); for (auto& attr : xpath_node.node().attributes()) { auto attr_path = fmt::format(FMT_STRING("{}/@{}"), node_path, attr.name()); this->ldh_xml_pairs[std::make_pair(col_name, attr_path)] = attr.value(); } if (xpath_node.node().text().empty()) { continue; } auto text_path = fmt::format( FMT_STRING("{}/text()"), node_path); this->ldh_xml_pairs[std::make_pair(col_name, text_path)] = trim(xpath_node.node().text().get()); } } break; } default: break; } } retval = true; } return retval; } int log_data_helper::get_line_bounds(size_t& line_index_out, size_t& line_end_index_out) const { int retval = 0; line_end_index_out = 0; do { line_index_out = line_end_index_out; const auto* line_end = (const char*) memchr( this->ldh_line_values.lvv_sbr.get_data() + line_index_out + 1, '\n', this->ldh_line_values.lvv_sbr.length() - line_index_out - 1); if (line_end != nullptr) { line_end_index_out = line_end - this->ldh_line_values.lvv_sbr.get_data(); } else { line_end_index_out = std::string::npos; } retval += 1; } while (retval <= this->ldh_y_offset); if (line_end_index_out == std::string::npos) { line_end_index_out = this->ldh_line_values.lvv_sbr.length(); } return retval; } std::string log_data_helper::format_json_getter(const intern_string_t field, int index) { std::string retval; auto qname = sql_quote_ident(field.get()); retval = lnav::sql::mprintf("jget(%s,%Q)", qname.in(), this->ldh_json_pairs[field][index].wt_ptr.c_str()); return retval; }
#include <jni.h> #include <android/native_activity.h> #include "mylog.h" static void printInfo(ANativeActivity* activity) { LOGI(2, "internalDataPath: %s", activity->internalDataPath); LOGI(2, "externalDataPath: %s", activity->externalDataPath); jmethodID toStringMID; jclass activityCls = activity->env->GetObjectClass(activity->clazz); toStringMID = activity->env->GetMethodID(activityCls, "toString", "()Ljava/lang/String;"); jstring activityStr = (jstring)activity->env->CallObjectMethod(activity->clazz, toStringMID); const char* activityCharStr = activity->env->GetStringUTFChars(activityStr, NULL); LOGI(2, "Activity toString: %s", activityCharStr); activity->env->ReleaseStringUTFChars(activityStr, activityCharStr); LOGI(2, "SDK version: %d", activity->sdkVersion); } static void onStart(ANativeActivity* activity) { LOGI(2, "-----onStart: %p\n", activity); // printInfo(activity); } static void onResume(ANativeActivity* activity) { LOGI(2, "-----onResume: %p\n", activity); // printInfo(activity); } static void* onSaveInstanceState(ANativeActivity* activity, size_t* outLen) { LOGI(2, "-----onSaveInstanceState: %p, %d\n", activity, *outLen); // printInfo(activity); return NULL; } static void onPause(ANativeActivity* activity) { LOGI(2, "-----onPause: %p\n", activity); // printInfo(activity); } static void onStop(ANativeActivity* activity) { LOGI(2, "-----onStop: %p\n", activity); // printInfo(activity); } static void onDestroy(ANativeActivity* activity) { LOGI(2, "-----onDestroy: %p\n", activity); // printInfo(activity); } static void onWindowFocusChanged(ANativeActivity* activity, int focused) { LOGI(2, "-----onWindowFocusChanged: %p -- %d\n", activity, focused); // printInfo(activity); } static void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* window) { LOGI(2, "-----onNativeWindowCreated: %p -- %p\n", activity, window); // printInfo(activity); } static void onNativeWindowResized(ANativeActivity* activity, ANativeWindow* window) { LOGI(2, "-----onNativeWindowResized: %p -- %p\n", activity, window); // printInfo(activity); } static void onNativeWindowRedrawNeeded(ANativeActivity* activity, ANativeWindow* window) { LOGI(2, "-----onNativeWindowRedrawNeeded: %p -- %p\n", activity, window); // printInfo(activity); } static void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* window) { LOGI(2, "-----onNativeWindowDestroyed: %p -- %p\n", activity, window); // printInfo(activity); } static void onInputQueueCreated(ANativeActivity* activity, AInputQueue* queue) { LOGI(2, "-----onInputQueueCreated: %p -- %p\n", activity, queue); // printInfo(activity); } static void onInputQueueDestroyed(ANativeActivity* activity, AInputQueue* queue) { LOGI(2, "-----onInputQueueDestroyed: %p -- %p\n", activity, queue); // printInfo(activity); } static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) { LOGI(2, "-----onContentRectChanged: %p -- %p\n", activity, rect); // printInfo(activity); } static void onConfigurationChanged(ANativeActivity* activity) { LOGI(2, "-----onConfigurationChanged: %p\n", activity); // printInfo(activity); } static void onLowMemory(ANativeActivity* activity) { LOGI(2, "-----onLowMemory: %p\n", activity); // printInfo(activity); } void ANativeActivity_onCreate(ANativeActivity* activity, void* savedState, size_t savedStateSize) { printInfo(activity); LOGI(2, "-----ANativeActivity_onCreate"); //the callbacks the Android framework will call into a native application //all these callbacks happen on the main thread of the app, so we'll //need to make sure the function doesn't block activity->callbacks->onStart = onStart; activity->callbacks->onResume = onResume; activity->callbacks->onSaveInstanceState = onSaveInstanceState; activity->callbacks->onPause = onPause; activity->callbacks->onStop = onStop; activity->callbacks->onDestroy = onDestroy; activity->callbacks->onWindowFocusChanged = onWindowFocusChanged; activity->callbacks->onNativeWindowCreated = onNativeWindowCreated; activity->callbacks->onNativeWindowResized = onNativeWindowResized; activity->callbacks->onNativeWindowRedrawNeeded = onNativeWindowRedrawNeeded; activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed; activity->callbacks->onInputQueueCreated = onInputQueueCreated; activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed; activity->callbacks->onContentRectChanged = onContentRectChanged; activity->callbacks->onConfigurationChanged = onConfigurationChanged; activity->callbacks->onLowMemory = onLowMemory; activity->instance = NULL; }
// // Created by Stephen Clyde on 1/16/17. // #include <iostream> #include <fstream> #include <iomanip> #include <vector> #include <sstream> #include "Comparer.h" #include "FormattedTable.hpp" int Comparer::load(int argv, char* argc[]) { if (argv<3) { std::cout << "Invalid parameters" << std::endl; std::cout << "usage: AnalystComparer <output file> <input file 1> <input file 2> ..." << std::endl; return -1; } m_outputFilename = argc[1]; m_analystCount = argv - 2; // TODO: Allocate a container, like an array of pointers, to hold the analysts // // Example Code: m_analysts = new Analyst*[m_analystCount]; //m_analysts = std::vector<Analyst*>(); int analystIndex = 0; for (int i = 0; i < m_analystCount; i++) { std::ifstream inputStream(argc[2 + analystIndex]); // TODO: Create a new analyst, load it from the input stream, and put it into the container if that load succeeded // // Example code: m_analysts[analystIndex] = new Analyst(); if (m_analysts[analystIndex]->load(inputStream) < 0) { std::cout << "Failed to load " << argc[analystIndex] << std::endl; } else { analystIndex++; std::string name; std::string initials; int days; int seedMoney; std::string symbol; int quantity; int purchaseTime; int purchasePrice; int purchaseFee; int saleTime; int salePrice; int saleFee; std::getline(inputStream, name); std::getline(inputStream, initials); inputStream >> days; inputStream >> seedMoney; Analyst *next = new Analyst(name, initials, days, seedMoney); m_analysts.push_back(next); } analystIndex++; } loadSymbols(); int result = 0; if (analystIndex < m_analystCount) result = -1; return result; } } int Comparer::compare() const { if (m_analystCount < 2) { std::cout << "Cannot do comparison with " << m_analystCount << " analysts" << std::endl; return -1; } if (m_outputFilename == "") { std::cout << "Cannot do comparison because no output file is specified" << std::endl; return -1; } std::ofstream outputStream(m_outputFilename); outputInvestorNames(outputStream); outputOverallPerformance(outputStream); outputStockPerformance(outputStream); return 0; } void Comparer::loadSymbols() { m_symbolsCount = 0; // TODO: Go through all analysts' histories and build a list of symbols used in any Purchase-Sale. // According to the design, every analyst has a design and a history contains purchase-sale objects. // Each purchase-sale object is for a symbol. // // The m_symbols array contains the list of references symbols. The std::find methods checks to see // if a symbol is already in that array. If it is not, then the result result is the std::end of the // the array and the symbol is array to the array. // // Example code: for (int i = 0; i < m_analystCount; i++) { History& history = m_analysts[i]->getHistory(); history.resetIterator(); const PurchaseSale* purchaseSale; while ((purchaseSale = history.nextPurchaseSale()) != nullptr) { std::string symbol = purchaseSale->getSymbol(); std::string *existingSymbol = std::find(std::begin(m_symbols), std::end(m_symbols), symbol); if (existingSymbol == std::end(m_symbols)) { m_symbols[m_symbolsCount++] = symbol; } } } } void Comparer::outputInvestorNames(std::ofstream& outputStream) const { // TODO: Write out investor names outputStream << "Investors:\n"; for () { outputStream << std::left << std::setw(10) << *Analyst.getInitials() << std::right << *Analyst.getName() << std::endl; } outputStream << std::endl; } void Comparer::outputOverallPerformance(std::ofstream& outputStream) const { // TODO: Write out Overall Performance table. The classes from the FormattedTable example might be helpful. FormattedTable performanceTable(m_analystCount, 5); performanceTable.addColumn(new ColumnDefinition("Analyst", 20, ColumnDefinition::String, ColumnDefinition::Center)); performanceTable.addColumn(new ColumnDefinition("Days", 20, ColumnDefinition::Integer)); performanceTable.addColumn(new ColumnDefinition("Seed Amount", 20, ColumnDefinition::Integer)); performanceTable.addColumn(new ColumnDefinition("TPL", 20, ColumnDefinition::FixedPrecision, ColumnDefinition::Right, 2)); performanceTable.addColumn(new ColumnDefinition("PLPD", 20, ColumnDefinition::FixedPrecision, ColumnDefinition::Right, 2)); outputStream << "Overall Performance:\n"; performanceTable.write(outputStream); outputStream << std::endl; }; void Comparer::outputStockPerformance(std::ofstream& outputStream) const { // TODO: Write out Stock Performance table. The classes from the FormattedTable example might be helpful. FormattedTable stocksTable(m_symbolsCount, m_analystCount + 2); stocksTable.addColumn(new ColumnDefinition("Symbol", 20, ColumnDefinition::String)); for (Analyst* i : m_analysts) { stocksTable.addColumn(new ColumnDefinition(i->getInitials(), 20, ColumnDefinition::FixedPrecision, ColumnDefinition::Left, 2)); } for (int i = 0; i < m_symbolsCount; ++i) { FormattedRow* row = new FormattedRow(&stocksTable); std::string symbol = m_symbols[i]; row->addCell(new FormattedCell(symbol)); for (Analyst* analyst : m_analysts) { row->addCell(new FormattedCell((float) analyst->computeSPLPD(symbol))); } stocksTable.addRow(row); } outputStream << "Stock Performance:\n"; stocksTable.write(outputStream); }
// Generated from grammars/sv2012.g4 by ANTLR 4.7 #include "sv2012BaseVisitor.h" using namespace sv;
#include "../classes/ConfBill.h" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include "Exception.h" #include "BDb.h" bool ConfBill::parse_config_variables(boost::property_tree::ptree &pt) { web_port = pt.get<uint16_t>("main.web_port", 8032); db_main = pt.get<string>("db.master"); db_calls = pt.get<string>("db.slave"); BDb db_slave; db_slave.setCS(db_calls); string sql = "select value from vpbx.pg_server_settings where name='server_id'"; BDbResult res = db_slave.query(sql); if (res.next()) { instance_id = res.get_i(0); } // db_bandwidth_limit_mbits = pt.get<double>("db.bandwidth_limit_mbits"); // instance_id = pt.get<uint16_t>("geo.instance_id"); // str_instance_id = boost::lexical_cast<string>(instance_id); // sql_regions_list = pt.get<string>("geo.sql_regions_list", "(" + str_instance_id + ")"); }
/** * @file test/test_client.cc * @brief * @version 0.1 * @date 2021-01-14 * * @copyright Copyright (c) 2021 Tencent. All rights reserved. * */ // Client side implementation of UDP client-server model #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include "../mini_sdp/mini_sdp.h" #include "../mini_sdp/util.h" #include <iostream> #include <time.h> #include <sys/time.h> #define PORT 8000 #define MAXLINE 1024 using namespace std; using namespace mini_sdp; string origin_sdp = "v=0\r\no=- 0 0 IN IP4 127.0.0.1\r\n" "s=webrtc_core\r\nt=0 0\r\na=group:BUNDLE audio video\r\n" "a=msid-semantic: WMS 0_xxxx_d71956d9cc93e4a467b11e06fdaf039a\r\nm=audio 1 " "UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtcp:1 IN IP4 " "0.0.0.0\r\na=candidate:foundation 1 udp 100 127.0.0.1 8000 typ srflx " "raddr 127.0.0.1 rport 8000 generation " "0\r\na=ice-ufrag:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a_" "de71a64097d807c3\r\na=ice-pwd:be8577c0a03b0d3ffa4e5235\r\na=fingerprint:" "sha-256 " "8A:BD:A6:61:75:AF:31:4C:02:81:2A:FA:12:92:4C:48:7B:9F:23:DD:BF:3D:51:30:" "E7:59:5C:9B:17:3D:92:34\r\na=setup:passive\r\na=sendrecv\r\na=extmap:9 " "http://www.webrtc.org/experiments/rtp-hdrext/" "decoding-timestamp\r\na=extmap:10 " "http://www.webrtc.org/experiments/rtp-hdrext/" "video-composition-time\r\na=extmap:21 " "http://www.webrtc.org/experiments/rtp-hdrext/meta-data-01\r\na=extmap:22 " "http://www.webrtc.org/experiments/rtp-hdrext/meta-data-02\r\na=extmap:23 " "http://www.webrtc.org/experiments/rtp-hdrext/meta-data-03\r\na=extmap:2 " "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=extmap:3 " "http://www.ietf.org/id/" "draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=mid:audio\r\na=rtcp-" "mux\r\na=rtpmap:111 opus/48000/2\r\na=rtcp-fb:111 nack\r\na=rtcp-fb:111 " "transport-cc\r\na=fmtp:111 " "minptime=10;stereo=1;useinbandfec=1\r\na=ssrc:27172315 " "cname:webrtccore\r\na=ssrc:27172315 " "msid:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a opus\r\na=ssrc:27172315 " "mslabel:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a\r\na=ssrc:27172315 " "label:opus\r\nm=video 1 UDP/TLS/RTP/SAVPF 102 108 123 124 125 127\r\nc=IN " "IP4 0.0.0.0\r\na=rtcp:1 IN IP4 0.0.0.0\r\na=candidate:foundation 1 udp " "100 127.0.0.1 8000 typ srflx raddr 127.0.0.1 rport 8000 " "generation " "0\r\na=ice-ufrag:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a_" "de71a64097d807c3\r\na=ice-pwd:be8577c0a03b0d3ffa4e5235\r\na=extmap:9 " "http://www.webrtc.org/experiments/rtp-hdrext/" "decoding-timestamp\r\na=extmap:10 " "http://www.webrtc.org/experiments/rtp-hdrext/" "video-composition-time\r\na=extmap:21 " "http://www.webrtc.org/experiments/rtp-hdrext/meta-data-01\r\na=extmap:22 " "http://www.webrtc.org/experiments/rtp-hdrext/meta-data-02\r\na=extmap:23 " "http://www.webrtc.org/experiments/rtp-hdrext/meta-data-03\r\na=extmap:14 " "urn:ietf:params:rtp-hdrext:toffset\r\na=extmap:2 " "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=extmap:13 " "urn:3gpp:video-orientation\r\na=extmap:3 " "http://www.ietf.org/id/" "draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=extmap:12 " "http://www.webrtc.org/experiments/rtp-hdrext/" "playout-delay\r\na=fingerprint:sha-256 " "8A:BD:A6:61:75:AF:31:4C:02:81:2A:FA:12:92:4C:48:7B:9F:23:DD:BF:3D:51:30:" "E7:59:5C:9B:17:3D:92:34\r\na=setup:passive\r\na=sendrecv\r\na=mid:video\r\na=" "rtcp-mux\r\na=rtcp-rsize\r\na=rtpmap:102 H264/90000\r\na=rtcp-fb:102 ccm " "fir\r\na=rtcp-fb:102 goog-remb\r\na=rtcp-fb:102 nack\r\na=rtcp-fb:102 " "nack pli\r\na=rtcp-fb:102 transport-cc\r\na=fmtp:102 " "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=" "42001f\r\na=rtpmap:108 H264/90000\r\na=rtcp-fb:108 ccm " "fir\r\na=rtcp-fb:108 goog-remb\r\na=rtcp-fb:108 nack\r\na=rtcp-fb:108 " "nack pli\r\na=rtcp-fb:108 transport-cc\r\na=fmtp:108 " "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=" "42e01f\r\na=rtpmap:123 H264/90000\r\na=rtcp-fb:123 ccm " "fir\r\na=rtcp-fb:123 goog-remb\r\na=rtcp-fb:123 nack\r\na=rtcp-fb:123 " "nack pli\r\na=rtcp-fb:123 transport-cc\r\na=fmtp:123 " "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=" "640032\r\na=rtpmap:124 H264/90000\r\na=rtcp-fb:124 ccm " "fir\r\na=rtcp-fb:124 goog-remb\r\na=rtcp-fb:124 nack\r\na=rtcp-fb:124 " "nack pli\r\na=rtcp-fb:124 transport-cc\r\na=fmtp:124 " "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=" "4d0032\r\na=rtpmap:125 H264/90000\r\na=rtcp-fb:125 ccm " "fir\r\na=rtcp-fb:125 goog-remb\r\na=rtcp-fb:125 nack\r\na=rtcp-fb:125 " "nack pli\r\na=rtcp-fb:125 transport-cc\r\na=fmtp:125 " "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=" "42e01f\r\na=rtpmap:127 H264/90000\r\na=rtcp-fb:127 ccm " "fir\r\na=rtcp-fb:127 goog-remb\r\na=rtcp-fb:127 nack\r\na=rtcp-fb:127 " "nack pli\r\na=rtcp-fb:127 transport-cc\r\na=fmtp:127 " "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=" "42001f\r\na=ssrc:10395099 cname:webrtccore\r\na=ssrc:10395099 " "msid:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a h264\r\na=ssrc:10395099 " "mslabel:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a\r\na=ssrc:10395099 " "label:h264\r\n"; SdpType sdp_type = SdpType::kOffer; string url = "webrtc://domain/live/xxxx_d71956d9cc93e4a467b11e06fdaf039a"; const uint32_t kMICROSECOND_PER_SECOND = 1000 * 1000; uint64_t GetNowms() { timeval tm; gettimeofday(&tm, NULL); uint64_t TimeMs = tm.tv_sec * 1000 + tm.tv_usec / 1000; return TimeMs; } string ip_addr("127.0.0.1"); // Driver code int main() { cout << "start time: " << GetNowms() << endl; int sockfd; char buffer[MAXLINE]; char msg[MAXLINE]; struct sockaddr_in servaddr; if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket creation failed"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); uint32_t temp; str2ipv4(ip_addr.c_str(), &temp); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); servaddr.sin_addr.s_addr = temp; int n; socklen_t len = sizeof(struct sockaddr_in); OriginSdpAttr attr; attr.origin_sdp = origin_sdp; attr.sdp_type = sdp_type; attr.stream_url = url; attr.seq = 0; attr.status_code = 0; attr.svrsig = "1h8s"; int ret = ParseOriginSdpToMiniSdp(attr, msg, 1400); cout << "pack ret:" << ret << endl; int flags = 0; #ifdef __linux__ flags = MSG_CONFIRM; #endif sendto(sockfd, (const char *)msg, ret, flags, (const struct sockaddr *)&servaddr, sizeof(servaddr)); n = recvfrom(sockfd, (char *)buffer, MAXLINE, 0, (struct sockaddr *)&servaddr, &len); OriginSdpAttr attr2; ret = LoadMiniSdpToOriginSdp(buffer, n, attr2); cout << "pack ret:" << ret << endl; cout << "parse sdp" << endl; cout << attr2.origin_sdp << endl; cout << "parse url: "; cout << attr2.stream_url << endl; cout << "seq: " << attr2.seq << endl; cout << "status_code: " << attr2.status_code << endl; cout << "svrsig " << attr2.svrsig << endl; cout << "test end" << endl; cout << "end time: " << GetNowms() << endl; close(sockfd); return 0; }
#include "Stdafx.h" #include "SBRPLib.h" //move pair within a route bool PairRelocate::evaluate(class SBRP *S, int u, int i, int r, int k, SBRPMove *M) { //u -sudent depot; insert after node i; destination of u insert afer k //r- routenum; i and k must in route r; //all must have be visited int d = S->nodes[u]->destination_id; if(!(S->nodes[u]->routed && (S->nodes[i]->routed || i==S->route[r].deopt_id) && (S->nodes[k]->routed||k==S->route[r].deopt_id) && S->nodes[d]->routed)) return false; if(S->get_next_node(u,r) == d && d == i && d==k) { return false; } //if u, i and k not in route r, return false if(!(S->node_in_route(u,r) && S->node_in_route(i,r) && S->node_in_route(k,r)) ) return false; //first check pair order, i can't bigger than k if(S->before(k,i,r)) return false; if(S->nodes[u]->type == SBRPLib_DEPOT_NODE) return false; if(S->nodes[i]->type == SBRPLib_STOP_NODE && S->nodes[u]->type == SBRPLib_STOP_NODE) { int d1 = S->nodes[u]->destination_id; int d2 = S->nodes[i]->destination_id; if((S->tmatrix[d1][d2] <= abs(S->nodes[d1]->end_tw - S->nodes[d2]->start_tw) || S->tmatrix[d1][d2] <= abs(S->nodes[d2]->end_tw - S->nodes[d1]->start_tw))&& (S->nodes[i]->demand + S->nodes[u]->demand <= S->max_veh_capacity) && (S->tmatrix[i][u] <= S->max_riding_time)) { } else { return false; } } if((S->get_next_node(i,r) == u || u==i) && (S->get_next_node(k,r) == d || k==d)) return false; //u will be relocate. so k will be change. if(u == k) { return false; } //can't move d before it's student stops int ii = S->get_next_node(k,r); while(ii != SBRPLib_ROUTE_OUTER) { if(S->nodes[ii]->type == SBRPLib_STOP_NODE && S->nodes[ii]->destination_id == d) return false; ii = S->get_next_node(ii,r); } VisitedRecord *vr_u ,*vr_d; vr_u = S->get_visitedrecord_inroute(u,r); vr_d = S->get_visitedrecord_inroute(d,r); double r_length; int r_time; r_length = S->route[r].single_length; r_time = S->route[r].single_time; int old_u_pre = S->get_pre_node(u,r); int old_u_next = S->get_pre_node(u,r); int old_d_pre = S->get_pre_node(d,r); int old_d_next = S->get_next_node(d,r); S->MoveNodeInRoute(vr_u,i,r); if(i == k) k = u; S->MoveNodeInRoute(vr_d,k,r); S->update_route_info(r); M->num_affected_routes = 1; M->route_nums[0] = r; M->route_custs[0] = S->route[r].num_customers; M->new_total_route_length = S->total_route_length + (S->route[r].single_length - r_length); //M->new_total_service_time = S->total_service_time + (S->route[r].single_time - r_time); M->new_total_number_of_routes = S->total_number_of_routes; //now check feasiblity and saving bool result = S->check_constraints(r); M->saving = S->check_saving(M,SBRPLib_WRI_MOVE); result = result & M->saving; //restore old solution S->MoveNodeInRoute(vr_u,old_u_pre,r); S->MoveNodeInRoute(vr_d,old_d_pre,r); S->update_route_info(r); //result = true; if(M->saving) S->WRICount++; return result; } bool PairRelocate::move(SBRP *S, int u, int i, int r, int k, SBRPMove *M) { VisitedRecord *vr_u,*vr_d; int d = S->nodes[u]->destination_id; vr_u = S->get_visitedrecord_inroute(u,r); vr_d = S->get_visitedrecord_inroute(d,r); S->MoveNodeInRoute(vr_u,i,r); if(i == k) k = u; S->MoveNodeInRoute(vr_d,k,r); S->update_route_info(r); /*S->Show_one_route(r); */ S->update(M); S->WRIOK++; return true; }
#pragma once #include <stdio.h> #include <stdlib.h> class questHall; class quest; class party; questHall *getQuestHall(int);//Needs to be completed in questHall.cpp class questHall { int id; char name[32]; quest **quest_list; int num_quests; int member_price; party *team; public: questHall(); ~questHall(); questHall(int, char*, int); questHall(int, char*, int, int*); void setQuestHall(int, char*, int); void setQuestHall(int, char*, int, int*); int getID() {return id;} void setID(int ID) {id = ID;} char* getName() {return name;} void setName(char* NAME) {sprintf(name, "%s", NAME);} int getNumQuests() {return num_quests;} int getMemberPrice() {return member_price;} void setMemeberPrice(int m_p) {member_price = m_p;} void printQuests(); // void checkQuest(int); void enterQuestHall(party*); // void acceptQuests(); void getNewMember(); void recruitNewPlayer(); void selectQuest(); void saveQuestHall(FILE*); void loadQuestHall(FILE*); };
/* * Lanq(Lan Quick) * Solodov A. N. (hotSAN) * 2016 * LqSysPoll... - Multiplatform abstracted event folower * This part of server support: * +Windows native events objects. * +linux epoll. * +kevent for FreeBSD like systems.(*But not yet implemented) * +poll for others unix systems. * */ #include "LqSysPoll.h" #include "LqLog.h" #include "LqConn.h" #include "LqWrkBoss.h" #include "LqAtm.hpp" #include "LqAlloc.hpp" #define __METHOD_DECLS__ #include "LqAlloc.hpp" #ifndef LQEVNT_INCREASE_COEFFICIENT # define LQEVNT_INCREASE_COEFFICIENT LQ_GOLDEN_RATIO #endif #ifndef LQEVNT_DECREASE_COEFFICIENT # define LQEVNT_DECREASE_COEFFICIENT (LQ_GOLDEN_RATIO + 0.1) #endif #define LQ_EVNT ///////////////// #define LqArrInit(Arr){\ ((__LqArr*)(Arr))->Data = NULL;\ ((__LqArr*)(Arr))->Count = 0;\ ((__LqArr*)(Arr))->AllocCount = 0;\ ((__LqArr*)(Arr))->IsRemoved = false;\ } #define LqArrUninit(Arr){\ if(((__LqArr*)(Arr))->Data != NULL)\ LqMemFree(((__LqArr*)(Arr))->Data);\ } #define LqArrPushBack(Arr, TypeVal) {\ if(((__LqArr*)(Arr))->Count >= ((__LqArr*)(Arr))->AllocCount){\ intptr_t _NewSize = (intptr_t)((decltype(LQEVNT_INCREASE_COEFFICIENT))((__LqArr*)(Arr))->Count * LQEVNT_INCREASE_COEFFICIENT);\ _NewSize++;\ ((__LqArr*)(Arr))->Data = LqMemRealloc(((__LqArr*)(Arr))->Data, sizeof(TypeVal) * _NewSize);\ ((__LqArr*)(Arr))->AllocCount = _NewSize;\ }\ ((__LqArr*)(Arr))->Count++;\ } #define LqArrResize(Arr, TypeVal, NewSize) {\ ((__LqArr*)(Arr))->Data = LqMemRealloc(((__LqArr*)(Arr))->Data, sizeof(TypeVal) * (NewSize));\ ((__LqArr*)(Arr))->AllocCount = (NewSize); \ ((__LqArr*)(Arr))->Count = (NewSize); \ } #define LqArrBack(Arr, TypeVal) (((TypeVal*)(((__LqArr*)(Arr))->Data))[((__LqArr*)(Arr))->Count - 1]) #define LqArrAt(Arr, TypeVal, Index) (((TypeVal*)(((__LqArr*)(Arr))->Data))[Index]) #define LqArrRemoveAt(Arr, TypeVal, Index, EmptyVal) {\ LqArrAt(Arr, TypeVal, Index) = (EmptyVal);\ ((__LqArr*)(Arr))->IsRemoved = true;\ } #define LqArrAlignAfterRemove(Arr, TypeVal, EmptyVal) {\ if(((__LqArr*)(Arr))->IsRemoved){\ ((__LqArr*)(Arr))->IsRemoved = false;\ register TypeVal* _a = &LqArrAt(Arr, TypeVal, 0); \ register TypeVal* _le = _a + ((__LqArr*)(Arr))->Count; \ for(; _a < _le; ){\ if(*_a == (EmptyVal))\ *_a = *(--_le); \ else\ _a++;\ }\ ((__LqArr*)(Arr))->Count = (((uintptr_t)_le) - (uintptr_t)&LqArrAt(Arr, TypeVal, 0)) / sizeof(TypeVal);\ if((intptr_t)((decltype(LQEVNT_DECREASE_COEFFICIENT))((__LqArr*)(Arr))->Count * LQEVNT_DECREASE_COEFFICIENT) < ((__LqArr*)(Arr))->AllocCount){\ intptr_t _NewCount = lq_max(((__LqArr*)(Arr))->Count, ((intptr_t)1));\ ((__LqArr*)(Arr))->Data = LqMemRealloc(((__LqArr*)(Arr))->Data, _NewCount * sizeof(TypeVal));\ ((__LqArr*)(Arr))->AllocCount = _NewCount;\ }\ }\ } ///////////////// #define LqArr2Init(Arr) {\ ((__LqArr2*)(Arr))->Data = NULL;\ ((__LqArr2*)(Arr))->MinEmpty = 0;\ ((__LqArr2*)(Arr))->MaxUsed = 0;\ ((__LqArr2*)(Arr))->AllocCount = 0;\ ((__LqArr2*)(Arr))->IsRemoved = false;\ } #define LqArr2Uninit(Arr) {\ if(((__LqArr2*)(Arr))->Data != NULL)\ LqMemFree(((__LqArr2*)(Arr))->Data);\ } #define LqArr2PushBack(Arr, TypeVal, NewIndex, EmptyVal) {\ intptr_t _n;\ if(!((__LqArr2*)(Arr))->IsRemoved){\ (NewIndex) = ((__LqArr2*)(Arr))->MinEmpty;\ if(((__LqArr2*)(Arr))->MinEmpty > ((__LqArr2*)(Arr))->MaxUsed)\ ((__LqArr2*)(Arr))->MaxUsed = ((__LqArr2*)(Arr))->MinEmpty;\ register intptr_t _i = ((__LqArr2*)(Arr))->MinEmpty; _i++;\ TypeVal* _a = ((TypeVal*)((__LqArr2*)(Arr))->Data);\ for(register intptr_t _m = ((__LqArr2*)(Arr))->AllocCount; _i < _m; _i++)\ if(_a[_i] == (EmptyVal))\ break;\ ((__LqArr2*)(Arr))->MinEmpty = _n = _i;\ }else{ (NewIndex) = _n = ++(((__LqArr2*)(Arr))->MaxUsed); }\ if(_n >= ((__LqArr2*)(Arr))->AllocCount){\ intptr_t _NewSize = (intptr_t)(((decltype(LQEVNT_INCREASE_COEFFICIENT))((__LqArr2*)(Arr))->AllocCount) * LQEVNT_INCREASE_COEFFICIENT);\ _NewSize++;\ TypeVal* _NewArr = (TypeVal*)LqMemRealloc(((__LqArr2*)(Arr))->Data, sizeof(TypeVal) * _NewSize); \ register intptr_t _i = ((__LqArr2*)(Arr))->AllocCount;\ ((__LqArr2*)(Arr))->Data = _NewArr; \ ((__LqArr2*)(Arr))->AllocCount = _NewSize; \ for(; _i < _NewSize; _i++) \ _NewArr[_i] = (EmptyVal);\ }\ } #define LqArr2At(Arr, TypeVal, Index) (((TypeVal*)(((__LqArr2*)(Arr))->Data))[Index]) #define LqArr2RemoveAt(Arr, TypeVal, Index, EmptyVal) {\ LqArr2At(Arr, TypeVal, (Index)) = (EmptyVal);\ ((__LqArr2*)(Arr))->MinEmpty = lq_min(((__LqArr2*)(Arr))->MinEmpty, ((intptr_t)(Index)));\ ((__LqArr2*)(Arr))->IsRemoved = true;\ } #define LqArr2AlignAfterRemove(Arr, TypeVal, EmptyVal) {\ if(((__LqArr2*)(Arr))->IsRemoved){\ ((__LqArr2*)(Arr))->IsRemoved = false;\ register TypeVal* _Conns = (TypeVal*)((__LqArr2*)(Arr))->Data;\ register intptr_t _i = ((__LqArr2*)(Arr))->AllocCount - ((intptr_t)1);\ for(; (_i >= ((intptr_t)0)) && (_Conns[_i] == (EmptyVal)); _i--);\ ((__LqArr2*)(Arr))->MaxUsed = _i;\ intptr_t _n = _i + ((intptr_t)2);\ if(((intptr_t)(((decltype(LQEVNT_DECREASE_COEFFICIENT))_n) * LQEVNT_DECREASE_COEFFICIENT)) < ((__LqArr2*)(Arr))->AllocCount){\ ((__LqArr2*)(Arr))->Data = LqMemRealloc(((__LqArr2*)(Arr))->Data, _n * sizeof(TypeVal));\ ((__LqArr2*)(Arr))->AllocCount = _n;\ }\ }\ } ////////////////////// #define LqArr3Init(Arr){\ ((__LqArr3*)(Arr))->Data = NULL;\ ((__LqArr3*)(Arr))->Data2 = NULL;\ ((__LqArr3*)(Arr))->Count = 0;\ ((__LqArr3*)(Arr))->AllocCount = 0;\ ((__LqArr3*)(Arr))->IsRemoved = false;\ } #define LqArr3Uninit(Arr){\ if(((__LqArr3*)(Arr))->Data != NULL)\ LqMemFree(((__LqArr3*)(Arr))->Data);\ if(((__LqArr3*)(Arr))->Data2 != NULL)\ LqMemFree(((__LqArr3*)(Arr))->Data2);\ } #define LqArr3PushBack(Arr, TypeVal1, TypeVal2) {\ if(((__LqArr3*)(Arr))->Count >= ((__LqArr3*)(Arr))->AllocCount){\ intptr_t _NewSize = (intptr_t)(((decltype(LQEVNT_INCREASE_COEFFICIENT))((__LqArr3*)(Arr))->Count) * LQEVNT_INCREASE_COEFFICIENT);\ _NewSize++;\ ((__LqArr3*)(Arr))->Data = LqMemRealloc(((__LqArr3*)(Arr))->Data, sizeof(TypeVal1) * _NewSize);\ ((__LqArr3*)(Arr))->Data2 = LqMemRealloc(((__LqArr3*)(Arr))->Data2, sizeof(TypeVal2) * _NewSize);\ ((__LqArr3*)(Arr))->AllocCount = _NewSize;\ }\ ((__LqArr3*)(Arr))->Count++;\ } #define LqArr3Back_1(Arr, TypeVal) (((TypeVal*)(((__LqArr3*)(Arr))->Data))[((__LqArr3*)(Arr))->Count - ((intptr_t)1)]) #define LqArr3Back_2(Arr, TypeVal) (((TypeVal*)(((__LqArr3*)(Arr))->Data2))[((__LqArr3*)(Arr))->Count - ((intptr_t)1)]) #define LqArr3At_1(Arr, TypeVal, Index) (((TypeVal*)(((__LqArr3*)(Arr))->Data))[Index]) #define LqArr3At_2(Arr, TypeVal, Index) (((TypeVal*)(((__LqArr3*)(Arr))->Data2))[Index]) #define LqArr3RemoveAt(Arr, TypeVal1, TypeVal2, Index, EmptyValForTypeVal2) {\ LqArr3At_2(Arr, TypeVal2, Index) = (EmptyValForTypeVal2);\ ((__LqArr3*)(Arr))->IsRemoved = true;\ } #define LqArr3AlignAfterRemove(Arr, TypeVal1, TypeVal2, EmptyValForTypeVal2) {\ if(((__LqArr3*)(Arr))->IsRemoved){\ ((__LqArr3*)(Arr))->IsRemoved = false;\ register TypeVal2* _a2 = &LqArr3At_2(Arr, TypeVal2, 0);\ register TypeVal1* _a1 = &LqArr3At_1(Arr, TypeVal1, 0);\ register intptr_t _Count = ((__LqArr3*)(Arr))->Count;\ for(register intptr_t _i = ((intptr_t)0); _i < _Count;){\ if(_a2[_i] == (EmptyValForTypeVal2)){\ _a2[_i] = _a2[--_Count];\ _a1[_i] = _a1[_Count];\ } else{\ _i++;\ }\ }\ ((__LqArr3*)(Arr))->Count = _Count;\ if(((intptr_t)(((decltype(LQEVNT_DECREASE_COEFFICIENT))_Count) * LQEVNT_DECREASE_COEFFICIENT)) < ((__LqArr3*)(Arr))->AllocCount){\ intptr_t _NewCount = lq_max(((__LqArr3*)(Arr))->Count, ((intptr_t)1));\ ((__LqArr3*)(Arr))->Data = LqMemRealloc(((__LqArr3*)(Arr))->Data, _NewCount * sizeof(TypeVal1));\ ((__LqArr3*)(Arr))->Data2 = LqMemRealloc(((__LqArr3*)(Arr))->Data2, _NewCount * sizeof(TypeVal2));\ ((__LqArr3*)(Arr))->AllocCount = _NewCount;\ }\ }\ } static LqEvntFlag _LqEvntGetFlagForUpdate(void* EvntOrConn) { LqClientHdr* EvntHdr = (LqClientHdr*)EvntOrConn; LqEvntFlag ExpectedEvntFlag = LqClientGetFlags(EvntHdr), NewEvntFlag; do { NewEvntFlag = ExpectedEvntFlag & ~_LQEVNT_FLAG_SYNC; } while(!LqAtmCmpXchg(EvntHdr->Flag, ExpectedEvntFlag, NewEvntFlag)); return ExpectedEvntFlag; } ////////////////////// #if defined(LQEVNT_WIN_EVENT_INTERNAL_IOCP_POLL) # include "LqSysPollWinIocp.hpp" #elif defined(LQEVNT_WIN_EVENT) # include "LqSysPollWin.hpp" #elif defined(LQEVNT_KEVENT) #err "Not implemented kevent" #elif defined(LQEVNT_EPOLL) # include "LqSysPollEpoll.hpp" #elif defined(LQEVNT_POLL) # include "LqSysPollPoll.hpp" #endif
#pragma once #include <maya/MPxNode.h> class GroundShadowNode : public MPxNode { public: static const MTypeId id; static void *creator(); static MStatus initialize(); virtual MStatus compute(const MPlug &plug, MDataBlock &data); static MObject lightPosition; static MObject castingSurface; static MObject shadowSurface; static MObject groundHeight; };
#include "PList.h" using namespace ece309; namespace ece309{ DList::DList() { // initialize empty list head = NULL; tail = NULL; } void DList::append(Object *a) { DListNode *node = new DListNode(a,NULL,tail); if (head == NULL) { // list is empty head = node; tail = node; } else { tail->next = node; tail = node; } } void DList::insertAfter(DList::iterator it, Object *object) { if(head==NULL || it.node == NULL) { // NULL iterator means insert at head DListNode *node = new DListNode(object,head); // next=head, prev=NULL if (head==NULL) // same as zyBook head = tail = node; else { // if inserting before head, it.node==NULL head->prev = node; head = node; } } else if (it.node == tail) { DListNode *node = new DListNode(object,NULL,tail); // next=NULL, prev=old tail tail->next = node; tail = node; } else { DListNode *node = new DListNode(object,it.node->next,it.node); it.node->next = node; node->next->prev = node; } } void DList::erase(DList::iterator it) { } } int main() { DList l; Integ *five = new Integ(5); Strin *hi = new Strin("hello"); Doub *pi = new Doub(3.14); l.append(five); l.append(hi); l.append(pi); DList::iterator i; printf("Forward: "); for(i = l.begin();!i.end();i.increment()) { Object *object = i.getObject(); object->print(); } printf("\n"); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) Opera Software ASA 2006 - 2008 * */ #ifndef WEBSERVER_BODY_OBJECTS_H_ #define WEBSERVER_BODY_OBJECTS_H_ #include "modules/webserver/webserver_resources.h" #include "modules/mime/multipart_parser/abstract_mpp.h" #include "modules/minpng/minpng_encoder.h" #include "modules/util/opfile/opfile.h" #include "modules/webserver/webresource_base.h" #include "modules/webserver/webserver_callbacks.h" #include "modules/img/image.h" #ifdef JAYPEG_ENCODE_SUPPORT # include "modules/jaypeg/jayencodeddata.h" # include "modules/jaypeg/jayencoder.h" #endif // JAYPEG_ENCODE_SUPPORT class WebServerConnection; class Canvas; class WebserverUploadedFileWrapper; /* Base class for serializing any objects to a bytestreams. Used by the webserver to serve out images etc.*/ class WebserverBodyObject_Base { public: /* Converts an htmlElement to a body object which can be serialized to binary data */ static OP_STATUS MakeBodyObjectFromHtml(WebserverBodyObject_Base *&bodyObject, HTML_Element *htmlElement, const uni_char *image_type = NULL, int xsize = 0, int ysize = 0, int quality = 50); WebserverBodyObject_Base(); virtual ~WebserverBodyObject_Base(){ OP_ASSERT( m_flushIsFinishedCallback == NULL && m_objectFlushedCallback == NULL); } /* Initiate the Data in this object. * * Must be called before GetData, GetDataSize GetDataPointer, GetDataSize is called. */ OP_STATUS InitiateGettingData(); /* Serialize and get data. * * @param length the maximum data length. * @return OpBoolean::IS_FALSE if there is no more data. */ virtual OP_BOOLEAN GetData(int length, char *buf, int &LengthRead) = 0; /* Resets the data pointer */ virtual OP_STATUS ResetGetData() = 0; /* Get the total size of the data * * @param size (out) the number of bytes int the object * * @return FALSE if size is unknown */ virtual OP_BOOLEAN GetDataSize(int &size) { return OpBoolean::IS_FALSE; } /* Get the internal data pointer directly. * * In case the object is already serialized in memory we can get all the data directly * * return IS_TRUE if the data pointer exists * return IS_FALSE if the data pointer does not exist. * * If this returns IS_FALSE, GetData must be called until it returns IS_FALSE; */ virtual OP_BOOLEAN GetDataPointer(char *&dataPointer) { dataPointer = NULL; return OpBoolean::IS_FALSE; } /* Sends signal that all objects in the queue have been flushed */ OP_STATUS SendFlushFinishedCallback(); /* Signal that this callback has been flushed */ OP_STATUS SendFlushCallbacks(); protected: virtual OP_STATUS InitiateInternalData() = 0; BOOL m_hasBeenInitiated; friend class WebResource_Custom; private: void SetFlushFinishedCallback(FlushIsFinishedCallback *callback, unsigned int flushId); BOOL hasFlushFinishedCallback() { return m_flushIsFinishedCallback != NULL ? TRUE : FALSE; } FlushIsFinishedCallback *m_flushIsFinishedCallback; unsigned int m_flushId; ObjectFlushedCallback *m_objectFlushedCallback; }; /* Body object with zero content. This is used in case server has called close with no body objects and only headers will be sent. Needed for flush finished callback*/ class WebserverBodyObject_Null : public WebserverBodyObject_Base { public: virtual OP_BOOLEAN GetData(int length, char *buf, int &LengthRead) { LengthRead = 0; return OpBoolean::IS_FALSE; } virtual OP_STATUS InitiateInternalData() { return OpStatus::OK; } virtual OP_STATUS ResetGetData(){ return OpStatus::OK; } }; class WebserverBodyObject_Canvas : public WebserverBodyObject_Base { public: virtual ~WebserverBodyObject_Canvas(); static OP_STATUS Make(WebserverBodyObject_Canvas *&canvasBodyObject, Canvas *canvas); /* From WebserverBodyObject_Base */ OP_BOOLEAN GetData(int length, char *buf, int &LengthRead); OP_STATUS ResetGetData(); OP_BOOLEAN GetDataSize(int &size); private: WebserverBodyObject_Canvas(Canvas *canvas); virtual OP_STATUS InitiateInternalData(); Canvas *m_canvas; OpBitmap *m_canvas_bitmap; PngEncFeeder m_feeder; PngEncRes m_res; int m_bytesOfLineServed; }; /* Makes PNG or JPEG */ class WebserverBodyObject_Image : public WebserverBodyObject_Base #ifdef JAYPEG_ENCODE_SUPPORT , public JayEncodedData #endif // JAYPEG_ENCODE_SUPPORT { public: virtual ~WebserverBodyObject_Image(); static OP_STATUS Make(WebserverBodyObject_Image *&imageBodyObject, Image image, BOOL jpg, int width, int height, int quality); /* From WebserverBodyObject_Base */ OP_BOOLEAN GetData(int length, char *buf, int &LengthRead); OP_STATUS ResetGetData(); OP_BOOLEAN GetDataSize(int &size); #ifdef JAYPEG_ENCODE_SUPPORT /* From JayEncodedData */ virtual OP_STATUS dataReady(const void* data, unsigned int datalen); #endif // JAYPEG_ENCODE_SUPPORT private: WebserverBodyObject_Image(Image image, BOOL jpg, int width, int height, int quality); virtual OP_STATUS InitiateInternalData(); Image m_image; OpBitmap *m_image_bitmap; BOOL m_produce_jpg; PngEncFeeder m_feeder; PngEncRes m_res; int m_bytesOfLineServed; #ifdef JAYPEG_ENCODE_SUPPORT UINT32 *m_scanline_data; JayEncoder m_encoder; char* m_buf; int m_line_number; unsigned int m_data_length; unsigned int m_max_length; BOOL m_max_length_reached; BOOL m_more; int m_quality; #endif // JAYPEG_ENCODE_SUPPORT }; #ifdef JAYPEG_ENCODE_SUPPORT class WebserverBodyObject_CanvasToJpeg : public WebserverBodyObject_Base, public JayEncodedData { public: virtual ~WebserverBodyObject_CanvasToJpeg(); static OP_STATUS Make(WebserverBodyObject_CanvasToJpeg *&imageBodyObject, Canvas *canvas, int quality); /* From WebserverBodyObject_Base */ OP_BOOLEAN GetData(int length, char *buf, int &LengthRead); OP_STATUS ResetGetData(); OP_BOOLEAN GetDataSize(int &size); /* From ImageListener */ /* From JayEncodedData */ virtual OP_STATUS dataReady(const void* data, unsigned int datalen); private: WebserverBodyObject_CanvasToJpeg(Canvas *canvas, int quality); virtual OP_STATUS InitiateInternalData(); Canvas *m_canvas; JayEncoder m_encoder; OpBitmap *m_image_bitmap; UINT32 *m_scanline_data; // PngEncFeeder m_feeder; // PngEncRes m_res; char* m_buf; int m_line_number; unsigned int m_data_length; unsigned int m_max_length; BOOL m_max_length_reached; BOOL m_more; int m_quality; }; #endif // JAYPEG_ENCODE_SUPPORT class WebserverBodyObject_File : public WebserverBodyObject_Base { public: virtual ~WebserverBodyObject_File(); static OP_STATUS Make(WebserverBodyObject_File *&fileBodyObject, const OpStringC16 &file_name); /* From WebserverBodyObject_Base */ OP_BOOLEAN GetData(int length, char *buf, int &LengthRead); OP_STATUS ResetGetData(); OP_BOOLEAN GetDataSize(int &size); protected: virtual OP_STATUS InitiateInternalData(); WebserverBodyObject_File(); OpString m_file_path; OpFile m_file; }; #ifdef WEBSERVER_SUPPORT class WebserverBodyObject_UploadedFile : public WebserverBodyObject_File { public: virtual ~WebserverBodyObject_UploadedFile(); static OP_STATUS Make(WebserverBodyObject_UploadedFile *&fileBodyObject, WebserverUploadedFile *file); private: virtual OP_STATUS InitiateInternalData(); WebserverBodyObject_UploadedFile(WebserverUploadedFile *uploadedFile); WebserverUploadedFileWrapper m_uploaded_file; }; #endif // WEBSERVER_SUPPORT class WebserverBodyObject_OpString8 : public WebserverBodyObject_Base { public: virtual ~WebserverBodyObject_OpString8(); static OP_STATUS Make(WebserverBodyObject_OpString8 *&stringBodyObject, const OpStringC16 &bodyData); static OP_STATUS Make(WebserverBodyObject_OpString8 *&stringBodyObject, const OpStringC8 &bodyData); /* From WebserverBodyObject_Base */ OP_BOOLEAN GetData(int length, char *buf, int &LengthRead); OP_BOOLEAN GetDataPointer(char *&dataPointer); OP_STATUS ResetGetData(); OP_BOOLEAN GetDataSize(int &size); private: virtual OP_STATUS InitiateInternalData(); WebserverBodyObject_OpString8(); int m_length; int m_numberOfCharsRetrieved; OpString8 m_string; }; class WebserverBodyObject_Binary : public WebserverBodyObject_Base { public: ~WebserverBodyObject_Binary(); static OP_STATUS Make(WebserverBodyObject_Binary *&stringBodyObject, const unsigned char* data = NULL, unsigned int dataLength = 0); /* From WebserverBodyObject_Base */ OP_BOOLEAN GetData(int length, char *buf, int &LengthRead); OP_BOOLEAN GetDataPointer(char *&dataPointer); OP_STATUS SetDataPointer(char *dataPointer, unsigned int dataLength); /* Takes over the dataPointer */ OP_STATUS ResetGetData(); OP_BOOLEAN GetDataSize(int &size); private: WebserverBodyObject_Binary(); OP_STATUS InitiateInternalData(); unsigned char *m_binaryString; unsigned int m_dataLength; unsigned int m_numberOfBytesRetrieved; }; #endif /*WEBSERVER_BODY_OBJECTS_H_*/
#include <iostream> #include <vector> #include <algorithm> using namespace std; int n, m; vector<int> nums; vector<int> targets; int low, high, mid; int upperBound(int target){ low = 0; high = nums.size() - 1; while(low <= high){ mid = (low + high) / 2; if(nums[mid] <= target){ low = mid + 1; }else{ high = mid - 1; } } int ret = (nums[low-1] == target) ? low-1:-1; return ret; } int lowerBound(int target){ low = 0; high = nums.size() - 1; while(low <= high){ mid = (low + high) / 2; if(nums[mid] >= target){ high = mid - 1; }else{ low = mid + 1; } } int ret = (nums[high+1] == target) ? high + 1:-1; return ret; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; while(n--){ int tp; cin >> tp; nums.push_back(tp); } cin >> m; while(m--){ int tp; cin >> tp; targets.push_back(tp); } sort(nums.begin(), nums.end()); for(int targ : targets){ int _low = lowerBound(targ); int _high = upperBound(targ); int ret = (_low == -1) ? 0:_high-_low+1; cout << ret << " "; } return 0; }
#include <iostream> #include <vector> #include <map> #include <algorithm> using namespace std; pair<int, int> search_min_sub_segment(const vector<int>& Trees, const int& cnt_uniq_trees) { vector<int> unique(cnt_uniq_trees + 1); int cnt_of_uniq = 0; int best_l = 1, best_r = Trees.size(); for (int l = 0, r = 0;r < Trees.size();) { int elem = Trees[r]; if (!unique[elem]++) ++cnt_of_uniq; ++r; if (cnt_of_uniq == cnt_uniq_trees) { while (unique[elem]) { elem = Trees[l]; --unique[elem]; ++l; } --cnt_of_uniq; if (r - l < best_r - best_l) { best_r = r; best_l = l; } } } return make_pair(best_l, best_r); } int main() { int N, K; cin >> N >> K; vector<int> trees(N); for (auto& tree : trees) cin >> tree; pair<int, int> ans = search_min_sub_segment(trees, K); cout << ans.first << " " << ans.second; }
#include "pch.h" #include "StateMachine.h" #include "GameObject.h" #include "GameObjectData/GameObjectData.h" StateMachine::StateMachine() :OnStateChangeEvent(std::make_unique<StateChangeEvent>()) { } void StateMachine::Start(GameObject* aOwner) { m_owner = aOwner; m_data = m_owner->GetData(); }
#include "precompiled.h" #include "script/script.h" #include "script/jsscript.h" #include "vfs/vfs.h" #include "vfs/file.h" #pragma warning( disable : 4311 4312 ) REGISTER_STARTUP_FUNCTION(jsscript, jsscript::init, 10); namespace jsscript { JSBool jsexecfile(JSContext *cx, uintN argc, jsval *vp); JSBool jsdumpobject(JSContext *cx, uintN argc, jsval *vp); JSBool jssetzeal(JSContext *cx, uintN argc, jsval *vp); JSBool jsclassof(JSContext *cx, uintN argc, jsval *vp); JSBool jsparentof(JSContext *cx, uintN argc, jsval *vp); } void jsscript::init() { script::gScriptEngine->AddFunction("execfile", 1, jsscript::jsexecfile); script::gScriptEngine->AddFunction("dumpobject", 1, jsscript::jsdumpobject); script::gScriptEngine->AddFunction("setzeal", 1, jsscript::jssetzeal); script::gScriptEngine->AddFunction("classof", 1, jsscript::jsclassof); script::gScriptEngine->AddFunction("parentof", 1, jsscript::jsparentof); } JSBool jsscript::jsexecfile(JSContext *cx, uintN argc, jsval *vp) { if (argc != 1) { script::gScriptEngine->ReportError("execfile() takes 1 argument"); return JS_FALSE; } vfs::File file = vfs::getFile(JS_GetStringBytes(JS_ValueToString(cx, JS_ARGV(cx,vp)[0]))); if (file) { script::gScriptEngine->RunScript(file); } else { script::gScriptEngine->ReportError("execfile(): unable to open %s", JS_GetStringBytes(JS_ValueToString(cx, JS_ARGV(cx,vp)[0]))); return JS_FALSE; } return JS_TRUE; } JSBool jsscript::jsdumpobject(JSContext *cx, uintN argc, jsval *vp) { if (argc != 1) { script::gScriptEngine->ReportError("dumpobject(): takes 1 argument"); return JS_FALSE; } if (!JSVAL_IS_OBJECT(JS_ARGV(cx,vp)[0])) { script::gScriptEngine->ReportError("dumpobject(): argument must be an object"); return JS_FALSE; } script::gScriptEngine->DumpObject(JSVAL_TO_OBJECT(JS_ARGV(cx,vp)[0])); return JS_TRUE; } JSBool jsscript::jssetzeal(JSContext *cx, uintN argc, jsval *vp) { if (argc != 1) { script::gScriptEngine->ReportError("setzeal(): takes 1 argument"); return JS_FALSE; } if (!JSVAL_IS_NUMBER(JS_ARGV(cx,vp)[0])) { script::gScriptEngine->ReportError("setzeal(): argument must be a number"); return JS_FALSE; } int32 zeal; JS_ValueToECMAInt32(cx, JS_ARGV(cx,vp)[0], &zeal); #ifdef DEBUG JS_SetGCZeal(cx, zeal); #endif return JS_TRUE; } JSBool jsscript::jsclassof(JSContext *cx, uintN argc, jsval *vp) { if (argc != 1) { script::gScriptEngine->ReportError("classof(): takes 1 argument"); return JS_FALSE; } if (!JSVAL_IS_OBJECT(JS_ARGV(cx,vp)[0])) { JS_RVAL(cx,vp) = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, "none")); } else JS_RVAL(cx,vp) = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, script::gScriptEngine->GetClassName(JSVAL_TO_OBJECT(JS_ARGV(cx,vp)[0])))); return JS_TRUE; } JSBool jsscript::jsparentof(JSContext *cx, uintN argc, jsval *vp) { if (argc != 1) { script::gScriptEngine->ReportError("parentof(): takes 1 argument"); return JS_FALSE; } if (!JSVAL_IS_OBJECT(JS_ARGV(cx,vp)[0])) return JS_FALSE; JS_RVAL(cx,vp) = OBJECT_TO_JSVAL(JS_GetParent(cx, JSVAL_TO_OBJECT(JS_ARGV(cx,vp)[0]))); return JS_TRUE; }
// // YouMeVoiceEngineImp.hpp // TalkCppSample // // Created by 杜红 on 2017/3/21. // // #ifndef YouMeVoiceEngineImp_hpp #define YouMeVoiceEngineImp_hpp #include <stdio.h> #include "IYouMeEventCallback.h" #define YouMe_Log( ... ) //printf("_______________YouMe:");printf( __VA_ARGS__ );printf("\n"); class YouMeVoiceEngineImp : public IYouMeEventCallback{ public: static YouMeVoiceEngineImp* getInstance(); void onEvent(const YouMeEvent event, const YouMeErrorCode error, const char * channel, const char * param) ; }; #endif /* YouMeVoiceEngineImp_hpp */
#include <iostream> #include <string> int main() { char skizb[4]; char verj[4]; int zngaluQanak = 0; std::cout << "mutqagreq skzbi jam:rope - verji Jam:rope" << std::endl; std::cin >> skizb; std::cin >> verj; int skzbiJam = ((int)skizb[0] - (int)'0') * 10 + (int)skizb[1]-(int)'0'; int verjiJam = ((int)verj[0] - (int)'0') * 10 + (int)verj[1]-(int)'0'; int skzbiRope = ((int)skizb[3] - (int)'0') * 10 + (int)skizb[4]-(int)'0'; int verjiRope = ((int)verj[3] - (int)'0') * 10 + (int)verj[4]-(int)'0'; if(skzbiJam > verjiJam || ( skzbiJam == verjiJam && skzbiRope >= verjiRope )) { std::cout << "jamayin intervaln sxal e"; } else { if (12 < skzbiJam < 0 || 12 < verjiJam < 0 || 60 < skzbiRope < 0 || 60 < verjiRope < 0){ std::cout << "sxal jam e mutqagrac"; } else if (6 >= skzbiRope) { zngaluQanak++; } else if(6 > verjiRope) { zngaluQanak--; } zngaluQanak = zngaluQanak + (verjiJam - skzbiJam )*2; std::cout << "Zangeri qanakn klini =" << zngaluQanak; } return 0; }
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 1000 #define INF 0x3F3F3F3F int table[MAXN+5][MAXN+5]; string str; int DP(int i, int j){ if( !(i<j) ) return table[i][j] = 0; if( table[i][j] != INF ) return table[i][j]; if( str[i] == str[j] ) table[i][j] = min(table[i][j], DP(i+1, j-1)); table[i][j] = min(table[i][j], DP(i+1, j-1)+1); table[i][j] = min(table[i][j], DP( i, j-1)+1); table[i][j] = min(table[i][j], DP(i+1, j)+1); return table[i][j]; } int main(int argc, char const *argv[]) { int kase; scanf("%d",&kase); for(int K = 1 ; K <= kase ; K++ ){ cin >> str; memset(table,0x3F,sizeof(table)); printf("Case %d: %d\n", K, DP(0,str.size()-1)); } return 0; }
#pragma once class ThirdPersonCameraComponent : public hg::IComponent { public: ThirdPersonCameraComponent(); void LoadFromXML(tinyxml2::XMLElement * data); virtual int GetTypeID() const { return s_TypeID; } void Init(); void Update(); void AttachTo(hg::Entity* target); virtual hg::IComponent* MakeCopyDerived() const; static uint32_t s_TypeID; void SetOffset(const float x, const float y, const float z); void SetDistance(const float distance); void SetSpeed(const float speed); void SetDesireOffsetDistance(FXMVECTOR& offset); void OnMessage(hg::Message* msg)override; float GetDistance()const { return m_distance; } void RecenterCamera(); private: hg::Entity* m_attached; XMFLOAT3 m_direction; XMFLOAT3 m_curOffsetDistance; XMFLOAT3 m_desireOffsetDistance; float m_distance; float m_maxDistance; float m_speed; };
#include<iostream> #include<cstdlib> using namespace std; class Stack { struct node { int data; node* link; }*top; public: Stack(); void push(int); void pop(); void display(); }; Stack::Stack() { top = NULL; } void Stack::push(int x) { node* temp; temp = new node; temp->data = x; temp->link = top; top = temp; } void Stack::pop() { if(top == NULL) { cout << "Stack is empty!" << endl; } else { node* temp = new node; temp = top; top = top->link; temp->link = NULL; cout << "Popped " << temp->data << endl; delete temp; } } void Stack::display() { node *temp; temp = new node; temp = top; while(temp != NULL) { cout << temp->data << " "; temp = temp->link; } } int main() { Stack s; s.push(10); s.push(20); s.push(30); s.push(40); s.push(50); s.pop(); s.pop(); s.display(); system("pause"); return 0; }
// // graph.cpp // A_STAR // // Created by Reb and Santi // Copyright 2018 Smols. All rights reserved. // #include "Graph.hpp" #include "Node.hpp" #include <map> #include <vector> #include <string> #include <iostream> std::ostream &operator<<(std::ostream &os, const Graph &g) { os << "This graph has nodes:" << std::endl; for (auto const& entry: g.nodes) { os << "\t" << entry.second << std::endl; } return os; } //istream format //N \n, number of nodes //each node has format { //S \n, name of node //H \n, heuristic //E \n, number of neighbors // for each neighbor { // e \n, name of neighbor // d \n, distance for neighbors // } //} // first node is starting node // second node is ending node std::istream &operator>>(std::istream &is, Graph &g) { std::vector<Node> all_nodes; int N; is >> N; //std::cout << N << std::endl; for (int i = 0; i < N; i++) { std::string name; is >> name; int heuristic; is >> heuristic; int E; is >> E; std::cout << "node " << name << " / heuristic " << heuristic << " / " << E << " neighbors" << std::endl; std::vector<distances> neighbors; for (int j = 0; j < E; j++) { std::string neighbor; int distance; is >> neighbor; is >> distance; std::cout << name << "->" << neighbor << ", " << distance << std::endl; neighbors.push_back(distances(neighbor, distance)); } if (i == 0) { g.start = name; } if (i == 1) { g.end = name; } Node n(name, heuristic, neighbors); g.nodes.insert(std::pair<std::string, Node>(name, n)); std::cout<<"---------"<<std::endl; } return is; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int a[1000100]; bool rec[1000100]; /* int big(int l,int r,int k) { while (l < r) { int mid = l + (r - l)/2; if (k >= a[mid + 1]) l = mid+1; else r = mid; } return l; } int small(int l,int r,int k) { while (l < r) { int mid = l + (r - l)/2; if (k <= a[mid]) r = mid; else l = mid+1; } if (k != a[l]) return 0; return l; } */ int main() { int n,m; while (scanf("%d%d",&n,&m) != EOF) { memset(rec,0,sizeof(rec)); int k,sl,sr,l,r; for (int i = 1;i <= n; i++) scanf("%d",&a[i]); sort(a+1,a+n+1); for (int i = 1;i <= m; i++) { scanf("%d",&k); l = 1,r = n; while (l < r) { int mid = l + (r - l)/2; if (k <= a[mid]) r = mid; else l = mid+1; } if (k != a[l]) sl = 0; else sl = l; if (!sl || rec[sl]) { printf("0\n"); continue; } l = 1,r = n; while (l < r) { int mid = l + (r - l)/2; if (k >= a[mid + 1]) l = mid+1; else r = mid; } sr = l; //cout << l << " " << r << endl; printf("%d\n",sr-sl+1); rec[sl] = true; } } return 0; }
#ifndef _PAYLOAD_H_ #define _PAYLOAD_H_ #include <boost/shared_ptr.hpp> class Payload; typedef boost::shared_ptr<Payload> PayloadPtr; class Payload { public: Payload(); ~Payload(); void inject(const PayloadPtr& ref); private: PayloadPtr reference; }; #endif // _PAYLOAD_H_
#ifndef __STDAFX_HPP_INCLUDED__ #define __STDAFX_HPP_INCLUDED__ #include "config.hpp" #if defined(CURSES_HAS_PRAGMA_ONCE) && !defined(CURSES_GCC_VERSION) #pragma once #endif // CURSES_HAS_PRAGMA_ONCE #include "geometry.hpp" #include "sobject.hpp" //#include "views.hpp" #endif // __STDAFX_HPP_INCLUDED__
#include "analyzers.h" //------------------------------------------------------------------------------ // Анализ на функцию void FuncDeclAnalyzer::run(const MatchFinder::MatchResult &Result) { ASTContext *context = Result.Context; const FunctionDecl *FD = Result.Nodes.getNodeAs<FunctionDecl>("funcDecl"); // We do not want to convert header files! ////if (!FD || !Context->getSourceManager().isWrittenInMainFile(FD->getForLoc())) if (!FD) return; getFuncDeclParameters(FD); //FD->dump(); } //------------------------------------------------------------------------------ // Анализ на глобальную переменную void DeclBaseVarGlobalMemoryAnalyzer::run(const MatchFinder::MatchResult &Result) { ASTContext *context = Result.Context; const VarDecl *VD = Result.Nodes.getNodeAs<VarDecl>("declBaseVarGlobalMemory"); // We do not want to convert header files! ////if (!VD || !Context->getSourceManager().isWrittenInMainFile(VD->getForLoc())) if (!VD) return; getVarDeclParameters(VD); //VD->dump(); } //------------------------------------------------------------------------------ // Анализатор цикла с заданными инициализатором, условием... Заимствован из примера void LoopAnalyzer::run(const MatchFinder::MatchResult &Result) { ASTContext *Context = Result.Context; const ForStmt *FS = Result.Nodes.getNodeAs<ForStmt>("forLoop"); // We do not want to convert header files! if (!FS || !Context->getSourceManager().isWrittenInMainFile(FS->getForLoc())) return; const VarDecl *IncVar = Result.Nodes.getNodeAs<VarDecl>("incVarName"); const VarDecl *CondVar = Result.Nodes.getNodeAs<VarDecl>("condVarName"); const VarDecl *InitVar = Result.Nodes.getNodeAs<VarDecl>("initVarName"); if (!areSameVariable(IncVar, CondVar) || !areSameVariable(IncVar, InitVar)) return; llvm::outs() << "Potential array-based loop discovered.\n"; } //------------------------------------------------------------------------------ // Анализ на целочисленную переменную void IntVarDeclAnalyzer::run(const MatchFinder::MatchResult &Result) { ASTContext *Context = Result.Context; const VarDecl *VD = Result.Nodes.getNodeAs<VarDecl>("intVarDecl"); // We do not want to convert header files! ////if (!VD || !Context->getSourceManager().isWrittenInMainFile(VD->getForLoc())) if (!VD) return; llvm::outs() << "Integer variable.\n"; // Определение и тестовый вывод основных параметров описания переменных getVarDeclParameters(VD); //VD->dump(); } //------------------------------------------------------------------------------ // Анализ на глобальную целочисленную переменную void IntVarDeclGlobalMemoryAnalyzer::run(const MatchFinder::MatchResult &Result) { ASTContext *Context = Result.Context; const VarDecl *VD = Result.Nodes.getNodeAs<VarDecl>("intVarGlobalMemoryDecl"); // We do not want to convert header files! ////if (!VD || !Context->getSourceManager().isWrittenInMainFile(VD->getForLoc())) if (!VD) return; llvm::outs() << "I`m variable. My name is " << VD->getNameAsString() << "\n"; if(VD->hasLocalStorage()) { llvm::outs() << " hasLocalStorage.\n"; } else { llvm::outs() << " not hasLocalStorage.\n"; } if(VD->isStaticLocal()) { llvm::outs() << " isStaticLocal.\n"; } else { llvm::outs() << " not isStaticLocal.\n"; } if(VD->hasExternalStorage()) { llvm::outs() << " hasExternalStorage.\n"; } else { llvm::outs() << " not hasExternalStorage.\n"; } if(VD->hasGlobalStorage()) { llvm::outs() << " hasGlobalStorage.\n"; } else { llvm::outs() << " not hasGlobalStorage.\n"; } if(VD->isLocalVarDecl()) { llvm::outs() << " isLocalVarDecl.\n"; } else { llvm::outs() << " not isLocalVarDecl.\n"; } if(VD->isLocalVarDeclOrParm()) { llvm::outs() << " isLocalVarDeclOrParm.\n"; } else { llvm::outs() << " not isLocalVarDeclOrParm.\n"; } if(VD->getAnyInitializer()) { llvm::outs() << " getAnyInitializer.\n"; } else { llvm::outs() << " not getAnyInitializer.\n"; } // APValue *initVal = VD->evaluateValue(); // if(initVal != nullptr) { // llvm::outs() << " evaluateValue = "; // if(initVal->isInt()) { // llvm::outs() << initVal->getInt(); // } // llvm::outs() << ".\n"; // } else { // llvm::outs() << " not evaluateValue.\n"; // } //VD->dump(); }
#include<thread> #include<iostream> #include <iomanip> #include<chrono> #include<ctime> #include<vector> using namespace std; class Timer{ bool is_clear; clock_t start_time, end_time; public: Timer(){ is_clear = false; } template<typename T> void setAlarmClock(T func, tm *ptm){ // cout<<ptm<<endl; is_clear = false; // printf("in timer: %d/%d/%d/%d:%d:%d\n", 1900 + ptm->tm_year, 1 + ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); thread t([=] () { if (is_clear) return; // printf("in thread: %d/%d/%d/%d:%d:%d\n", 1900 + ptm->tm_year, 1 + ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); std::this_thread::sleep_until(chrono::system_clock::from_time_t (mktime(ptm))); if (is_clear) return; func(); }); t.detach(); } template<typename T> void setTimeout(T func, int delay){ is_clear = false; thread t([=] () { if (is_clear) return; std::this_thread::sleep_for(std::chrono::milliseconds(delay)); if (is_clear) return; func(); }); t.detach(); } template<typename T> void setInterval(T func, int interval, int times = -1){ is_clear = false; thread t([=] () { int t_times = times; while (t_times==-1 || t_times>0) { if (is_clear) return; std::this_thread::sleep_for(std::chrono::milliseconds(interval)); if (is_clear) return; func(); if (t_times>0) t_times--; } }); t.detach(); } void reset(){ } void clear(){ is_clear = true; } }; class ClockDetail{ public: time_t start_time; bool is_running; int interval; int times; char* details; ClockDetail(){ is_running = true; interval = -1; times = 0; details = NULL; } }; class AlarmClock{ vector<Timer*> clocks; vector<ClockDetail*> details; // template<typename T> // void on_destroy(T func, int id){ // func(); // clear_clock(id); // } public: AlarmClock(){ } int get_free_clock(){ for(int i=0; i<clocks.size(); i++){ if (clocks[i]==NULL) return i; } Timer *timer = NULL; clocks.push_back(timer); details.push_back(new ClockDetail()); return clocks.size()-1; } int clear_clock(int id){ if (id<clocks.size()-1){ if (clocks[id]!=NULL){ delete(clocks[id]); clocks[id] = NULL; return 0; } else { return -2; // clock is already clear } } else { return -1; // no such clock } } static void copy_tm(tm* p1, tm* p2){ p2->tm_hour = p1->tm_hour; p2->tm_min = p1->tm_min; p2->tm_sec = p1->tm_sec; p2->tm_mday = p1->tm_mday; p2->tm_mon = p1->tm_mon; p2->tm_year = p1->tm_year; } tm* set_time(int tm_sec, int tm_min, int tm_hour, int tm_mday = -1, int tm_month = -1, int tm_year = -1){ time_t ptime; time(&ptime); tm *ptm_tmp = localtime(&ptime); tm* ptm = new tm(); copy_tm(ptm_tmp, ptm); ptm->tm_sec = tm_sec; ptm->tm_min = tm_min; ptm->tm_hour = tm_hour; if (tm_mday!=-1) ptm->tm_mday = tm_mday; if (tm_month!=-1) ptm->tm_mon = tm_month; if (tm_year!=-1) ptm->tm_year = tm_year; return ptm; } template<typename T> int setOnceClock(T func, tm* ptm){ int id = get_free_clock(); Timer *timer = clocks[id]; timer = new Timer(); timer->setAlarmClock(func, ptm); return id; } template<typename T> int setIntervalClock(T func, tm* ptm, int interval, int times = -1){ int id = get_free_clock(); Timer *timer = clocks[id]; timer = new Timer(); while(difftime(mktime(ptm), time(NULL))<0){ // printf("%d/%d/%d/%d:%d:%d\n\n", 1900 + ptm->tm_year, 1 + ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); ptm->tm_sec += interval/1000; } // printf("%d/%d/%d/%d:%d:%d\n\n", 1900 + ptm->tm_year, 1 + ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); timer->setAlarmClock([=](){ func(); timer->setInterval(func, interval, times); }, ptm); return id; } }; // void print(){ // cout<<"time_out\n"; // time_t ptime; // time(&ptime); // tm *ptm = localtime(&ptime); // printf("%d/%d/%d/%d:%d:%d\n\n", 1900 + ptm->tm_year, 1 + ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); // } // // int main(){ // AlarmClock ac; // // ac.setOnceClock(print, ac.set_time(0,47,18)); // ac.setIntervalClock(print, ac.set_time(0, 0, 19), 60*1000); // // cout<<difftime(time(NULL), mktime(ac.set_time(0,1,19))); // while(true){ // // time(&ptime); // // tm *ptm = localtime(&ptime); // // printf("%d/%d/%d/%d:%d:%d\n", 1900 + ptm->tm_year, 1 + ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); // } // // time(&ptime); // // ptm = localtime(&ptime); // // printf("%d/%d/%d/%d:%d:%d\n", 1900 + ptm->tm_year, 1 + ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec); // }
#include <map> #include <vector> using namespace std; class tower { public: Point loc; vector<Point> direc; vector<bullet*> fired; bullet *b; tower(int x, int y); std::pair<bool, Point> targetScan(board* m); void shoot(board* m); }; tower::tower(int x, int y) { loc.x = x; loc.y = y; direc.push_back({0,-1}); direc.push_back({0, 1}); direc.push_back({-1, 0}); direc.push_back({1, 0}); direc.push_back({-1, -1}); direc.push_back({1,1}); direc.push_back({-1,1}); direc.push_back({1, -1}); } void tower::shoot(board* m) { auto [targeting, target] = targetScan(m); if (targeting) { b = new bullet(loc, target); fired.push_back(b); } } std::pair<bool, Point> tower::targetScan(board* m) { struct target { Point loc; int distance; target(Point l, int d) : loc(l), distance(d) { } }; int x, y; map<Point, bool> seen; Point next; queue<target*> radar; target* curr = new target(loc, 0); seen[curr->loc] = true; radar.push(curr); while (!radar.empty()) { curr = radar.front(); radar.pop(); x = curr->loc.x; y = curr->loc.y; if (m->world[x][y].populated) { return make_pair(true, curr->loc); } for (auto d : direc) { next = {curr->loc.x + d.x, curr->loc.y + d.y}; if (inbounds(next.x, next.y) && seen[next] == false) { if (curr->distance + 1 < 10) { radar.push(new target(next, curr->distance + 1)); } } } } next = {0,0}; return make_pair(false, next); }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<algorithm> #include<cmath> using namespace std; struct point{ int ed; int son[3]; }; point trie[3000100]; int sum = 0; string st; void build() { int s = 0; for (int i = 0;i < st.size(); i++) { if (!trie[s].son[st[i] - 'a']) trie[s].son[st[i] - 'a'] = ++sum; s = trie[s].son[st[i] - 'a']; } trie[s].ed = 1; } bool find(int s,int k,int c) { bool ans = false; if (k >= st.size()) if (trie[s].ed) return true; else return false; if (c > 0) { for (int i = 0;i < 3; i++) if (trie[s].son[i]) { if ('a' + i == st[k]) ans = find(trie[s].son[i],k+1,c); else ans = find(trie[s].son[i],k+1,c-1); if (ans) break; } } else if (trie[s].son[st[k] - 'a']) ans = find(trie[s].son[st[k] - 'a'],k+1,c); else ans = false; return ans; } int main() { int n,m; while (scanf("%d%d",&n,&m) != EOF) { sum = 0; memset(trie,0,sizeof(trie)); for (int i = 1;i <= n; i++) { cin >> st; build(); } for (int i = 1;i <= m; i++) { cin >> st; if (find(0,0,1)) printf("YES\n"); else printf("NO\n"); } } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef BROWSER_MENU_HANDLER_H #define BROWSER_MENU_HANDLER_H #include "adjunct/desktop_util/settings/SettingsListener.h" #include "adjunct/quick/menus/DesktopMenuHandler.h" #include "modules/util/OpHashTable.h" class ClassicApplication; class ClassicGlobalUiContext; class SpellCheckContext; class DesktopMenuContext; class BrowserMenuHandler : public DesktopMenuHandler , public SettingsListener { public: BrowserMenuHandler(ClassicApplication& application, ClassicGlobalUiContext& global_context, SpellCheckContext& spell_check_context); // // DesktopMenuHandler // virtual PrefsSection* GetMenuSection(const char* menu_name); /** * @override */ virtual void ShowPopupMenu(const char* popup_name, const PopupPlacement& placement, INTPTR popup_value = 0, BOOL use_keyboard_context = FALSE, DesktopMenuContext* context = NULL); virtual BOOL IsShowingMenu() const; virtual void OnMenuShown(BOOL shown, OpScopeDesktopWindowManager_SI::QuickMenuInfo& info); /** * @override */ virtual void AddMenuItems(void* platform_handle, const char* menu_name, INTPTR menu_value, INT32 start_at_index, OpInputContext* menu_input_context, BOOL is_sub_menu = FALSE); virtual void SetSpellSessionID(int id); virtual int GetSpellSessionID() const; #ifdef EMBROWSER_SUPPORT virtual void SetContextMenuWasBlocked(BOOL blocked); virtual BOOL GetContextMenuWasBlocked(); #endif // EMBROWSER_SUPPORT // // SettingsListener // void OnSettingsChanged(DesktopSettings* settings); private: class MenuSection : public OpString8 { public: MenuSection(const char* name, PrefsSection* section); ~MenuSection(); PrefsSection* GetSection(); private: PrefsSection* m_section; }; // Test if the point is in a OpBrwoserView static BOOL IsPointInPage(const OpPoint& pt); ClassicApplication* m_application; ClassicGlobalUiContext* m_global_context; OpAutoString8HashTable<MenuSection> m_menu_sections; SpellCheckContext* m_spell_check_context; BOOL m_showing_menu; #ifdef EMBROWSER_SUPPORT BOOL m_menu_blocked; #endif DesktopMenuContext* m_popup_menu_context; }; #endif // BROWSER_MENU_HANDLER_H
#include "stdafx.h" #include "SMBIOS.h" const char* LocateStringA (const char* str, UINT i) { static const char strNull[] = "Null String"; if (0 == i || 0 == *str) return strNull; while (--i) { str += strlen ((char*)str) + 1; } return str; } const wchar_t* LocateStringW (const char* str, UINT i) { static wchar_t buff[2048]; const char *pStr = LocateStringA (str, i); SecureZeroMemory (buff, sizeof (buff)); MultiByteToWideChar (CP_OEMCP, 0, pStr, strlen (pStr), buff, sizeof (buff)); return buff; } const char* toPointString (void* p) { return (char*)p + ((PSMBIOSHEADER)p)->Length; } bool ProcBIOSInfo (void* p, std::vector<std::string> &v) { PBIOSInfo pBIOS = (PBIOSInfo)p; const char *str = toPointString (p); v.push_back ("Поставщик: " + toString (LocateString (str, pBIOS->Vendor))); v.push_back ("Версия: " + toString (LocateString (str, pBIOS->Version))); v.push_back ("Дата выпуска: " + toString (LocateString (str, pBIOS->ReleaseDate))); v.push_back ("Размер: " + toString ((((pBIOS->ROMSize) + 1) * 64)) + " K"); if (pBIOS->Header.Length > 0x14) { // for spec v2.4 and later v.push_back ("Версия системы BIOS: " + toString ((UINT)pBIOS->MajorRelease) + "." + toString ((UINT)pBIOS->MinorRelease)); v.push_back ("Версия EC Firmware: " + toString ((UINT)pBIOS->ECFirmwareMajor) + "." + toString ((UINT)pBIOS->ECFirmwareMinor)); } return true; } bool ProcSysInfo (void* p, std::vector<std::string> &v) { PSystemInfo pSystem = (PSystemInfo)p; const char *str = toPointString (p); v.push_back ("Производитель: " + toString (LocateString (str, pSystem->Manufacturer))); v.push_back ("Наименование продукта: " + toString (LocateString (str, pSystem->ProductName))); v.push_back ("Версия: " + toString (LocateString (str, pSystem->Version))); v.push_back ("Серийный номер: " + toString (LocateString (str, pSystem->SN))); if (pSystem->Header.Length > 0x19) { // fileds for spec. 2.4 v.push_back ("Номер SKU: " + toString (LocateString (str, pSystem->SKUNumber))); v.push_back ("Семейство: " + toString (LocateString (str, pSystem->Family))); } return true; } bool ProcBoardInfo (void* p, std::vector<std::string> &v) { PBoardInfo pBoard = (PBoardInfo)p; const char *str = toPointString (p); v.push_back ("Производитель: " + toString (LocateString (str, pBoard->Manufacturer))); v.push_back ("Наименование продукта: " + toString (LocateString (str, pBoard->Product))); v.push_back ("Версия: " + toString (LocateString (str, pBoard->Version))); v.push_back ("Серийный номер: " + toString (LocateString (str, pBoard->SN))); v.push_back ("Asset Tag Number: " + toString (LocateString (str, pBoard->AssetTag))); if (pBoard->Header.Length > 0x08) { v.push_back ("Расположение на шасси: " + toString (LocateString (str, pBoard->LocationInChassis))); } return true; } bool ProcSystemEnclosure (void* p, std::vector<std::string> &v) { PSystemEnclosure pSysEnclosure = (PSystemEnclosure)p; const char *str = toPointString (p); v.push_back ("Производитель: " + toString (LocateString (str, pSysEnclosure->Manufacturer))); v.push_back ("Версия: " + toString (LocateString (str, pSysEnclosure->Version))); v.push_back ("Серийный номер: " + toString (LocateString (str, pSysEnclosure->SN))); v.push_back ("Asset Tag Number: " + toString (LocateString (str, pSysEnclosure->AssetTag))); return true; } bool ProcProcessorInfo (void* p, std::vector<std::string> &v) { PProcessorInfo pProcessor = (PProcessorInfo)p; const char *str = toPointString (p); v.push_back ("Тип сокета: " + toString (LocateString (str, pProcessor->SocketDesignation)) + "; Количество ядер: " + toString ((UINT)pProcessor->CoreCount)); v.push_back ("Тип процессора: " + toString (LocateString (str, pProcessor->Type))); v.push_back ("Производитель процессора: " + toString (LocateString (str, pProcessor->Manufacturer))); v.push_back ("Идентификационный номер: " + toString ((ULONG64)pProcessor->ID)); v.push_back ("Серийный номер: " + toString (LocateString (str, pProcessor->SerialNumber))); v.push_back ("Номер партии: " + toString (LocateString (str, pProcessor->PartNumber))); v.push_back ("Внешняя тактовая частота: " + toString (pProcessor->ExtClock) + " MГц"); v.push_back ("Максимальная тактовая частота : " + toString (pProcessor->MaxSpeed) + " MГц"); v.push_back ("Текущая тактовая частота: " + toString (pProcessor->CurrentSpeed) + " MГц"); return true; } bool ProcMemModuleInfo (void* p, std::vector<std::string> &v) { PMemModuleInfo pMemModule = (PMemModuleInfo)p; const char *str = toPointString (p); v.push_back ("Тип сокета памяти: " + toString (LocateString (str, pMemModule->SocketDesignation))); v.push_back ("Текущая скорость: " + toString ((UINT)pMemModule->CurrentSpeed) + " нс"); return true; } bool ProcCacheInfo (void* p, std::vector<std::string> &v) { PCacheInfo pCache = (PCacheInfo)p; const char* str = toPointString (p); //v.push_back ("Кэш процессора: " + toString (LocateString (str, pCache->SocketDesignation))); v.push_back(toString(LocateString(str, pCache->SocketDesignation)) + "; "); return true; } bool ProcOEMString (void* p, std::vector<std::string> &v) { PSMBIOSHEADER pHdr = (PSMBIOSHEADER)p; const char *str = toPointString (p); v.push_back ("OEM String: " + toString (LocateString (str, *(((char*)p) + 4)))); return true; } bool ProcMemoryDevice (void* p, std::vector<std::string> &v) { PMemoryDevice pMD = (PMemoryDevice)p; const char *str = toPointString (p); v.push_back ("Total Width: " + toString (pMD->TotalWidth) + " bits"); v.push_back ("Data Width: " + toString (pMD->DataWidth) + " bits"); v.push_back ("Device Locator: " + toString (LocateString (str, pMD->DeviceLocator))); v.push_back ("Bank Locator: " + toString (LocateString (str, pMD->BankLocator))); if (pMD->Header.Length > 0x15) { v.push_back ("Speed: " + toString (pMD->Speed)); v.push_back ("Manufacturer: " + toString (LocateString (str, pMD->Manufacturer))); v.push_back ("Serial Number: " + toString (LocateString (str, pMD->SN))); v.push_back ("Asset Tag Number: " + toString (LocateString (str, pMD->AssetTag))); v.push_back ("Part Number: " + toString (LocateString (str, pMD->PN))); } return true; } bool ProcMemoryArrayMappedAddress (void* p, std::vector<std::string> &v) { PMemoryArrayMappedAddress pMAMA = (PMemoryArrayMappedAddress)p; const char *str = toPointString (p); v.push_back ("Starting Address: 0x" + toString ((UINT)pMAMA->Starting)); v.push_back ("Ending Address: 0x" + toString ((UINT)pMAMA->Ending)); v.push_back ("Memory Array Handle: 0x" + toString ((UINT)pMAMA->Handle)); v.push_back ("Partition Width: 0x" + toString ((UINT)pMAMA->PartitionWidth)); return true; } bool ProcPortableBattery (void* p, std::vector<std::string> &v) { PPortableBattery pPB = (PPortableBattery)p; const char *str = toPointString (p); v.push_back ("Location: " + toString (LocateString (str, pPB->Location))); v.push_back ("Manufacturer: " + toString (LocateString (str, pPB->Manufacturer))); v.push_back ("Manufacturer Date: " + toString (LocateString (str, pPB->Date))); v.push_back ("Serial Number: " + toString (LocateString (str, pPB->SN))); return true; } int GetSMBInfo (int func, std::vector<std::string> &info) { typedef struct { BYTE t; bool (*Proc)(void*, std::vector<std::string> &); } TPFUNC; const TPFUNC tpfunc[] = { { 0, ProcBIOSInfo }, { 1, ProcSysInfo }, { 2, ProcBoardInfo }, { 3, ProcSystemEnclosure }, { 4, ProcProcessorInfo }, { 6, ProcMemModuleInfo }, { 7, ProcCacheInfo }, { 11, ProcOEMString }, { 17, ProcMemoryDevice }, { 19, ProcMemoryArrayMappedAddress }, { 22, ProcPortableBattery } }; DWORD needBufferSize = 0; // the seqence just for x86, but don't worry we know SMBIOS/DMI only exist on x86 platform const BYTE byteSignature[] = { 'B', 'M', 'S', 'R' }; const DWORD Signature = *((DWORD*)byteSignature); LPBYTE pBuff = NULL; needBufferSize = GetSystemFirmwareTable (Signature, 0, NULL, 0); pBuff = (LPBYTE)malloc (needBufferSize); if (pBuff) { GetSystemFirmwareTable (Signature, 0, pBuff, needBufferSize); const PRawSMBIOSData pDMIData = (PRawSMBIOSData)pBuff; LPBYTE p = (LPBYTE)(&(pDMIData->SMBIOSTableData)); const DWORD lastAddress = ((DWORD)p) + pDMIData->Length; PSMBIOSHEADER pHeader; for (;;) { pHeader = (PSMBIOSHEADER)p; if (tpfunc[func].t == pHeader->Type) tpfunc[func].Proc ((void*)pHeader, info); PBYTE nt = p + pHeader->Length; // point to struct end while (0 != (*nt | *(nt + 1))) nt++; // skip string area nt += 2; if ((DWORD)nt >= lastAddress) break; p = nt; } } else info.push_back ("Can not allocate memory for recevice SMBIOS/DMI table."); if (pBuff) free (pBuff); return 0; }
#include "Flags.hpp" char * PIPE_FILENAME = "./fifo_adas"; int setupNamedPipe(int rights) { int fd; if(rights == O_WRONLY) mkfifo(PIPE_FILENAME, 0666); //O_WRONLY - O_RDONLY fd = open(PIPE_FILENAME, rights); if(fd == -1) { char buffer[256]; char * message = strerror_r(errno, buffer, 256); std::cout << "(Open) " << errno << " : " << message << std::endl; } return fd; } void runningThread(int pipeDescriptor) { pid_t pid = fork(); if(pid == 0) { //Child while(1) { Data data; data.flag = RUNNING; std::sprintf (data.message, "Running Thread"); int err = write(pipeDescriptor,&data, sizeof(Data)); if(err == -1) { char buffer[256]; char * message = strerror_r(errno, buffer, 256); std::cout << "(Running Thread) " << errno << " : " << message << std::endl; break; } sleep(2); } } }
#ifndef COLUMN_H #define COLUMN_H #include <iostream> #include <string> #include <vector> #include "elevator.hpp" class Column { //int _id; int _numberOfFloors; int _numberOfColumns; int _callButtonFloor; std::vector<int> _listOfCallButtonFloors; std::vector<Elevator> _elevatorList; public: Column(int id, int numberOfFloors, int numberOfColumns, std::vector<Elevator> &elevatorList); //void setId(int id); void setNumberOfFloors(int numberOfFloors); void setNumberOfColumns(int numberOfColumns); //int getId(); int getNumberOfFloors(); int getNumberOfColumns(); std::vector<Elevator> getElevatorList(); Elevator getClosestElevator(); Column(); }; #endif // COLUMN_H
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * 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/>. */ #include "backend/opencl/wrappers/OclPlatform.h" #include "3rdparty/rapidjson/document.h" #include "backend/opencl/wrappers/OclLib.h" std::vector<xmrig::OclPlatform> xmrig::OclPlatform::get() { const std::vector<cl_platform_id> platforms = OclLib::getPlatformIDs(); std::vector<OclPlatform> out; if (platforms.empty()) { return out; } out.reserve(platforms.size()); for (size_t i = 0; i < platforms.size(); i++) { out.emplace_back(i, platforms[i]); } return out; } void xmrig::OclPlatform::print() { const auto platforms = OclPlatform::get(); printf("%-28s%zu\n\n", "Number of platforms:", platforms.size()); for (const auto &platform : platforms) { printf(" %-26s%zu\n", "Index:", platform.index()); printf(" %-26s%s\n", "Profile:", platform.profile().data()); printf(" %-26s%s\n", "Version:", platform.version().data()); printf(" %-26s%s\n", "Name:", platform.name().data()); printf(" %-26s%s\n", "Vendor:", platform.vendor().data()); printf(" %-26s%s\n\n", "Extensions:", platform.extensions().data()); } } rapidjson::Value xmrig::OclPlatform::toJSON(rapidjson::Document &doc) const { using namespace rapidjson; auto &allocator = doc.GetAllocator(); if (!isValid()) { return Value(kNullType); } Value out(kObjectType); out.AddMember("index", static_cast<uint64_t>(index()), allocator); out.AddMember("profile", profile().toJSON(doc), allocator); out.AddMember("version", version().toJSON(doc), allocator); out.AddMember("name", name().toJSON(doc), allocator); out.AddMember("vendor", vendor().toJSON(doc), allocator); out.AddMember("extensions", extensions().toJSON(doc), allocator); return out; } std::vector<xmrig::OclDevice> xmrig::OclPlatform::devices() const { std::vector<OclDevice> out; if (!isValid()) { return out; } cl_uint num_devices = 0; OclLib::getDeviceIDs(id(), CL_DEVICE_TYPE_GPU, 0, nullptr, &num_devices); if (num_devices == 0) { return out; } out.reserve(num_devices); std::vector<cl_device_id> devices(num_devices); OclLib::getDeviceIDs(id(), CL_DEVICE_TYPE_GPU, num_devices, devices.data(), nullptr); for (size_t i = 0; i < devices.size(); ++i) { out.emplace_back(i, devices[i], id()); } return out; } xmrig::String xmrig::OclPlatform::extensions() const { return OclLib::getString(id(), CL_PLATFORM_EXTENSIONS); } xmrig::String xmrig::OclPlatform::name() const { return OclLib::getString(id(), CL_PLATFORM_NAME); } xmrig::String xmrig::OclPlatform::profile() const { return OclLib::getString(id(), CL_PLATFORM_PROFILE); } xmrig::String xmrig::OclPlatform::vendor() const { return OclLib::getString(id(), CL_PLATFORM_VENDOR); } xmrig::String xmrig::OclPlatform::version() const { return OclLib::getString(id(), CL_PLATFORM_VERSION); }
#include <Windows.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { }
#include<iostream> using namespace std; int prime(int c) { int a,flag; flag=0; a=1; while(a<=c) { if(c%a==0) { flag++; } a++; } if(flag==2) { return 1; } else return 0; } int main() { int c,x; c=1; for(int i=1;i<=4;i++) { for(int j=1;j<=i;j++) { x=prime(c); if(x==1) { cout<<"# "; } else cout<<"* "; c++; } cout<<"\n"; } return 0; }
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "Direct3D9Renderer/Shader/ShaderLanguageHlsl.h" #include "Direct3D9Renderer/Shader/ProgramHlsl.h" #include "Direct3D9Renderer/Shader/VertexShaderHlsl.h" #include "Direct3D9Renderer/Shader/FragmentShaderHlsl.h" #include "Direct3D9Renderer/Direct3D9Renderer.h" #include "Direct3D9Renderer/Direct3D9RuntimeLinking.h" #include <Renderer/ILog.h> #include <Renderer/IAllocator.h> //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace Direct3D9Renderer { //[-------------------------------------------------------] //[ Public definitions ] //[-------------------------------------------------------] const char* ShaderLanguageHlsl::NAME = "HLSL"; //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] ShaderLanguageHlsl::ShaderLanguageHlsl(Direct3D9Renderer& direct3D9Renderer) : IShaderLanguage(direct3D9Renderer) { // Nothing here } ShaderLanguageHlsl::~ShaderLanguageHlsl() { // Nothing here } ID3DXBuffer* ShaderLanguageHlsl::loadShaderFromSourcecode(const char* shaderModel, const char* sourceCode, const char* entryPoint, ID3DXConstantTable** d3dXConstantTable) const { // TODO(co) Error handling // Get compile flags UINT compileFlags = D3DXSHADER_IEEE_STRICTNESS; switch (getOptimizationLevel()) { case OptimizationLevel::Debug: compileFlags |= D3DXSHADER_DEBUG; compileFlags |= D3DXSHADER_SKIPOPTIMIZATION; break; case OptimizationLevel::None: compileFlags |= D3DXSHADER_SKIPVALIDATION; compileFlags |= D3DXSHADER_SKIPOPTIMIZATION; break; case OptimizationLevel::Low: compileFlags |= D3DXSHADER_SKIPVALIDATION; compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL0; break; case OptimizationLevel::Medium: compileFlags |= D3DXSHADER_SKIPVALIDATION; compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1; break; case OptimizationLevel::High: compileFlags |= D3DXSHADER_SKIPVALIDATION; compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL2; break; case OptimizationLevel::Ultra: compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL3; break; } ID3DXBuffer* d3dXBuffer = nullptr; ID3DXBuffer* d3dXBufferErrorMessages = nullptr; if (D3D_OK != D3DXCompileShader(sourceCode, static_cast<UINT>(strlen(sourceCode)), nullptr, nullptr, entryPoint ? entryPoint : "main", shaderModel, compileFlags, &d3dXBuffer, &d3dXBufferErrorMessages, d3dXConstantTable)) { if (static_cast<Direct3D9Renderer&>(getRenderer()).getContext().getLog().print(Renderer::ILog::Type::CRITICAL, sourceCode, __FILE__, static_cast<uint32_t>(__LINE__), static_cast<char*>(d3dXBufferErrorMessages->GetBufferPointer()))) { DEBUG_BREAK; } d3dXBufferErrorMessages->Release(); } // Done return d3dXBuffer; } //[-------------------------------------------------------] //[ Public virtual Renderer::IShaderLanguage methods ] //[-------------------------------------------------------] const char* ShaderLanguageHlsl::getShaderLanguageName() const { return NAME; } Renderer::IVertexShader* ShaderLanguageHlsl::createVertexShaderFromBytecode(const Renderer::VertexAttributes&, const Renderer::ShaderBytecode& shaderBytecode) { // There's no need to check for "Renderer::Capabilities::vertexShader", we know there's vertex shader support return RENDERER_NEW(getRenderer().getContext(), VertexShaderHlsl)(static_cast<Direct3D9Renderer&>(getRenderer()), shaderBytecode); } Renderer::IVertexShader* ShaderLanguageHlsl::createVertexShaderFromSourceCode(const Renderer::VertexAttributes&, const Renderer::ShaderSourceCode& shaderSourceCode, Renderer::ShaderBytecode* shaderBytecode) { // There's no need to check for "Renderer::Capabilities::vertexShader", we know there's vertex shader support return RENDERER_NEW(getRenderer().getContext(), VertexShaderHlsl)(static_cast<Direct3D9Renderer&>(getRenderer()), shaderSourceCode.sourceCode, shaderBytecode); } Renderer::ITessellationControlShader* ShaderLanguageHlsl::createTessellationControlShaderFromBytecode(const Renderer::ShaderBytecode&) { // Error! Direct3D 9 has no tessellation control shader support. return nullptr; } Renderer::ITessellationControlShader* ShaderLanguageHlsl::createTessellationControlShaderFromSourceCode(const Renderer::ShaderSourceCode&, Renderer::ShaderBytecode*) { // Error! Direct3D 9 has no tessellation control shader support. return nullptr; } Renderer::ITessellationEvaluationShader* ShaderLanguageHlsl::createTessellationEvaluationShaderFromBytecode(const Renderer::ShaderBytecode&) { // Error! Direct3D 9 has no tessellation evaluation shader support. return nullptr; } Renderer::ITessellationEvaluationShader* ShaderLanguageHlsl::createTessellationEvaluationShaderFromSourceCode(const Renderer::ShaderSourceCode&, Renderer::ShaderBytecode*) { // Error! Direct3D 9 has no tessellation evaluation shader support. return nullptr; } Renderer::IGeometryShader* ShaderLanguageHlsl::createGeometryShaderFromBytecode(const Renderer::ShaderBytecode&, Renderer::GsInputPrimitiveTopology, Renderer::GsOutputPrimitiveTopology, uint32_t) { // Error! Direct3D 9 has no geometry shader support. return nullptr; } Renderer::IGeometryShader* ShaderLanguageHlsl::createGeometryShaderFromSourceCode(const Renderer::ShaderSourceCode&, Renderer::GsInputPrimitiveTopology, Renderer::GsOutputPrimitiveTopology, uint32_t, Renderer::ShaderBytecode*) { // Error! Direct3D 9 has no geometry shader support. return nullptr; } Renderer::IFragmentShader* ShaderLanguageHlsl::createFragmentShaderFromBytecode(const Renderer::ShaderBytecode& shaderBytecode) { // There's no need to check for "Renderer::Capabilities::fragmentShader", we know there's fragment shader support return RENDERER_NEW(getRenderer().getContext(), FragmentShaderHlsl)(static_cast<Direct3D9Renderer&>(getRenderer()), shaderBytecode); } Renderer::IFragmentShader* ShaderLanguageHlsl::createFragmentShaderFromSourceCode(const Renderer::ShaderSourceCode& shaderSourceCode, Renderer::ShaderBytecode* shaderBytecode) { // There's no need to check for "Renderer::Capabilities::fragmentShader", we know there's fragment shader support return RENDERER_NEW(getRenderer().getContext(), FragmentShaderHlsl)(static_cast<Direct3D9Renderer&>(getRenderer()), shaderSourceCode.sourceCode, shaderBytecode); } Renderer::IProgram* ShaderLanguageHlsl::createProgram(const Renderer::IRootSignature&, const Renderer::VertexAttributes&, Renderer::IVertexShader* vertexShader, Renderer::ITessellationControlShader* tessellationControlShader, Renderer::ITessellationEvaluationShader* tessellationEvaluationShader, Renderer::IGeometryShader* geometryShader, Renderer::IFragmentShader* fragmentShader) { // A shader can be a null pointer, but if it's not the shader and program language must match! // -> Optimization: Comparing the shader language name by directly comparing the pointer address of // the name is safe because we know that we always reference to one and the same name address // TODO(co) Add security check: Is the given resource one of the currently used renderer? if (nullptr != vertexShader && vertexShader->getShaderLanguageName() != NAME) { // Error! Vertex shader language mismatch! } else if (nullptr != tessellationControlShader) { // Error! Direct3D 9 has no tessellation control shader support. } else if (nullptr != tessellationEvaluationShader) { // Error! Direct3D 9 has no tessellation evaluation shader support. } else if (nullptr != geometryShader) { // Error! Direct3D 9 has no geometry shader support. } else if (nullptr != fragmentShader && fragmentShader->getShaderLanguageName() != NAME) { // Error! Fragment shader language mismatch! } else { // Create the program return RENDERER_NEW(getRenderer().getContext(), ProgramHlsl)(static_cast<Direct3D9Renderer&>(getRenderer()), static_cast<VertexShaderHlsl*>(vertexShader), static_cast<FragmentShaderHlsl*>(fragmentShader)); } // Error! Shader language mismatch! // -> Ensure a correct reference counter behaviour, even in the situation of an error if (nullptr != vertexShader) { vertexShader->addReference(); vertexShader->releaseReference(); } if (nullptr != fragmentShader) { fragmentShader->addReference(); fragmentShader->releaseReference(); } // Error! return nullptr; } //[-------------------------------------------------------] //[ Protected virtual Renderer::RefCount methods ] //[-------------------------------------------------------] void ShaderLanguageHlsl::selfDestruct() { RENDERER_DELETE(getRenderer().getContext(), ShaderLanguageHlsl, this); } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // Direct3D9Renderer
#include "Login.h" boost::property_tree::ptree Login::execute(std::shared_ptr<Controller> controller) { return controller->loginUser(commandParams); } Login::Login(boost::property_tree::ptree &params) : BaseCommand("Login") { commandParams = params; }
#include <iostream> using namespace std; //Cautare binara int main() { int x,n,st,dr,m,i,v[10]; cout<<"n="; cin>>n; cout<<"x="; cin>>x; cout<<"Sirul va fi dat in ordine crescatoare!"<<endl; for(i=0; i<n; i++) { cout<<"v["<<i<<"]="; cin>>v[i]; } st=0; dr=n+1; m=(st+dr)/2; while(dr-st>1) { if(v[m]==x) { cout<<x<<" se regaseste in sir"; return 0; } if(v[m]<=x) st=m; else dr=m-1; m=(st+dr)/2; } cout<<x<<" nu se regaseste in sir"; return 0; }
/* * Ball.h * * Created on: Oct 24, 2013 * Author: ilansh */ #ifndef BALL_H_ #define BALL_H_ #ifdef __APPLE__ #include <OpenGL/OpenGL.h> #else #include <GL/gl.h> #endif #include <glm/glm.hpp> #define MIN_COLOR 0.7 class Model; struct Ball { Ball(int xPos, int yPos, const Model* model); void update(); //The color of the ball glm::vec3 _color; //The radius of the ball GLfloat _radius; GLfloat _initialRadius; void setRadius(float radius); static const GLfloat DEFAULT_RAD = 30; //The position of the ball glm::vec2 _pos; //Moving direction of the ball (velocity) glm::vec2 _dir; //The model const Model* _model; }; #endif /* BALL_H_ */
#include "statement.h" #include "visitor.h" Statement::Statement() {} Statement::~Statement() {} Assignment_statement::Assignment_statement(std::string _id, Expression* _expr) : id(_id), expr(_expr) { posx = NULL; posy = NULL; } Assignment_statement::Assignment_statement(std::string _id, Expression* _posx, Expression* _expr) : id(_id), expr(_expr) { posx = _posx; posy = NULL; } Assignment_statement::Assignment_statement(std::string _id, Expression* _posx, Expression* _posy, Expression* _expr) : id(_id), expr(_expr) { posx = _posx; posy = _posy; } void Assignment_statement::Accept(AbstractDispatcher& dispatcher) { dispatcher.Dispatch(*this); } Assignment_statement::~Assignment_statement() { if (posx != NULL) delete posx; if (posy != NULL) delete posy; } Return_statement::Return_statement(Expression* _expr) : expr(_expr) {} void Return_statement::Accept(AbstractDispatcher& dispatcher) { dispatcher.Dispatch(*this); } Return_statement::~Return_statement() { delete expr; }
#include "f3lib/assets/model/Skeleton.h" using namespace f3; Skeleton::Skeleton() { } Skeleton::~Skeleton() { } void Skeleton::initBoneTransforms(std::vector<types::Matrix>& boneTransforms) { boneTransforms.resize(_bones.size()); for (unsigned int i = 0; i < boneTransforms.size(); ++i) { boneTransforms[i] = types::Matrix::Identity; } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <quic/logging/QLoggerTypes.h> #include <quic/QuicException.h> #include <quic/logging/QLoggerConstants.h> namespace quic { folly::dynamic PaddingFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::PADDING); d["num_frames"] = numFrames; return d; } folly::dynamic NewTokenFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::NEW_TOKEN); d["token"] = token; return d; } folly::dynamic RstStreamFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::RST_STREAM); d["stream_id"] = streamId; d["error_code"] = errorCode; d["offset"] = offset; return d; } folly::dynamic ConnectionCloseFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); auto isTransportErrorCode = errorCode.asTransportErrorCode(); auto isApplicationErrorCode = errorCode.asApplicationErrorCode(); auto isLocalErrorCode = errorCode.asLocalErrorCode(); if (isTransportErrorCode || isLocalErrorCode) { d["frame_type"] = toQlogString(FrameType::CONNECTION_CLOSE); } else if (isApplicationErrorCode) { d["frame_type"] = toQlogString(FrameType::CONNECTION_CLOSE_APP_ERR); } d["error_code"] = toString(errorCode); d["reason_phrase"] = reasonPhrase; d["closing_frame_type"] = toString(closingFrameType); return d; } folly::dynamic MaxDataFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::MAX_DATA); d["maximum_data"] = maximumData; return d; } folly::dynamic MaxStreamDataFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::MAX_STREAM_DATA); d["stream_id"] = streamId; d["maximum_data"] = maximumData; return d; } folly::dynamic MaxStreamsFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); FrameType type; if (isForBidirectional) { type = FrameType::MAX_STREAMS_BIDI; } else { type = FrameType::MAX_STREAMS_UNI; } d["frame_type"] = toString(type); d["max_streams"] = maxStreams; return d; } folly::dynamic StreamsBlockedFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); FrameType type; if (isForBidirectional) { type = FrameType::STREAMS_BLOCKED_BIDI; } else { type = FrameType::STREAMS_BLOCKED_UNI; } d["frame_type"] = toString(type); d["stream_limit"] = streamLimit; return d; } folly::dynamic PingFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::PING); return d; } folly::dynamic DataBlockedFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::DATA_BLOCKED); d["data_limit"] = dataLimit; return d; } folly::dynamic KnobFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::KNOB); d["knob_space"] = knobSpace; d["knob_id"] = knobId; d["knob_blob_len"] = knobBlobLen; return d; } folly::dynamic AckFrequencyFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::ACK_FREQUENCY); d["sequence_number"] = sequenceNumber; d["packet_tolerance"] = packetTolerance; d["update_max_ack_delay"] = updateMaxAckDelay; d["reorder_threshold"] = reorderThreshold; return d; } folly::dynamic ImmediateAckFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::IMMEDIATE_ACK); return d; } folly::dynamic StreamDataBlockedFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::STREAM_DATA_BLOCKED); d["stream_id"] = streamId; d["data_limit"] = dataLimit; return d; } folly::dynamic StreamFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["offset"] = offset; d["length"] = len; d["fin"] = fin; d["stream_id"] = folly::to<std::string>(streamId); d["frame_type"] = toQlogString(FrameType::STREAM); return d; } folly::dynamic DatagramFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::DATAGRAM); d["length"] = len; return d; } folly::dynamic CryptoFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::CRYPTO_FRAME); d["offset"] = offset; d["len"] = len; return d; } folly::dynamic StopSendingFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::STOP_SENDING); d["stream_id"] = streamId; d["error_code"] = errorCode; return d; } folly::dynamic PathChallengeFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::PATH_CHALLENGE); d["path_data"] = pathData; return d; } folly::dynamic PathResponseFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::PATH_RESPONSE); d["path_data"] = pathData; return d; } folly::dynamic NewConnectionIdFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::NEW_CONNECTION_ID); d["sequence"] = sequence; folly::dynamic dToken = folly::dynamic::array(); for (const auto& a : token) { dToken.push_back(a); } d["token"] = dToken; return d; } folly::dynamic RetireConnectionIdFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::RETIRE_CONNECTION_ID); d["sequence"] = sequence; return d; } folly::dynamic ReadAckFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); folly::dynamic ackRangeDynamic = folly::dynamic::array(); folly::dynamic recvdPacketsTimestampRangesDynamic = folly::dynamic::array(); for (const auto& b : ackBlocks) { ackRangeDynamic.push_back( folly::dynamic::array(b.startPacket, b.endPacket)); } d["acked_ranges"] = ackRangeDynamic; d["frame_type"] = toQlogString(frameType); if (frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { if (maybeLatestRecvdPacketTime.has_value()) { d["latest_recvd_packet_time"] = maybeLatestRecvdPacketTime.value().count(); } if (maybeLatestRecvdPacketNum.has_value()) { d["latest_recvd_packet_num"] = maybeLatestRecvdPacketNum.value(); } for (auto it = recvdPacketsTimestampRanges.cbegin(); it != recvdPacketsTimestampRanges.cend(); ++it) { folly::dynamic currentRxTimestampRange = folly::dynamic::object(); currentRxTimestampRange["gap"] = it->gap; currentRxTimestampRange["timestamp_delta_count"] = it->timestamp_delta_count; currentRxTimestampRange["deltas"] = folly::dynamic::array(it->deltas.begin(), it->deltas.end()); recvdPacketsTimestampRangesDynamic.push_back(currentRxTimestampRange); } d["timestamp_ranges"] = recvdPacketsTimestampRangesDynamic; } d["ack_delay"] = ackDelay.count(); return d; } folly::dynamic WriteAckFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); folly::dynamic ackRangeDynamic = folly::dynamic::array(); folly::dynamic recvdPacketsTimestampRangesDynamic = folly::dynamic::array(); for (auto it = ackBlocks.cbegin(); it != ackBlocks.cend(); ++it) { ackRangeDynamic.push_back(folly::dynamic::array(it->start, it->end)); } d["acked_ranges"] = ackRangeDynamic; d["frame_type"] = toQlogString(frameType); if (frameType == FrameType::ACK_RECEIVE_TIMESTAMPS) { if (maybeLatestRecvdPacketTime.has_value()) { d["latest_recvd_packet_time"] = maybeLatestRecvdPacketTime.value().count(); } if (maybeLatestRecvdPacketNum.has_value()) { d["latest_recvd_packet_num"] = maybeLatestRecvdPacketNum.value(); } for (auto it = recvdPacketsTimestampRanges.cbegin(); it != recvdPacketsTimestampRanges.cend(); ++it) { folly::dynamic currentRxTimestampRange = folly::dynamic::object(); currentRxTimestampRange["gap"] = it->gap; currentRxTimestampRange["timestamp_delta_count"] = it->timestamp_delta_count; currentRxTimestampRange["deltas"] = folly::dynamic::array(it->deltas.begin(), it->deltas.end()); recvdPacketsTimestampRangesDynamic.push_back(currentRxTimestampRange); } d["timestamp_ranges"] = recvdPacketsTimestampRangesDynamic; } d["ack_delay"] = ackDelay.count(); return d; } folly::dynamic ReadNewTokenFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::NEW_TOKEN); return d; } folly::dynamic HandshakeDoneFrameLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d["frame_type"] = toQlogString(FrameType::HANDSHAKE_DONE); return d; } folly::dynamic VersionNegotiationLog::toDynamic() const { folly::dynamic d = folly::dynamic::object(); d = folly::dynamic::array(); for (const auto& v : versions) { d.push_back(toString(v)); } return d; } folly::dynamic QLogPacketEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["header"] = folly::dynamic::object("packet_size", packetSize); // A Retry packet does not include a packet number. if (packetType != toString(LongHeader::Types::Retry)) { data["header"]["packet_number"] = packetNum; data["frames"] = folly::dynamic::array(); for (const auto& frame : frames) { data["frames"].push_back(frame->toDynamic()); } } data["packet_type"] = packetType; d.push_back(std::move(data)); return d; } folly::dynamic QLogVersionNegotiationEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["versions"] = versionLog->toDynamic(); data["header"] = folly::dynamic::object("packet_size", packetSize); data["packet_type"] = packetType; d.push_back(std::move(data)); return d; } folly::dynamic QLogRetryEvent::toDynamic() const { folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["header"] = folly::dynamic::object("packet_size", packetSize); data["packet_type"] = packetType; data["token_size"] = tokenSize; d.push_back(std::move(data)); return d; } QLogConnectionCloseEvent::QLogConnectionCloseEvent( std::string errorIn, std::string reasonIn, bool drainConnectionIn, bool sendCloseImmediatelyIn, std::chrono::microseconds refTimeIn) : error{std::move(errorIn)}, reason{std::move(reasonIn)}, drainConnection{drainConnectionIn}, sendCloseImmediately{sendCloseImmediatelyIn} { eventType = QLogEventType::ConnectionClose; refTime = refTimeIn; } folly::dynamic QLogConnectionCloseEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "connectivity", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["error"] = error; data["reason"] = reason; data["drain_connection"] = drainConnection; data["send_close_immediately"] = sendCloseImmediately; d.push_back(std::move(data)); return d; } QLogTransportSummaryEvent::QLogTransportSummaryEvent( uint64_t totalBytesSentIn, uint64_t totalBytesRecvdIn, uint64_t sumCurWriteOffsetIn, uint64_t sumMaxObservedOffsetIn, uint64_t sumCurStreamBufferLenIn, uint64_t totalBytesRetransmittedIn, uint64_t totalStreamBytesClonedIn, uint64_t totalBytesClonedIn, uint64_t totalCryptoDataWrittenIn, uint64_t totalCryptoDataRecvdIn, uint64_t currentWritableBytesIn, uint64_t currentConnFlowControlIn, uint64_t totalPacketsSpuriouslyMarkedLost, uint64_t finalPacketLossReorderingThreshold, uint64_t finalPacketLossTimeReorderingThreshDividend, bool usedZeroRttIn, QuicVersion quicVersionIn, uint64_t dsrPacketCountIn, std::chrono::microseconds refTimeIn) : totalBytesSent{totalBytesSentIn}, totalBytesRecvd{totalBytesRecvdIn}, sumCurWriteOffset{sumCurWriteOffsetIn}, sumMaxObservedOffset{sumMaxObservedOffsetIn}, sumCurStreamBufferLen{sumCurStreamBufferLenIn}, totalBytesRetransmitted{totalBytesRetransmittedIn}, totalStreamBytesCloned{totalStreamBytesClonedIn}, totalBytesCloned{totalBytesClonedIn}, totalCryptoDataWritten{totalCryptoDataWrittenIn}, totalCryptoDataRecvd{totalCryptoDataRecvdIn}, currentWritableBytes{currentWritableBytesIn}, currentConnFlowControl{currentConnFlowControlIn}, totalPacketsSpuriouslyMarkedLost{totalPacketsSpuriouslyMarkedLost}, finalPacketLossReorderingThreshold{finalPacketLossReorderingThreshold}, finalPacketLossTimeReorderingThreshDividend{ finalPacketLossTimeReorderingThreshDividend}, usedZeroRtt{usedZeroRttIn}, quicVersion{quicVersionIn}, dsrPacketCount{dsrPacketCountIn} { eventType = QLogEventType::TransportSummary; refTime = refTimeIn; } folly::dynamic QLogTransportSummaryEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["total_bytes_sent"] = totalBytesSent; data["total_bytes_recvd"] = totalBytesRecvd; data["sum_cur_write_offset"] = sumCurWriteOffset; data["sum_max_observed_offset"] = sumMaxObservedOffset; data["sum_cur_stream_buffer_len"] = sumCurStreamBufferLen; data["total_bytes_retransmitted"] = totalBytesRetransmitted; data["total_stream_bytes_cloned"] = totalStreamBytesCloned; data["total_bytes_cloned"] = totalBytesCloned; data["total_crypto_data_written"] = totalCryptoDataWritten; data["total_crypto_data_recvd"] = totalCryptoDataRecvd; data["current_writable_bytes"] = currentWritableBytes; data["current_conn_flow_control"] = currentConnFlowControl; data["total_packets_spuriously_marked_lost"] = totalPacketsSpuriouslyMarkedLost; data["final_packet_loss_reordering_threshold"] = finalPacketLossReorderingThreshold; data["final_packet_loss_time_reordering_threshold_dividend"] = finalPacketLossTimeReorderingThreshDividend; data["used_zero_rtt"] = usedZeroRtt; data["quic_version"] = static_cast<std::underlying_type<decltype(quicVersion)>::type>( quicVersion); data["dsr_packet_count"] = dsrPacketCount; d.push_back(std::move(data)); return d; } QLogCongestionMetricUpdateEvent::QLogCongestionMetricUpdateEvent( uint64_t bytesInFlightIn, uint64_t currentCwndIn, std::string congestionEventIn, std::string stateIn, std::string recoveryStateIn, std::chrono::microseconds refTimeIn) : bytesInFlight{bytesInFlightIn}, currentCwnd{currentCwndIn}, congestionEvent{std::move(congestionEventIn)}, state{std::move(stateIn)}, recoveryState{std::move(recoveryStateIn)} { eventType = QLogEventType::CongestionMetricUpdate; refTime = refTimeIn; } folly::dynamic QLogCongestionMetricUpdateEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "metric_update", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["bytes_in_flight"] = bytesInFlight; data["current_cwnd"] = currentCwnd; data["congestion_event"] = congestionEvent; data["state"] = state; data["recovery_state"] = recoveryState; d.push_back(std::move(data)); return d; } QLogAppLimitedUpdateEvent::QLogAppLimitedUpdateEvent( bool limitedIn, std::chrono::microseconds refTimeIn) : limited(limitedIn) { eventType = QLogEventType::AppLimitedUpdate; refTime = refTimeIn; } folly::dynamic QLogAppLimitedUpdateEvent::toDynamic() const { folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "APP_LIMITED_UPDATE", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["app_limited"] = limited ? kAppLimited : kAppUnlimited; d.push_back(std::move(data)); return d; } QLogBandwidthEstUpdateEvent::QLogBandwidthEstUpdateEvent( uint64_t bytesIn, std::chrono::microseconds intervalIn, std::chrono::microseconds refTimeIn) : bytes(bytesIn), interval(intervalIn) { refTime = refTimeIn; eventType = QLogEventType::BandwidthEstUpdate; } folly::dynamic QLogBandwidthEstUpdateEvent::toDynamic() const { folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "BANDIWDTH_EST_UPDATE", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["bandwidth_bytes"] = bytes; data["bandwidth_interval"] = interval.count(); d.push_back(std::move(data)); return d; } QLogPacingMetricUpdateEvent::QLogPacingMetricUpdateEvent( uint64_t pacingBurstSizeIn, std::chrono::microseconds pacingIntervalIn, std::chrono::microseconds refTimeIn) : pacingBurstSize{pacingBurstSizeIn}, pacingInterval{pacingIntervalIn} { eventType = QLogEventType::PacingMetricUpdate; refTime = refTimeIn; } folly::dynamic QLogPacingMetricUpdateEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "metric_update", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["pacing_burst_size"] = pacingBurstSize; data["pacing_interval"] = pacingInterval.count(); d.push_back(std::move(data)); return d; } QLogPacingObservationEvent::QLogPacingObservationEvent( std::string actualIn, std::string expectIn, std::string conclusionIn, std::chrono::microseconds refTimeIn) : actual(std::move(actualIn)), expect(std::move(expectIn)), conclusion(std::move(conclusionIn)) { eventType = QLogEventType::PacingObservation; refTime = refTimeIn; } // TODO: Sad. I wanted moved all the string into the dynamic but this function // is const. I think we should make all the toDynamic rvalue qualified since // users are not supposed to use them after toDynamic() is called. folly::dynamic QLogPacingObservationEvent::toDynamic() const { folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "metric_update", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["actual_pacing_rate"] = actual; data["expect_pacing_rate"] = expect; data["conclusion"] = conclusion; d.push_back(std::move(data)); return d; } QLogAppIdleUpdateEvent::QLogAppIdleUpdateEvent( std::string idleEventIn, bool idleIn, std::chrono::microseconds refTimeIn) : idleEvent{std::move(idleEventIn)}, idle{idleIn} { eventType = QLogEventType::AppIdleUpdate; refTime = refTimeIn; } folly::dynamic QLogAppIdleUpdateEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "idle_update", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["idle_event"] = idleEvent; data["idle"] = idle; d.push_back(std::move(data)); return d; } QLogPacketDropEvent::QLogPacketDropEvent( size_t packetSizeIn, std::string dropReasonIn, std::chrono::microseconds refTimeIn) : packetSize{packetSizeIn}, dropReason{std::move(dropReasonIn)} { eventType = QLogEventType::PacketDrop; refTime = refTimeIn; } folly::dynamic QLogPacketDropEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "loss", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["packet_size"] = packetSize; data["drop_reason"] = dropReason; d.push_back(std::move(data)); return d; } // namespace quic QLogDatagramReceivedEvent::QLogDatagramReceivedEvent( uint64_t dataLen, std::chrono::microseconds refTimeIn) : dataLen{dataLen} { eventType = QLogEventType::DatagramReceived; refTime = refTimeIn; } folly::dynamic QLogDatagramReceivedEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["data_len"] = dataLen; d.push_back(std::move(data)); return d; } QLogLossAlarmEvent::QLogLossAlarmEvent( PacketNum largestSentIn, uint64_t alarmCountIn, uint64_t outstandingPacketsIn, std::string typeIn, std::chrono::microseconds refTimeIn) : largestSent{largestSentIn}, alarmCount{alarmCountIn}, outstandingPackets{outstandingPacketsIn}, type{std::move(typeIn)} { eventType = QLogEventType::LossAlarm; refTime = refTimeIn; } folly::dynamic QLogLossAlarmEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "loss", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["largest_sent"] = largestSent; data["alarm_count"] = alarmCount; data["outstanding_packets"] = outstandingPackets; data["type"] = type; d.push_back(std::move(data)); return d; } QLogPacketsLostEvent::QLogPacketsLostEvent( PacketNum largestLostPacketNumIn, uint64_t lostBytesIn, uint64_t lostPacketsIn, std::chrono::microseconds refTimeIn) : largestLostPacketNum{largestLostPacketNumIn}, lostBytes{lostBytesIn}, lostPackets{lostPacketsIn} { eventType = QLogEventType::PacketsLost; refTime = refTimeIn; } folly::dynamic QLogPacketsLostEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "loss", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["largest_lost_packet_num"] = largestLostPacketNum; data["lost_bytes"] = lostBytes; data["lost_packets"] = lostPackets; d.push_back(std::move(data)); return d; } QLogTransportStateUpdateEvent::QLogTransportStateUpdateEvent( std::string updateIn, std::chrono::microseconds refTimeIn) : update{std::move(updateIn)} { eventType = QLogEventType::TransportStateUpdate; refTime = refTimeIn; } folly::dynamic QLogTransportStateUpdateEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["update"] = update; d.push_back(std::move(data)); return d; } QLogPacketBufferedEvent::QLogPacketBufferedEvent( ProtectionType protectionTypeIn, uint64_t packetSizeIn, std::chrono::microseconds refTimeIn) : protectionType{protectionTypeIn}, packetSize{packetSizeIn} { eventType = QLogEventType::PacketBuffered; refTime = refTimeIn; } folly::dynamic QLogPacketBufferedEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["protection_type"] = toString(protectionType); data["packet_size"] = packetSize; d.push_back(std::move(data)); return d; } QLogPacketAckEvent::QLogPacketAckEvent( PacketNumberSpace packetNumSpaceIn, PacketNum packetNumIn, std::chrono::microseconds refTimeIn) : packetNumSpace{packetNumSpaceIn}, packetNum{packetNumIn} { eventType = QLogEventType::PacketAck; refTime = refTimeIn; } folly::dynamic QLogPacketAckEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["packet_num_space"] = folly::to<std::string>(packetNumSpace); data["packet_num"] = packetNum; d.push_back(std::move(data)); return d; } QLogMetricUpdateEvent::QLogMetricUpdateEvent( std::chrono::microseconds latestRttIn, std::chrono::microseconds mrttIn, std::chrono::microseconds srttIn, std::chrono::microseconds ackDelayIn, std::chrono::microseconds refTimeIn) : latestRtt{latestRttIn}, mrtt{mrttIn}, srtt{srttIn}, ackDelay{ackDelayIn} { eventType = QLogEventType::MetricUpdate; refTime = refTimeIn; } folly::dynamic QLogMetricUpdateEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "recovery", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["latest_rtt"] = latestRtt.count(); data["min_rtt"] = mrtt.count(); data["smoothed_rtt"] = srtt.count(); data["ack_delay"] = ackDelay.count(); d.push_back(std::move(data)); return d; } QLogStreamStateUpdateEvent::QLogStreamStateUpdateEvent( StreamId idIn, std::string updateIn, folly::Optional<std::chrono::milliseconds> timeSinceStreamCreationIn, VantagePoint vantagePoint, std::chrono::microseconds refTimeIn) : id{idIn}, update{std::move(updateIn)}, timeSinceStreamCreation(std::move(timeSinceStreamCreationIn)), vantagePoint_(vantagePoint) { eventType = QLogEventType::StreamStateUpdate; refTime = refTimeIn; } folly::dynamic QLogStreamStateUpdateEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "HTTP3", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["id"] = id; data["update"] = update; if (timeSinceStreamCreation) { if (update == kOnEOM && vantagePoint_ == VantagePoint::Client) { data["ttlb"] = timeSinceStreamCreation->count(); } else if (update == kOnHeaders && vantagePoint_ == VantagePoint::Client) { data["ttfb"] = timeSinceStreamCreation->count(); } else { data["ms_since_creation"] = timeSinceStreamCreation->count(); } } d.push_back(std::move(data)); return d; } QLogConnectionMigrationEvent::QLogConnectionMigrationEvent( bool intentionalMigration, VantagePoint vantagePoint, std::chrono::microseconds refTimeIn) : intentionalMigration_{intentionalMigration}, vantagePoint_(vantagePoint) { eventType = QLogEventType::ConnectionMigration; refTime = refTimeIn; } folly::dynamic QLogConnectionMigrationEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["intentional"] = intentionalMigration_; if (vantagePoint_ == VantagePoint::Client) { data["type"] = "initiating"; } else { data["type"] = "accepting"; } d.push_back(std::move(data)); return d; } QLogPathValidationEvent::QLogPathValidationEvent( bool success, VantagePoint vantagePoint, std::chrono::microseconds refTimeIn) : success_{success}, vantagePoint_(vantagePoint) { eventType = QLogEventType::PathValidation; refTime = refTimeIn; } folly::dynamic QLogPathValidationEvent::toDynamic() const { // creating a folly::dynamic array to hold the information corresponding to // the event fields relative_time, category, event_type, trigger, data folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "transport", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["success"] = success_; if (vantagePoint_ == VantagePoint::Client) { data["vantagePoint"] = "client"; } else { data["vantagePoint"] = "server"; } d.push_back(std::move(data)); return d; } QLogPriorityUpdateEvent::QLogPriorityUpdateEvent( StreamId streamId, uint8_t urgency, bool incremental, std::chrono::microseconds refTimeIn) : streamId_(streamId), urgency_(urgency), incremental_(incremental) { eventType = QLogEventType::PriorityUpdate; refTime = refTimeIn; } folly::dynamic QLogPriorityUpdateEvent::toDynamic() const { folly::dynamic d = folly::dynamic::array( folly::to<std::string>(refTime.count()), "HTTP3", toString(eventType)); folly::dynamic data = folly::dynamic::object(); data["id"] = streamId_; data["urgency"] = urgency_; data["incremental"] = incremental_; d.push_back(std::move(data)); return d; } folly::StringPiece toString(QLogEventType type) { switch (type) { case QLogEventType::PacketSent: return "packet_sent"; case QLogEventType::PacketReceived: return "packet_received"; case QLogEventType::ConnectionClose: return "connection_close"; case QLogEventType::TransportSummary: return "transport_summary"; case QLogEventType::CongestionMetricUpdate: return "congestion_metric_update"; case QLogEventType::PacingMetricUpdate: return "pacing_metric_update"; case QLogEventType::AppIdleUpdate: return "app_idle_update"; case QLogEventType::PacketDrop: return "packet_drop"; case QLogEventType::DatagramReceived: return "datagram_received"; case QLogEventType::LossAlarm: return "loss_alarm"; case QLogEventType::PacketsLost: return "packets_lost"; case QLogEventType::TransportStateUpdate: return "transport_state_update"; case QLogEventType::PacketBuffered: return "packet_buffered"; case QLogEventType::PacketAck: return "packet_ack"; case QLogEventType::MetricUpdate: return "metric_update"; case QLogEventType::StreamStateUpdate: return "stream_state_update"; case QLogEventType::PacingObservation: return "pacing_observation"; case QLogEventType::AppLimitedUpdate: return "app_limited_update"; case QLogEventType::BandwidthEstUpdate: return "bandwidth_est_update"; case QLogEventType::ConnectionMigration: return "connection_migration"; case QLogEventType::PathValidation: return "path_validation"; case QLogEventType::PriorityUpdate: return "priority"; } folly::assume_unreachable(); } } // namespace quic
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- * * Copyright (C) 2011-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef OPPLUGINLIBRARY_H__ #define OPPLUGINLIBRARY_H__ #ifdef _PLUGIN_SUPPORT_ #include "modules/opdata/UniString.h" #include "modules/ns4plugins/src/plug-inc/npfunctions.h" /** * A platform interface for loading, probing and initializing libraries * conforming to the Netscape Plug-in API (NPAPI). * * If it manages to successfully load a plug-in library, the object should keep * the library loaded as long as it exists. On destruction, the object should * unload the library and release its resources. * * In a particular process, at most one instance of OpPluginLibrary will * exist at any time. */ class OpPluginLibrary { public: typedef NPNetscapeFuncs* BrowserFunctions; typedef NPPluginFuncs* PluginFunctions; /** * Unload the library and release any resources. */ virtual ~OpPluginLibrary() {} struct LibraryPath { UniString path; /**< Path to a plugin library */ OpComponentType type; /**< Component type to start for running this plugin. Can be used by the platform to specify e.g. different architectures */ }; /** * Enumerate the plug-in libraries available on the system. Filtering of * undesired libraries (e.g. applying security blacklists and * plugin_ignore.ini) may be done by this method or deferred until probing, * leaving them for OpPluginLibrary::Create() to reject by returning * OpStatus::ERR. * * @param[out] library_paths A list of library identifiers returned * to the caller. The identifiers must be valid arguments to Create(). * * @param suggested_paths A list of directories in which plugin libraries * may be found. The string is the return value of OpSystemInfo::GetPluginPathL() * invoked with the preference [User Prefs] "Plugin Path" as argument. The * preference setters are responsible for using a platform-appropriate separator * (e.g. colon on Unix-like platforms, semicolon on MS-Windows) between * directories in the list. This list is intended to augment platform * knowledge, not replace it. * * @return See OpStatus; OK on success. */ static OP_STATUS EnumerateLibraries(OtlList<LibraryPath>* library_paths, const UniString& suggested_paths); /** * Create a new OpPluginLibrary. * * The identifying argument is the path member of an OpPluginLibrary returned * by EnumerateLibraries(). This method will be called by a component of the * type specified by the corresponding type parameter. * * Before calling this method to instantiate a new OpPluginLibrary object, the * owning plug-in component will destroy any previously instantiated library, * such that the number of concurrent library instances in a process is less * than or equal to the number of plug-in components the platform is running * in said process. * * @param[out] library An OpPluginLibrary object on success, otherwise undefined. * @param[in] path The name of the library file to open, including path to the file. * * @return See OpStatus. * @retval OpStatus::OK on success. * @retval OpStatus::ERR if the library is unsuitable, such as when it is blacklisted * for compatibility or security reasons, or simply if it turns out not to be * a valid NPAPI plug-in library. * @retval OpStatus::ERR_NO_MEMORY on OOM. */ static OP_STATUS Create(OpPluginLibrary** library, const UniString& path); /** * Retrieve the plug-in library name. * * @param[out] name The name the plug-in represents itself as, or more * specifically, the string retrieved by * NPPVpluginNameString (e.g. "Shockwave Flash"). * * @return See OpStatus; OK on success. */ virtual OP_STATUS GetName(UniString* name) = 0; /** * Retrieve the plug-in library description as given by the plug-in library. * * @param[out] description The plug-in library description string, * retrieved by NPPVpluginDescriptionString. * * @return See OpStatus; OK on success. */ virtual OP_STATUS GetDescription(UniString* description) = 0; /** * Retrieve the plug-in library version. * * @param[out] version The plug-in library version string. * * @return See OpStatus; OK on success. */ virtual OP_STATUS GetVersion(UniString* version) = 0; /** * Check if the plug-in library is enabled. * * Browser users may go to about:plugins to see a detailed list of plug-in libraries * discovered. This page also allows libraries to be enabled or disabled, the latter * state preventing the browser from loading and using the library. If a specific * library should be listed but not be used unless explicitly enabled by the user, * an implementation may return false here. * * @return true if enabled, false otherwise. */ virtual bool GetEnabled() { return true; } /** * Return the list of content types handled by this plug-in library. * * The list was previously populated by a call to NP_GetMIMEDescription * during initialisation and contains all the MIME types the plug-in claims * to support. * * @param[out] content_types The list of content types supported by the plug-in library. * * @return See OpStatus. */ virtual OP_STATUS GetContentTypes(OtlList<UniString>* content_types) = 0; /** * Retrieve the file extensions associated with a library-defined content type. * * @param[out] extensions The list of extensions associated with this content type. * @param content_type The content type to retrieve file extensions for. * * @return See OpStatus; OK on success. */ virtual OP_STATUS GetExtensions(OtlList<UniString>* extensions, const UniString& content_type) = 0; /** * Retrieve a description of a content type. * * @param[out] description A content type description string. * @param content_type The content type to describe. * * @return See OpStatus; OK on success. */ virtual OP_STATUS GetContentTypeDescription(UniString* description, const UniString& content_type) = 0; /** * Load the library, if it's not already loaded. * * Platforms are encouraged to use the RAII idiom and perform load/unload * of the library in the initialiser/destructor. Whenever Load() is called, * simply return OpStatus::OK to indicate that the library is loaded. * * @return See OpStatus; OK if the library is loaded on return from this method. */ virtual OP_STATUS Load() = 0; /** * Call the NPAPI initializer function or functions, and retrieve the * plug-in library's entry points. The exact approach varies between platforms. * * Load() will be called before this method. * * @param plugin_funcs The table of plug-in library entry points to be filled by * the plug-in. * @param browser_funcs The browser entry points to be given to the plug-in library. * * @return The return value is the NPAPI return value of the first NPAPI function * that failed, or the NPError translation of the first significant error, * or NPERR_NO_ERROR on success. Before returning an error, all resources * allocated by this method must be released. Shutdown() will be called * precisely if Initialize() succeeds. */ virtual NPError Initialize(PluginFunctions plugin_funcs, const BrowserFunctions browser_funcs) = 0; /** * Call the NPAPI shutdown function (NP_Shutdown). */ virtual void Shutdown() = 0; }; #endif // defined(_PLUGIN_SUPPORT_) #endif // OPPLUGINLIBRARY_H__
#include "Multivector.h" #include <set> #include "MatlabEng.h" #include <algorithm> #include <iterator> namespace alg { class DelaunayVertex { public: DelaunayVertex() {} DelaunayVertex(const Multivector<double> &pt) : m_pt(pt) {} DelaunayVertex(const DelaunayVertex &V) : m_pt(V.m_pt), m_simplex(V.m_simplex) {} DelaunayVertex &operator=(const DelaunayVertex &V) { if (&V != this) { m_pt = V.m_pt; m_simplex = V.m_simplex; } return *this; } Multivector<double> m_pt; std::set<int> m_simplex; }; class DelaunaySimplex { public: DelaunaySimplex() { } DelaunaySimplex(std::vector<int> vtxIdx) { m_vertices = vtxIdx; } DelaunaySimplex(const DelaunaySimplex &T) { m_vertices = T.m_vertices; m_neighborTriangles = T.m_neighborTriangles; } DelaunaySimplex& operator=(const DelaunaySimplex &T) { if (this != &T) { m_vertices = T.m_vertices; m_neighborTriangles = T.m_neighborTriangles; } return *this; } bool isBorder()const { for (int i : m_neighborTriangles) if (i == -1) return true; return false; } int getNextNeighbor(const std::set<int>& _neighbor) const{ for (int index : m_neighborTriangles) if (_neighbor.find(index) != _neighbor.end()) return index; return -1; // não achou vizinho } std::vector<int> m_vertices; std::vector<int> m_neighborTriangles; }; class DelaunayTriangulation { public: DelaunayTriangulation() {} DelaunayTriangulation(Orthogonal<int> _ort) : m_metrica(_ort){ } friend DelaunayTriangulation generateDelaunayTriangulation2D_matlab(const std::vector<std::vector<double>>& matrix_point); inline Multivector<double> No() const { return (0.5*e(m_metrica.getSize() - 1) + e(m_metrica.getSize())); } inline Multivector<double> Nii() const{ return (1.0*e(m_metrica.getSize()) - e(m_metrica.getSize() - 1)); } Multivector<double> hiperesfera(int _indexSimplex) const{ Multivector<double> C = m_vertices[m_simplex[_indexSimplex].m_vertices[0]].m_pt; for (size_t i = 1; i < m_simplex[_indexSimplex].m_vertices.size(); i++) C = C^m_vertices[m_simplex[_indexSimplex].m_vertices[i]].m_pt; return C; } int selectInicialSimplex(const std::set<int>& _neighbors) const{ for (const auto& index : _neighbors) if (m_simplex[index].isBorder()) return index; return *_neighbors.begin(); } public: std::vector<DelaunayVertex> m_vertices; std::vector<DelaunaySimplex> m_simplex; Orthogonal<int> m_metrica; }; class Voronoi { public: Voronoi(Multivector<double> Nii) { m_map_id_simplex_pontoFinito[-1] = Nii; } std::map<int ,Multivector<double>> m_map_id_simplex_pontoFinito; std::vector<std::vector<int>> m_region; }; void calculateDelaunayMatlab2D(DelaunayTriangulation& dl, const int dim) { //calcular delaunay pelo matlab CMatlabEng matlab; matlab.Open(NULL); matlab.SetVisible(FALSE); // matlab mxArray *mxc; mxc = mxCreateDoubleMatrix(dim, dl.m_vertices.size(), mxREAL); double * ptrIn = (double *)mxGetPr(mxc); int i = 0; for (auto vertex : dl.m_vertices) { int j = 0; for (; j < dim; j++) { ptrIn[i*(dim)+j] = vertex.m_pt.getCoefBladeBase(j + 1); } i++; } matlab.PutVariable("T", mxc); matlab.EvalString("K = delaunayTriangulation(T');"); matlab.EvalString("K = K.ConnectivityList';"); matlab.EvalString("[dim1 dim2] = size(K);"); mxArray* dim1 = matlab.GetVariable("dim1"); double* a = (double *)mxGetData(dim1); mxArray* dim2 = matlab.GetVariable("dim2"); double* b = (double *)mxGetData(dim2); std::cout << "Qtd simplex" << (int)b[0] << std::endl; std::cout << "vertices" << (int)a[0] << std::endl; mxArray* convex_hull = matlab.GetVariable("K"); double * ptr = (double *)mxGetData(convex_hull); for (int i = 0; i < (int)b[0]; i++) { // para cada triângulo dl.m_simplex.push_back(DelaunaySimplex()); int indexTriang = dl.m_simplex.size() - 1; for (int j = 0; j < (int)a[0]; j++) { dl.m_simplex[indexTriang].m_vertices.push_back(ptr[i*(int)a[0] + j] - 1); dl.m_vertices[(ptr[i*(int)a[0] + j] - 1)].m_simplex.insert(indexTriang); } } mxDestroyArray(mxc); mxDestroyArray(convex_hull); mxDestroyArray(dim1); mxDestroyArray(dim2); } DelaunayTriangulation generateDelaunayTriangulation2D_matlab(const std::vector<std::vector<double>>& matrix_point) { if (matrix_point.empty()) return DelaunayTriangulation(); std::vector<int> metric_values; for (size_t i = 0; i < matrix_point[0].size(); i++) metric_values.push_back(1); metric_values.push_back(1); metric_values.push_back(-1); Orthogonal<int> metric(metric_values); DelaunayTriangulation dl(metric); const int qtdPoint = matrix_point.size(); const int dim = matrix_point[0].size(); for (size_t i = 0; i < matrix_point.size(); i++) { Multivector<double> P = dl.No(); double valueNii = 0.0; for (size_t j = 0; j < matrix_point[i].size(); j++) { P = P + e(j + 1)*matrix_point[i][j]; valueNii += ((matrix_point[i][j] * matrix_point[i][j])*0.5); } P = P + valueNii*dl.Nii(); dl.m_vertices.push_back(DelaunayVertex(P)); } calculateDelaunayMatlab2D(dl, dim); // calcular vizinhança for (size_t i = 0; i < dl.m_simplex.size(); i++) { DelaunaySimplex &T = dl.m_simplex[i]; for (size_t j = 0; j < T.m_vertices.size(); j++) { std::set<int> simplex_neighbor = dl.m_vertices[T.m_vertices[j]].m_simplex; for (size_t aux = 1; aux < T.m_vertices.size() - 1; aux++) { const DelaunayVertex &V2 = dl.m_vertices[T.m_vertices[(j + aux) % T.m_vertices.size()]]; // (j + aux ) mod qtd vertices , necessário para pecorrer o vetor de forma circular. std::vector<int> intersection; std::set_intersection(simplex_neighbor.begin(), simplex_neighbor.end(), V2.m_simplex.begin(), V2.m_simplex.end(), std::back_inserter(intersection)); simplex_neighbor.clear(); simplex_neighbor.insert(intersection.begin(), intersection.end()); } simplex_neighbor.erase(i); if (!simplex_neighbor.empty()) T.m_neighborTriangles.push_back(*(simplex_neighbor.begin())); else T.m_neighborTriangles.push_back(-1); // não possui vizinho } } return dl; } Voronoi generateVoronoi(const DelaunayTriangulation& _delaunay) { Voronoi v(_delaunay.Nii()); // blade direção //calcula o ponto finito, ou seja, o centro de todas as hiperesferas for (size_t i = 0; i < _delaunay.m_simplex.size(); i++){ const DelaunaySimplex &T = _delaunay.m_simplex[i]; Multivector<double> hiperEsfera = _delaunay.hiperesfera(i); Multivector<double> pontoFinito = -0.5*(GP(GP(hiperEsfera, _delaunay.Nii(), _delaunay.m_metrica), hiperEsfera, _delaunay.m_metrica)); Multivector<double> divisor = LCont(_delaunay.Nii(), hiperEsfera, _delaunay.m_metrica); Multivector<double> divisorFinal = GP(divisor, divisor, _delaunay.m_metrica); v.m_map_id_simplex_pontoFinito[i] = pontoFinito * (1.0 / divisorFinal.getCoefBladeBase(0)); } // para cada vertices referência montar o polígono do voronoi usando os pontos finitos já calculados for (size_t j = 0; j < _delaunay.m_vertices.size(); j++) { const DelaunayVertex& vertex = _delaunay.m_vertices[j]; std::set<int> neighbor = vertex.m_simplex; std::vector<int> region; int next_index = _delaunay.selectInicialSimplex(neighbor); region.push_back(next_index); neighbor.erase(next_index); while (!neighbor.empty()) { next_index = _delaunay.m_simplex[next_index].getNextNeighbor(neighbor); region.push_back(next_index); neighbor.erase(next_index); } v.m_region.push_back(region); } return v; } }
/* #include "timer.h" #include <QtCore> #include <QDebug> timer::Timer(QObject *parent) : QObject(parent) { timer = new QTimer(this); connect(timer.SIGNAL(timeout()).this,SLOT(slot())); // How long the timer is (ms) timer->start(1000); } void timer::slot() { qDebug() << "Timer executed"; } */
#include "image.h" #include <QFileInfo> #include <math.h> namespace { /*std::vector<std::vector<float>> kernel = {{1./256, 4./256, 6./256, 4./256, 1./256}, {4./256, 16./256, 24./256, 16./256, 4./256}, {6./256, 24./256, 36./256, 24./256, 6./256}, {4./256, 16./256, 24./256, 16./256, 4./256}, {1./256, 4./256, 6./256, 4./256, 1./256}};*/ std::vector<std::vector<float>> kernel = {{1./16, 1./8, 1./16}, {1./8, 1./4, 1./8}, {1./16, 1./8, 1./16}}; } Image::Image(const QString &filePath) { imagePyramid.push_back(QImage(filePath)); fileName = QFileInfo(filePath).fileName(); } QImage Image::getPyramidLayer(int layer) const { return imagePyramid[layer]; } float Image::getImageDiagonal() { const int height = imagePyramid.front().height(); const int width = imagePyramid.front().width(); return std::sqrt(height * height + width * width); } QSize Image::getSize() { return imagePyramid[0].size(); } QString Image::getName() { return fileName; } int Image::getLayersNumber() { return imagePyramid.size(); } void Image::addCustomPyramidLayer(float scaleFactor) { QImage newLayer(imagePyramid.back().width() / scaleFactor, imagePyramid.back().height() / scaleFactor, imagePyramid.back().format()); interpolateBilinear(imagePyramid.back(), 1.f/scaleFactor, newLayer); imagePyramid.push_back(newLayer); } void Image::interpolateBilinear(QImage &inImage, float scaleFactor, QImage &outImage) { for(int x = 0; x < outImage.width(); x++) for(int y = 0; y < outImage.height(); y++) { int px = (int)(x / scaleFactor); int py = (int)(y / scaleFactor); double fx1 = (double)x / (double)scaleFactor - (double)px; double fx2 = 1 - fx1; double fy1 = (double)y / (double)scaleFactor - (double)py; double fy2 = 1 - fy1; double w1 = fx2 * fy2; double w2 = fx1 * fy2; double w3 = fx2 * fy1; double w4 = fx1 * fy1; QRgb p1 = inImage.pixel(px, py); QRgb p2 = inImage.pixel(px + 1, py); QRgb p3 = inImage.pixel(px, py + 1); QRgb p4 = inImage.pixel(px + 1, py + 1); int red = w1 * qRed(p1) + w2 * qRed(p2) + w3 * qRed(p3) + w4 * qRed(p4); int green = w1 * qGreen(p1) + w2 * qGreen(p2) + w3 * qGreen(p3) + w4 * qGreen(p4); int blue = w1 * qBlue(p1) + w2 * qBlue(p2) + w3 * qBlue(p3) + w4 * qBlue(p4); outImage.setPixel(x, y, qRgb(red, green, blue)); } }
#include<bits/stdc++.h> using namespace std; typedef long long ll; //based on padovan sequence. vector<ll> dp(1000000,0); int main(){ ll d = 1000000007; dp[2]=1; dp[3]=1; for(ll i=4;i<=1000000;i++){ dp[i] = (dp[i-2] + dp[i-3])%d; } ll t; cin>>t; while(t--){ ll n; cin>>n; cout<<dp[n]<<"\n"; } return 0; }
#include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> #include "advantech_pci1714/Ping_received.h" int main(int argc, char **argv) { ros::init(argc, argv, "advantechDriver_node"); ros::NodeHandle n; ros::Rate loop_rate(10); while (ros::ok()) { /** * This is a message object. You stuff it with data, and then publish it. */ ROS_INFO("test"); ros::spinOnce(); loop_rate.sleep(); } return 0; }
#include<bits/stdc++.h> using namespace std; #define PI 3.1415926535897932 void addMatrix (int arrayA[2][2], int arrayB[2][2]) { int x=2; int y=2; for (int i=0;i<y;++i) { for (int j=0;j<x;++j) { arrayA[i][j]+=arrayB[i][j]; } } } void printMatrix(int array[2][2]) { for (int i=0;i<2;++i) { printf("%d %d\n",array[i][0],array[i][1]); } } int main(){ //sizeof(array) / sizeof(array[0]) /** int matrixA[2][2] = {{1, 2}, {3, 4}}; int matrixB[2][2] = {{5, 6}, {7, 8}}; **/ int matrixA[2][2] = {{1, 2}, {3, 4}}; int matrixB[2][2] = {{5, 6}, {7, 8}}; printMatrix(matrixA); printf(" + \n"); printMatrix(matrixB); printf(" = \n"); addMatrix(matrixA, matrixB); printMatrix(matrixA); return 0; }
#pragma once #include <iostream> using namespace std; class Employee { public: Employee(); virtual void init() = 0; virtual void calcSalary() = 0; virtual void disInfo() = 0; virtual void promote() = 0; virtual ~Employee(); protected: string _name; int _num; int _grade; float _salary; static int _startNum; };
#include <cppunit/extensions/HelperMacros.h> #include <Poco/Exception.h> #include "cppunit/BetterAssert.h" #include "model/OpMode.h" using namespace std; using namespace Poco; namespace BeeeOn { class OpModeTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(OpModeTest); CPPUNIT_TEST(testParse); CPPUNIT_TEST(testParseInvalid); CPPUNIT_TEST(testToString); CPPUNIT_TEST_SUITE_END(); public: void testParse(); void testParseInvalid(); void testToString(); }; CPPUNIT_TEST_SUITE_REGISTRATION(OpModeTest); void OpModeTest::testParse() { CPPUNIT_ASSERT_EQUAL( OpMode::TRY_ONCE, OpMode::parse("try_once").raw()); CPPUNIT_ASSERT_EQUAL( OpMode::TRY_HARDER, OpMode::parse("try_harder").raw()); CPPUNIT_ASSERT_EQUAL( OpMode::REPEAT_ON_FAIL, OpMode::parse("repeat_on_fail").raw()); } void OpModeTest::testParseInvalid() { CPPUNIT_ASSERT_THROW( OpMode::parse("something"), InvalidArgumentException); } void OpModeTest::testToString() { CPPUNIT_ASSERT_EQUAL( "try_once", OpMode(OpMode::TRY_ONCE).toString()); CPPUNIT_ASSERT_EQUAL( "try_harder", OpMode(OpMode::TRY_HARDER).toString()); CPPUNIT_ASSERT_EQUAL( "repeat_on_fail", OpMode(OpMode::REPEAT_ON_FAIL).toString()); } }
////////////////////////////////////////////////////////////////////// ///Copyright (C) 2011-2012 Benjamin Quach // //This file is part of the "Lost Horizons" video game demo // //"Lost Horizons" 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 _FADER_H_ #define _FADER_H_ #include "irrlicht.h" class CFader { public: CFader(irr::IrrlichtDevice *graphics) { this->graphics = graphics; time = graphics->getTimer()->getTime(); transition_alpha = 0; transition_time_start = -1; } ~CFader(); void update(irr::f32 speed, irr::f32 current_time,bool fadeout) { float difference = (current_time - transition_time_start)/1000; graphics->getVideoDriver()->draw2DRectangle(irr::video::SColor(transition_alpha,0,0,0), irr::core::rect<irr::s32>(0,0 ,graphics->getVideoDriver()->getScreenSize().Width, graphics->getVideoDriver()->getScreenSize().Height)); if(difference >= speed/1000) { if(fadeout==true) { if(transition_alpha<255) transition_alpha++; } else { if(transition_alpha>0) transition_alpha--; } transition_time_start = current_time; } } void drop() { delete this; } private: irr::IrrlichtDevice *graphics; int time; int transition_alpha; int transition_time_start; }; #endif
#include "TestCPU.h" #include <iostream> int main(int argc, char** argv) { using namespace test; memoryInterface *mem = new RAMImpl(10); cpu device(mem); CPUtestbench tester(&device); tester.storeReg(1, 654321); tester.constructInstruction(SW, 0, 1, 0x108); tester.run(); if (mem->readWord(0x108) == 654321) std::cout << argv[0] << " Pass" << std::endl; else std::cout << argv[0] << " Fail" << std::endl; delete mem; }