blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
927f645dd5e9aeb7eda457044dffb1f65f8fd448
2e519db027baba2cb7d15d6a90df740e16d827e0
/BullsAndCows/steps.cpp
b4644ec6973c3b2f1af1bb113ad74eeb7e582a6f
[]
no_license
DariaBudchan/eltech.2015.teamR
0f4f353fda06c97cf3f6c5f41b7442fdd6c7b4b7
f0d0f5f8b37fc209a2b80b5d86984bb0723163c2
refs/heads/master
2021-01-10T21:21:05.514942
2015-05-20T18:48:07
2015-05-20T18:48:07
30,929,441
0
0
null
null
null
null
UTF-8
C++
false
false
578
cpp
#include "steps.h" Steps::Steps(QWidget *parent) : QWidget(parent) { QVBoxLayout* l = new QVBoxLayout; l->setAlignment(Qt::AlignTop); setLayout(l); setMaximumSize(390,475); setMinimumSize(390,475); layout()->setMargin(5); layout()->setSpacing(3); //imagePathBack = ":res/Image/StepResult/stepsback.png"; } void Steps::addStep(int number, int bc) { layout()->addWidget(new StepResult(number, bc, this)); } Steps::~Steps() { } void Steps::paintEvent(QPaintEvent *pe) { QPainter p(this); p.drawPixmap(pe->rect(), imagePathBack); }
[ "daria.budchan@mail.ru" ]
daria.budchan@mail.ru
cc3eb0b69d251bd3ecc4a4dd3a66c34cb7ef12e9
5ef5a1c2476f3a6d5be209b94ba5e2dae79473c2
/DebugToolSavePanelAndMap/DebugToolSavePanelAndMap/LogTool.cpp
6e020b44ddbe787c15aced26ea20989e72d29620
[]
no_license
xautshuanglong/GithubForTaomee
ce7ab75e51a10af4c430ba0f7aea1943cdfd7a78
6ebc08b7b8ce3d5c19738735ffcc713cfb414299
refs/heads/master
2021-01-01T05:01:25.342234
2016-05-09T06:16:15
2016-05-09T06:16:15
56,964,357
0
0
null
null
null
null
UTF-8
C++
false
false
1,657
cpp
#include <iostream> #include "LogTool.h" LogTool::LogTool() { try { PropertyConfigurator::configure("..//config//log4cpp.ini"); } catch (ConfigureFailure& e) { } } LogTool* LogTool::getInstance() { if (m_pInstance == NULL) { m_pInstance = new LogTool(); } return m_pInstance; } void LogTool::info(const char* msg) { //Category& root = Category::getRoot(); Category& m_fileCategory = Category::getInstance("tempfile"); Category& m_rollingCategory = Category::getInstance("rolling"); //root.info(msg); m_fileCategory.info(msg); m_rollingCategory.info(msg); } void LogTool::info(std::string& msg) { //Category& root = Category::getRoot(); Category& m_fileCategory = Category::getInstance("tempfile"); Category& m_rollingCategory = Category::getInstance("rolling"); //root.info(msg); m_fileCategory.info(msg); m_rollingCategory.info(msg); } void LogTool::debug(const char* msg) { //Category::getRoot().debug(msg); Category::getInstance("tempfile").debug(msg); Category::getInstance("rolling").debug(msg); } void LogTool::debug(std::string& msg) { //Category::getRoot().debug(msg); Category::getInstance("tempfile").debug(msg); Category::getInstance("rolling").debug(msg); } void LogTool::error(const char* msg) { //Category::getRoot().error(msg); Category::getInstance("tempfile").error(msg); Category::getInstance("rolling").error(msg); } void LogTool::error(std::string& msg) { //Category::getRoot().error(msg); Category::getInstance("tempfile").error(msg); Category::getInstance("rolling").error(msg); } void LogTool::pushNDC(const std::string& msg) { NDC::push(msg); } void LogTool::popNDC() { NDC::pop(); }
[ "xjshuanglong@126.com" ]
xjshuanglong@126.com
1f3f5cf21a3dfb85e4ea544504f53f338af8c103
05d599a23b85dbe23ece42848090181c9e2a94cc
/main.cpp
a689471603dae082a436c06438985a1fa62c5a86
[]
no_license
ChrisNoissue/ttt
913d3e2be70b811eafb76529bbb1eafa8bae18eb
d2f04084c18f4e0e6e39c92398a3f112260c03a6
refs/heads/master
2020-03-07T17:04:37.075404
2018-04-01T06:10:10
2018-04-01T06:10:10
127,601,955
0
0
null
null
null
null
UTF-8
C++
false
false
3,643
cpp
/** PJC2 PROJEKT main.cpp Purpose: menu + gra kolko i krzyzyk @author Krzysztof Siwoń @version 0.9 24/10/16 */ #include <iostream> #include "curses.h" #include "Menu.h" #include "Game.h" int menu_choosing(Menu o_menuWin, Game o_gameWin, WINDOW *menu_window, WINDOW *game_window); int main(void) { WINDOW *menu_window, *game_window; // Okna programu initscr(); // Rozpoczecie pracy z biblioteka CURSES curs_set(0);// Nie wyswietlaj kursora noecho(); // Nie wyswietlaj inputow z klawiatury cbreak(); start_color(); // inicjalizacja kolorów init_pair(1, COLOR_WHITE, COLOR_BLACK); init_pair(2, COLOR_RED, COLOR_BLACK); init_pair(3, COLOR_GREEN, COLOR_BLACK); init_pair(4, COLOR_MAGENTA, COLOR_BLACK); init_pair(5, COLOR_CYAN, COLOR_BLACK); init_pair(6, COLOR_YELLOW, COLOR_BLACK); init_pair(7, COLOR_BLACK, COLOR_WHITE); menu_window = newwin(LINES, 20, 0, COLS-20);// okno menu game_window = newwin(LINES, COLS-20, 0, 0);// okno gry Menu o_menuWin(menu_window);// tworzy objekt okna menu Game o_gameWin(game_window);// tworzy objekt okna gry menu_choosing(o_menuWin, o_gameWin, menu_window, game_window);// funkcja odpowiedzalna za sterowanie grą delwin(menu_window);// Usuniecie okien delwin(game_window); endwin();// Koniec pracy z CURSES return(0); } int menu_choosing(Menu o_menuWin, Game o_gameWin, WINDOW *menu_window, WINDOW *game_window) { int input; do { wbkgdset(menu_window, COLOR_PAIR(o_menuWin.color)); //odpowiada za kolor okna menu wbkgdset(game_window, COLOR_PAIR(o_menuWin.color)); //odpowiada za kolor okna gry wclear(menu_window); o_menuWin.draw_window(); // rysuje okno menu o_gameWin.draw_window(); // rysuje okno gry mvwprintw(game_window, LINES-3, COLS-70, "Poruszanie sie po menu: \"gora\", \"dol\""); mvwprintw(game_window, LINES-2, COLS-70, "Zatwierdz wybor: \"ENTER\""); mvwprintw(menu_window, LINES-(o_menuWin.color_list.size()+2), 1, "ZMIEN KOLOR"); for(int i=0;i<=o_menuWin.color_list.size()-1;i++) mvwprintw(menu_window,LINES-(o_menuWin.color_list.size()+1)+i, 1,"F%d - %s", i+1, o_menuWin.color_list[i].c_str()); wrefresh(game_window); wrefresh(menu_window); o_menuWin.menu_refresh(o_menuWin.menu_list); // odswierzenie menu o_menuWin.choice = 0; // aktualna pozycja w menu input = wgetch(menu_window); // Oczekiwanie na klawisz for(int i=1;i<=o_menuWin.color_list.size();i++) if(input == KEY_F(i)) // sprawdza na bieżąco i zmienia kolory w menu { o_menuWin.color = i; wclear(game_window); } o_menuWin.menu_move(o_menuWin.menu_list, input);// jesli wcisnieto strzalke zmien pozycje menu o_menuWin.menu_refresh(o_menuWin.menu_list); // odswierzenie menu if(input == 10) o_menuWin.choice = o_menuWin.highlight; // po zatwierdzeniu enterem przypisuje nr pozycji menu do choice switch(o_menuWin.choice) { case 1: // nowa gra o_gameWin.run(); break; case 2: // zasady o_gameWin.rules(); break; case 3: // historia o_gameWin.history(); break; case 4: // autorzy o_gameWin.authors(); break; case 5: // wyjscie return 0; } wrefresh(game_window); } while(input != 27); // petla menu działa dopóki nie wcisnięto "ESC" }
[ "k.siwon@hotmail.com" ]
k.siwon@hotmail.com
59eff0bb1911ad0b372d9428de60a4eb4d404f10
06f9c8e88ae09ff889fd2d052dc56378b1ddd7a5
/lab1(float).cpp
da26bbccb90211face6cc89ba3a5b29e1d7a5097
[]
no_license
Misc1170/Timolyanov-G.K.-1-semestr-C-
66371ef0e04fdc2e301621cd388cbcf6d2e30156
75d34d8146489269dd758d15e2faa11281d7f6b6
refs/heads/main
2023-04-19T16:33:13.061712
2021-04-27T17:08:59
2021-04-27T17:08:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
226
cpp
#include <iostream> using namespace std; int main() { float a, b, c, d, f; a = 1000; b = 0.0001; c = (a + b) * (a + b) - (a * a + 2 * a * b); d = b * b; f = c / d; cout << f; }
[ "noreply@github.com" ]
noreply@github.com
e63c059dfedd63f83e16a7c0ea1445e44aef3a79
7ea6c776b6bd8054bae6ec2dbba96717c3bec471
/smc/src/core/filesystem/resource_manager.h
a71fb2f9c62dbaa84c551970ab63bef13cdc7114
[]
no_license
sKabYY/SMC
e8017bde855166432a22ab91d9483d2d16e36d97
6af20fea76e499858f35c1d9ffb6b981c82b59fc
refs/heads/master
2021-01-18T08:42:29.977070
2010-06-05T07:51:57
2010-06-05T07:51:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,491
h
/*************************************************************************** * resource_manager.h - header for the corresponding cpp file * * Copyright (C) 2009 - 2010 Florian Richter ***************************************************************************/ /* 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. 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 SMC_RESOURCE_MANAGER_H #define SMC_RESOURCE_MANAGER_H #include "../../core/global_basic.h" #include "../../core/global_game.h" namespace SMC { /* *** *** *** *** *** cResource_Manager *** *** *** *** *** *** *** *** *** *** *** *** */ class cResource_Manager { public: cResource_Manager( void ); ~cResource_Manager( void ); // Set the user data write directory bool Set_User_Directory( const std::string &dir ); // Create the necessary folders in the user directory void Init_User_Directory( void ); // user data directory std::string user_data_dir; }; /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ // Resource Manager extern cResource_Manager *pResource_Manager; /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ } // namespace SMC #endif
[ "fluxey@gmail.com" ]
fluxey@gmail.com
13aabce38a7f0bfa6851aa17777fb96445d66b29
8621ba408250943b4b822d6e91ea152aa408ab78
/JoyGen_Animation_Test/JoyGen_Animation_Test.ino
1b43751cfe50e0ece6f83603f89235ee6cb933a5
[]
no_license
bhagman/JoyGenTest
c623f799482d289268f6da64be31c5870047e011
10750206278e74872501126239f5772c684be600
refs/heads/master
2021-01-13T10:27:45.769474
2016-10-30T14:29:25
2016-10-30T14:29:25
72,218,922
0
0
null
null
null
null
UTF-8
C++
false
false
7,236
ino
/* || || @author Brett Hagman <bhagman@roguerobotics.com> || @url http://roguerobotics.com/ || @url http://wiring.org.co/ || || @description || | || | Joy Gen Test - Tree Animation || | || # || || @license || | || | Copyright (c) 2016 - Brett Hagman (http://roguerobotics.com/) || | || | 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. || # || || @notes || | || | || # || */ #include <SPI.h> #include "RF24.h" #include <Adafruit_NeoPixel.h> #define VERSIONSTR "1.0" #define PIN 6 #define IDLETIMEOUT 30000L #define IDLECOLOUR 0x505050 #define IDLESPARKLECOLOUR 0xffffff #define IDLENEXTSPARKLETIME 50 byte ctrlAddr[][6] = { "1Ctrl", "2Ctrl" }; byte treeAddr[][6] = { "1Tree", "2Tree", "3Tree" }; bool radioNumber = 0; RF24 radio(9, 10); Adafruit_NeoPixel strip = Adafruit_NeoPixel(100, PIN, NEO_RGB + NEO_KHZ800); uint8_t animationNumber = 0; uint32_t param1 = 0; uint32_t param2 = 0; uint32_t param3 = 0; bool prepared = false; uint32_t lastInteractionTime = 0; bool idle = false; struct dataStruct { char cmd; uint16_t value; } myData; uint8_t red(uint32_t c) { return (c >> 16); } uint8_t green(uint32_t c) { return (c >> 8); } uint8_t blue(uint32_t c) { return (c); } uint32_t fadeOne(uint32_t c, float rate) { uint16_t r, g, b; r = constrain(red(c) * rate, 0, 255); g = constrain(green(c) * rate, 0, 255); b = constrain(blue(c) * rate, 0, 255); return strip.Color(r, g, b); } void fadeAll(float rate) { for (int i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, fadeOne(strip.getPixelColor(i), rate)); } } void prepareIdleAnimation() { for (int i = 0; i < strip.numPixels(); i++) { strip.setPixelColor(i, IDLECOLOUR); } strip.show(); } void idleAnimation() { static uint32_t lastTime = 0; static uint8_t lastSparklePixel = 0; if (!prepared) { prepareIdleAnimation(); prepared = true; lastTime = millis(); } if ((millis() - lastTime) > IDLENEXTSPARKLETIME) { strip.setPixelColor(lastSparklePixel, IDLECOLOUR); lastSparklePixel = random(strip.numPixels()); strip.setPixelColor(lastSparklePixel, IDLESPARKLECOLOUR); strip.show(); lastTime = millis(); } } // Animation 0: light chase // Param A: colour // Param B: speed void prepareAnimation0() { strip.clear(); strip.show(); } void animation0() { static uint32_t lastTime = 0; static uint8_t lastPixel = 0; if (!prepared) { prepareAnimation0(); prepared = true; lastTime = millis(); lastPixel = 0; } if ((millis() - lastTime) > param2) { lastPixel = lastPixel + 1; if (lastPixel == strip.numPixels()) lastPixel = 0; fadeAll(0.85); strip.setPixelColor(lastPixel, param1); strip.show(); lastTime = millis(); } } // Animation 1: dual light chase // Param A: colour // Param B: speed void prepareAnimation1() { strip.clear(); strip.show(); } void animation1() { static uint32_t lastTime = 0; static uint8_t lastPixel = 0; if (!prepared) { prepareAnimation1(); prepared = true; lastTime = millis(); lastPixel = 0; } if ((millis() - lastTime) > param2) { lastPixel = lastPixel + 1; if (lastPixel == strip.numPixels()) lastPixel = 0; fadeAll(0.85); strip.setPixelColor(lastPixel, param1); strip.setPixelColor(strip.numPixels() - lastPixel - 1, 0x0000ff); strip.show(); lastTime = millis(); } } // Animation 2: random pixels with fade // Param A: colour // Param B: speed void prepareAnimation2() { strip.clear(); strip.show(); } void animation2() { static uint32_t lastTime = 0; // static uint8_t lastPixel = 0; if (!prepared) { prepareAnimation2(); prepared = true; lastTime = millis(); // lastPixel = 0; } if ((millis() - lastTime) > param2) { fadeAll(0.85); strip.setPixelColor(random(strip.numPixels()), param1); strip.show(); lastTime = millis(); } } void setIdleMode() { idle = true; prepared = false; } void setActiveMode() { idle = false; prepared = false; lastInteractionTime = millis(); } // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(byte WheelPos) { WheelPos = 255 - WheelPos; if (WheelPos < 85) { return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); } if (WheelPos < 170) { WheelPos -= 85; return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); } WheelPos -= 170; return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } void setup() { Serial.begin(115200); Serial.println(F("JoyGen -- Animation Test V" VERSIONSTR)); strip.begin(); strip.show(); // Initialize all pixels to 'off' radio.begin(); radio.setPALevel(RF24_PA_MIN); radio.openWritingPipe(ctrlAddr[0]); radio.openReadingPipe(1, treeAddr[radioNumber]); radio.startListening(); setIdleMode(); } void loop() { if (!idle && (millis() - lastInteractionTime) > IDLETIMEOUT) { setIdleMode(); } if (idle) { idleAnimation(); } else { switch (animationNumber) { case 0: animation0(); break; case 1: animation1(); break; case 2: animation2(); break; default: break; } } if (Serial.available()) { char c = Serial.read(); switch (c) { case 'a': animationNumber = 0; param1 = Wheel(random(256)); param2 = 20; setActiveMode(); break; case 'b': animationNumber = 1; param1 = Wheel(random(256)); param2 = 20; setActiveMode(); break; case 'c': animationNumber = 2; param1 = Wheel(random(256)); param2 = 20; setActiveMode(); break; } } /* if (radio.available()) { int n = radio.available(); while (radio.available()) { radio.read(&myData, sizeof(myData)); // Get the payload } Serial.print(F("Got: ")); Serial.print(myData.cmd); Serial.print(' '); Serial.println(myData.value); showPixel(myData.value); } */ }
[ "bhagman@roguerobotics.com" ]
bhagman@roguerobotics.com
906b373d6410259110dc4e3eea9eb3f914a500e7
fdf546fa646202da2aa9c56f7146241762a75638
/buildings.cpp
a7a5c4fee603221907490491d14855cdabcbf192
[]
no_license
Seidmani64/temporalComplexity
984d5ad28ab5a77bdbec838de3ecc8fe6c7bca8d
0b5d719f6658a1de8c586b32e803d885eb43a36e
refs/heads/master
2022-12-06T02:14:20.229897
2020-08-27T17:27:21
2020-08-27T17:27:21
290,838,572
0
0
null
null
null
null
UTF-8
C++
false
false
1,343
cpp
#include <iostream> //#include <chrono> using namespace std; //Method resulting in O(m+n) //Has an approximate worst case runtime of 0.001007 seconds (1007000 nanoseconds) template <size_t n, size_t m> int tallest1(int (&arr)[n][m]) { for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(arr[i][j]==0) return j; } } return -1; } //Method resulting in O(mlog(n)) //Has an approximate worst case runtime of 0.000992 seconds (992000 nanoseconds) template <size_t n, size_t m> int tallest2(int row, int (&arr)[n][m]) { for(int i = 0; i < m; i++) if(arr[row][i]==0) return i; return tallest2(row+1, arr); } int main() { //auto start = chrono::high_resolution_clock::now(); int buildings[5][6] = {{1,1,1,0,1,1},{1,1,0,0,0,1}, {0,1,0,0,0,1,},{0,1,0,0,0,1},{0,0,0,0,0,1}}; cout<<"The tallest building using the first method is building at loc #"<<tallest1(buildings)<<endl; cout<<"The tallest building using the second method is building at loc #"<<tallest2(0,buildings)<<endl; //auto duration = chrono::high_resolution_clock::now(); //auto runtime = chrono::duration_cast<std::chrono::nanoseconds>( duration - start ).count(); //cout<<runtime; return 0; }
[ "noreply@github.com" ]
noreply@github.com
776c0503b42960adb48775cf64adbc9c8cb06c8b
76630b58310d55ddd7796f6cc2f7edf0c135693e
/palindrome_num.cpp
fc832fddc8a987bd9f5af77dc6f0a3e06ea1382a
[]
no_license
largetalk/leetcode
1c782a5077a283f49587364f5f92d2fde105ee8f
6a814719faca7628da4f899a0c0e685073e3c679
refs/heads/master
2021-01-21T04:39:19.835841
2019-02-11T03:57:23
2019-02-11T03:57:23
25,806,156
0
0
null
null
null
null
UTF-8
C++
false
false
1,133
cpp
// //Determine whether an integer is a palindrome. Do this without extra space. #include <stdio.h> #include <iostream> #include <vector> using namespace std; class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } if (x < 10) { return true; } int base = 1; while (x /base >= 10) { base *= 10; } while (base) { int left = x /base; int right = x % 10; if (left != right) { return false; } else { x = x % base; x = x / 10; base = base / 100; } } return true; } }; int main(int argc, const char * argv[]) { std::cout << "Hello, World!\n"; Solution s = Solution(); cout << s.isPalindrome(9) << endl; cout << s.isPalindrome(121) << endl; cout << s.isPalindrome(13) << endl; cout << s.isPalindrome(1874994781) << endl; return 0; }
[ "arthur_wang@adsame.com" ]
arthur_wang@adsame.com
3e78c049474babaf34daae335d8c26789ab19c8f
55b0dc4c45cf1e96f1d10d525ae88f602898cf98
/customTabStyle/customTabStyle.h
981fa247a40ac41958de2694c342f49b571a7caa
[]
no_license
0000duck/robotTeachHR
0ac58b5d22318a654200748f98c7154fa501f6eb
3ff999b24bdd7b3660bb22a8d4beb06769d05118
refs/heads/master
2022-03-29T17:51:32.401174
2019-11-04T02:45:34
2019-11-04T02:45:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
598
h
#ifndef CUSTOMTABSTYLE_H #define CUSTOMTABSTYLE_H #include <QPainter> #include <QProxyStyle> #include <QStyleOptionTab> class CustomTabStyle : public QProxyStyle { public: CustomTabStyle(); QSize sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const; void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const; }; #endif
[ "758417483@qq.com" ]
758417483@qq.com
6df04359307b5c26b63d213a93e32d77921daf7d
3fc9c4263fcc758db542322c78235195fd5dfade
/nmchelper/src/JtEventTimer.cpp
3f85dc704ab5430c038cd4ff0f04895afb9fa865
[]
no_license
github188/eventserver
62d6577b02d4f472b448adbbf1e72f05a0f90510
ce237e9c86c6531de872a389483cad27a2393f90
refs/heads/master
2020-06-23T04:51:40.784726
2015-10-18T02:27:36
2015-10-18T02:27:36
null
0
0
null
null
null
null
GB18030
C++
false
false
1,170
cpp
#include "StdAfx.h" #include <time.h> #include "JtEventTimer.h" #include "CachedAffair.h" #include "jtprintf.h" JtEventTimer::JtEventTimer() { } JtEventTimer::~JtEventTimer() { //if(timeout) //{ event_del(&timeout); ///event_free(&timeout); //作为定时器并未分配内存的 //timeout = NULL; //} } void JtEventTimer::TimeoutCallBack(evutil_socket_t fd, short event, void *arg) { JtEventTimer *Self = (JtEventTimer *)arg; Self->Timeout(fd, event); } void JtEventTimer::Timeout(evutil_socket_t fd, short event) { /* struct timeval newtime, difference, lasttime; double elapsed; evutil_gettimeofday(&newtime, NULL); evutil_timersub(&newtime, &lasttime, &difference); elapsed = difference.tv_sec + (difference.tv_usec / 1.0e6); lasttime = newtime; */ ///////////CCachedAffairMap::GetInstance()->CheckBeOverTime(time(0)); } int JtEventTimer::OnAddToServer(JtEventServer *m_Server) { event_assign(&timeout, m_Server->GetBase(), -1, EV_PERSIST, TimeoutCallBack, this); struct timeval tv; evutil_timerclear(&tv); tv.tv_sec = 1000; event_add(&timeout, &tv); return 0; } int JtEventTimer::OnRemoveFromServer() { return 0; }
[ "wwyyxx26@163.com" ]
wwyyxx26@163.com
469e444a599e9b6bb6ed718414e851365332f141
2048fb0c5aacfdb8e564a9588f4aa970b6b5ddba
/路由算法/AdjMGraph.cpp
c58b4bd08a6484ff69752b5ebe49b4841001e78e
[]
no_license
donglin0/Routin
9444f41efaa12a6c80292248bcf0621bf827a147
51b2a060b14026900770cd615e2d76357ec0f96a
refs/heads/master
2020-11-25T04:41:09.035795
2019-12-23T02:12:06
2019-12-23T02:12:06
null
0
0
null
null
null
null
GB18030
C++
false
false
5,316
cpp
#include"AdjMGraph.h" //置带权有向图G为空图 void GraphInitiate(AdjMGraph* G) { int i, j; for (i = 0;i < MaxVertices;i++) for (j = 0;j < MaxVertices;j++) { if (i == j) { G->edge[i][j] = 0; } else { G->edge[i][j] = MaxWeight;//MaxWeight表示权值无穷大 } } G->numOfEdges= 0; //边的条数置为0 ListInitiate(&G->vertices); //顶点顺序表初始化 } //在带权有向图G中取第v个顶点的第一个邻接顶点,如果这样的邻接顶点存在,则返回该顶点在顶点顺序表的序号,否则返回-1。时间复杂度:O(n)。 int GetFirstVex(AdjMGraph G, int v) { int col;//列号 DataType x; v = v - 1; if (ListGet(G.vertices, v, &x) == 0) { printf("取第一个邻接顶点时参数v越界出错!\n"); exit(1); } //寻找邻接矩阵v行中从最左开始第一个值非零且非无穷大的权值对应的顶点 for (col = 0;col < G.vertices.size;col++) if (G.edge[v][col] > 0 && G.edge[v][col] < MaxWeight) return col; return -1; } //在带权有向图G中取第v1个顶点的继邻接结点第v2个顶点之后的下一个邻接结点,时间复杂度:O(n)。 int GetNextVex(AdjMGraph G, int v1, int v2) { int col; DataType x; if ((ListGet(G.vertices, v1, &x) == 0) || (ListGet(G.vertices, v2, &x) == 0)) { printf("取下一邻接顶点时参数v1和v2越界出错!\n"); exit(1); } if (G.edge[v1][v2] == 0) { printf("v2不是v1的邻接顶点\n"); exit(1); } //寻找邻接矩阵v行中从第v2+1列开始的第一个值非零且非无穷大的权值对应的顶点 for (col = v2 + 1;col < G.vertices.size;col++) if (G.edge[v1][col] > 0 && G.edge[v1][col] < MaxWeight) return col; return -1; } //创建有向图G,通过在空图G中插入n个顶点和e条边实现。时间复杂度:O(n^2+e)。 void CreatGraph(AdjMGraph* G, DataType v[], int n, RowColWeight W[], int e) { int i, k; GraphInitiate(G);//图初始化 for (i = 0;i < n;i++) { InsertVertex(G, v[i]);//插入顶点 } for (k = 0;k < e;k++) InsertEdge(G, W[k].row, W[k].col, W[k].weight);//插入边 } void InsertEdge(AdjMGraph* G, int v1, int v2, int weight) { DataType x; if (v1 != v2) { if ((ListGet(G->vertices, v1, &x) == 0) || (ListGet(G->vertices, v2, &x) == 0)) { printf("插入边时参数v1和v2越界出错!\n"); exit(1); } G->edge[v1][v2] = weight; G->edge[v2][v1] = weight;//有向图,两边 G->numOfEdges++; } } void InsertVertex(AdjMGraph* G, DataType vertex) { if (ListInsert(&G->vertices, G->vertices.size, vertex) == 0)//在顶点顺序表的表尾插入顶点vertex { printf("插入顶点时空间已满无法插入!"); exit(1); } } // 在带权有向图G中删除一条第v1个顶点指向第v2个顶点的边。 void DeleteEdge(AdjMGraph* G, int v1, int v2) { G->edge[v1][v2] = MaxWeight; G->edge[v2][v1] = MaxWeight; G->numOfEdges--; } //删除顶点 //在带权有向图G中删除第v个顶点,时间复杂度:O(n^2)。 void DeleteVertex(AdjMGraph* G, int v) { int m3, i, j; m3 = v - 1; if (m3 < 0 || m3 >= G->vertices.size) { printf("对不起,此链路内没有您想要删除的路由节点\n"); exit(0); } else { //for(i=m3;i < G->vertices.size;i++) for (j = 0, i = m3;j < G->vertices.size;j++) { G->edge[j][i] = MaxWeight;//边的权值改为最大值表示不连通 } //for(i=m3;i < G->vertices.size;i++) for (i = m3, j = 0;j < G->vertices.size;j++) G->edge[i][j] = MaxWeight;//有向图修改两次 //for(i=m3;i < G->vertices.size;i++) //G->vertices.list[i]=G->vertices.list[i]-1; //G->vertices.size--; printf("删除结点成功\n"); } } //迪克特斯拉算法求得是最短路径和相应的路由器 void Dijkstra(AdjMGraph* G, int v0, int distance[], int path[]) //带权图G从下标0顶点到其它顶点的最短距离distance和最短路径上顶点前驱下标path { int n = G->vertices.size; int* S = (int*)malloc(sizeof(int) * n); //S数组 int minDis, i, j, u; FILE* fp=NULL; /*初始化*/ for (i = 0; i < n; i++) { distance[i] = G->edge[v0][i]; S[i] = 0; if (i != v0 && distance[i] < MaxWeight) path[i] = v0; else path[i] = -1; } S[v0] = 1; /*在当前还未找到最短路径的顶点集中选取具有最短距离的顶点u*/ for (i = 1; i < n; i++) { minDis = MaxWeight; for (j = 0;j < n;j++) if (S[j] == 0 && distance[j] < minDis) { u = j; minDis = distance[j]; } /*当已不再存在路径时算法结束*/ if (minDis == MaxWeight) return; S[u] = 1; //标记顶点u已从集合T加入到集合S中*/ /*修改从v0到其它顶点的最短距离和最短路径*/ for (j = 0; j < n; j++) if (S[j] == 0 && G->edge[u][j] < MaxWeight && distance[u] + G->edge[u][j] < distance[j]) { distance[j] = distance[u] + G->edge[u][j]; path[j] = u; } } printf("目的路由 下一跳路由\n");//一旦有单独的路由,路由表就无法输出 errno_t err;//标志文件打开与否 err = fopen_s(&fp, "routinlist.txt", "w"); for (i = 0;i < n;i++) { if (i == v0) continue;//不输出到本路由的表项 j = i; while (path[j] != v0) { j = path[j]; if (j == -1) break; } printf("%5d%12d\n", i + 1, j + 1); fprintf(fp, "%5d%12d\n", i + 1, j + 1);//写入到文件中去 } fclose(fp); }
[ "44114683+donglin0@users.noreply.github.com" ]
44114683+donglin0@users.noreply.github.com
6068b71f67d8f07e690c686abd34cafd2874cb84
e69198f43d3fd9d3272028ea253bcfe30e9698d6
/wz_epmcs/src/pmcsana.h
8d3c0dcfd1e79191396e1b3af058bb6dc042b8de
[]
no_license
hengne/d0wmass
a8514dfb01db7d9a60aa517e49bb6bc980c8cd24
f25d5ddb4616b00ca1e9ab83c02657844b778c3b
refs/heads/master
2021-01-20T18:20:06.573869
2016-06-05T13:30:24
2016-06-05T13:30:24
60,460,795
0
0
null
null
null
null
UTF-8
C++
false
false
12,845
h
////////////////////////////////////////////////////////// // This class has been automatically generated on // Mon Jun 20 11:05:42 2005 by ROOT version 4.02/00 // from TTree Global/Global // found on file: /rooms/salon/dpchapin/wz_mc/cabout_cteq6l/zgamma_cteq6l_1-p17.02.00-maxopt-Linux-692397/global.root.root ////////////////////////////////////////////////////////// #ifndef pmcsana_h #define pmcsana_h #include <TROOT.h> #include <TChain.h> #include <TFile.h> #include <TSelector.h> #include "PMCSEvent.hpp" #include "GlobalParameters.hpp" #include "WAnalysis.hpp" #include "ZAnalysis.hpp" #include "ZMuAnalysis.hpp" #include "ZNuNuAnalysis.hpp" #include "JPsiMuAnalysis.hpp" #include "TRandom3.h" #include "BeamWeight.hpp" // // Need to uncomment out pmcs_ana_evflav1, pmcs_ana_evflav2, // pmcs_ana_evqdq, pmcs_ana_evx1 and pmcs_ana_evx2 for PDF reweighting // class pmcsana : public TSelector { public : TTree *fChain; //!pointer to the analyzed TTree or TChain // Declaration of leave types Int_t pmcs_ana_nevtp; Int_t pmcs_ana_npart; Int_t pmcs_ana_nvtx; Float_t pmcs_ana_evnum[1000]; //[nevtp] Float_t pmcs_ana_evrun[1000]; //[nevtp] Float_t pmcs_ana_evwt[1000]; //[nevtp] Float_t pmcs_ana_evxs[1000]; //[nevtp] Float_t pmcs_ana_pE[1000]; //[npart] Float_t pmcs_ana_pcid[1000]; //[npart] Float_t pmcs_ana_pcnum[1000]; //[npart] Float_t pmcs_ana_pdvtx[1000]; //[npart] Float_t pmcs_ana_peta[1000]; //[npart] Float_t pmcs_ana_pidx[1000]; //[npart] Float_t pmcs_ana_pistable[1000]; //[npart] Float_t pmcs_ana_pphi[1000]; //[npart] Float_t pmcs_ana_ppid[1000]; //[npart] Float_t pmcs_ana_ppt[1000]; //[npart] Float_t pmcs_ana_ppvtx[1000]; //[npart] Float_t pmcs_ana_ppx[1000]; //[npart] Float_t pmcs_ana_ppy[1000]; //[npart] Float_t pmcs_ana_ppz[1000]; //[npart] Float_t pmcs_ana_vcid[1000]; //[nvtx] Float_t pmcs_ana_vcnum[1000]; //[nvtx] Float_t pmcs_ana_vct[1000]; //[nvtx] Float_t pmcs_ana_vidx[1000]; //[nvtx] Float_t pmcs_ana_visdisp[1000]; //[nvtx] Float_t pmcs_ana_vpprt[1000]; //[nvtx] Float_t pmcs_ana_vx[1000]; //[nvtx] Float_t pmcs_ana_vy[1000]; //[nvtx] Float_t pmcs_ana_vz[1000]; //[nvtx] #ifdef __USE_PDFS__ Float_t pmcs_ana_evflav1[1000]; //[nevtp] Float_t pmcs_ana_evflav2[1000]; //[nevtp] Float_t pmcs_ana_evqsq[1000]; //[nevtp] Float_t pmcs_ana_evx1[1000]; //[nevtp] Float_t pmcs_ana_evx2[1000]; //[nevtp] #endif #ifdef __USE_PDFS_RESBOS__ Float_t pmcs_ana_pdf_wgts[45]; #endif Int_t pmcs_em_nelg; Int_t pmcs_em_nels; Int_t pmcs_em_nphg; Int_t pmcs_em_nphs; Float_t pmcs_em_elcalphis[120]; //[nels] Float_t pmcs_em_eleg[120]; //[nelg] Float_t pmcs_em_elelmergedEg[120]; //[nelg] Float_t pmcs_em_eles[120]; //[nels] Float_t pmcs_em_eletads[120]; //[nels] Float_t pmcs_em_eletag[120]; //[nelg] Float_t pmcs_em_eletas[120]; //[nels] Float_t pmcs_em_elfid[120]; //[nelg] Int_t pmcs_em_elhastrack[120]; //[nels] Float_t pmcs_em_eliso[120]; //[nels] Int_t pmcs_em_elmergedg[120]; //[nelg] Int_t pmcs_em_elpasshmtx[120]; //[nels] Int_t pmcs_em_elpassid1011[120]; //[nels] Float_t pmcs_em_elphig[120]; //[nelg] Float_t pmcs_em_elphis[120]; //[nels] Float_t pmcs_em_elphmergedEg[120]; //[nelg] Int_t pmcs_em_elpntg[120]; //[nels] Int_t pmcs_em_elpnts[120]; //[nelg] Float_t pmcs_em_elptg[120]; //[nelg] Float_t pmcs_em_elpts[120]; //[nels] Int_t pmcs_em_elpttr[120]; //[nels] Float_t pmcs_em_elFSRxInCones[120]; //[nels] Int_t pmcs_em_elFSRnInCones[120]; //[nels] Float_t pmcs_em_pheg[120]; //[nphg] Float_t pmcs_em_phes[120]; //[nphs] Float_t pmcs_em_phetads[120]; //[nphs] Float_t pmcs_em_phetag[120]; //[nphg] Float_t pmcs_em_phetas[120]; //[nphs] Float_t pmcs_em_phfid[120]; //[nphg] Int_t pmcs_em_phhastrack[120]; //[nels] Float_t pmcs_em_phiso[120]; //[nphs] Int_t pmcs_em_phpasshmtx[120]; //[nels] Float_t pmcs_em_phphig[120]; //[nphg] Float_t pmcs_em_phphis[120]; //[nphs] Int_t pmcs_em_phpntg[120]; //[nphs] Int_t pmcs_em_phpnts[120]; //[nphg] Float_t pmcs_em_phptg[120]; //[nphg] Float_t pmcs_em_phpts[120]; //[nphs] Int_t pmcs_met_nmetg; Int_t pmcs_met_nmets; Float_t pmcs_met_metg[200]; //[nmetg] Float_t pmcs_met_metphig[200]; //[nmetg] Float_t pmcs_met_metphis[200]; //[nmets] Float_t pmcs_met_mets[200]; //[nmets] Float_t pmcs_met_metxg[200]; //[nmetg] Float_t pmcs_met_metxs[200]; //[nmets] Float_t pmcs_met_metyg[200]; //[nmetg] Float_t pmcs_met_metys[200]; //[nmets] Float_t pmcs_met_scalarg[200]; //[nmetg] Float_t pmcs_met_scalars[200]; //[nmets] Int_t pmcs_vtx_nvtxg; Int_t pmcs_vtx_nvtxs; Float_t pmcs_vtx_vtnds[150]; //[nvtxs] Float_t pmcs_vtx_vtxxs[150]; //[nvtxs] Float_t pmcs_vtx_vtxys[150]; //[nvtxs] Float_t pmcs_vtx_vtxzg[150]; //[nvtxg] Float_t pmcs_vtx_vtxzs[150]; //[nvtxs] // List of branches TBranch *b_pmcs_ana; //! TBranch *b_pmcs_em; //! TBranch *b_pmcs_met; //! TBranch *b_pmcs_vtx; //! pmcsana(TTree *tree=0) { } ~pmcsana(); Int_t Version() const {return 1;} void Begin(TTree *tree); void SlaveBegin(TTree *tree); void Init(TTree *tree); Bool_t Notify(); Bool_t Process(Long64_t entry); void SetOption(const char *option) { fOption = option; } void SetObject(TObject *obj) { fObject = obj; } void SetInputList(TList *input) {fInput = input;} TList *GetOutputList() const { return fOutput; } void SlaveTerminate(); void Terminate(); int WriteOut(); void Initialize(); ClassDef(pmcsana,0); // user defined functions void fixEMBlock(Int_t entry, PMCSVtx& vtx, double cut_dR_CC, double cut_dR_EC, double instlumi, bool selectLeadingFSR=false, double* LeadFSR_ET=0, double* LeadFSR_dR=0, double* LeadFSR_x=0, double* TrailFSR_ET=0, int* FSR_nPhot=0, int* FSR_nInConePhot=0, int* FSR_nOutConePhot=0); bool constructPMCSEvent(Int_t entry, int runNo, double instlumi, double& evtweight, PMCSParticle& wzboson, std::vector<PMCSEMObj>& emobjs_raw, std::vector<PMCSEMObj>& emobjs_raw_wfsr, std::vector<PMCSEMObj>& emobjs, PMCSMet& met, PMCSRecoil& recoil, PMCSVtx& vtx, std::vector<PMCSMuon>& muons, bool selectLeadingFSR, double& LeadFSR_ET, double& LeadFSR_dR, double& LeadFSR_x, double& TrailFSR_ET, int& FSR_nPhot, int& FSR_nInConePhot, int& FSR_nOutConePhot, TRandom3 *dummy); Float_t CalculateTruePhiStar(Bool_t* passesCuts=0); void setParameterFileName(const char *s){ _parameter_filename = TString(s); } void setOutputRootFileName(const char *s){ _output_root_filename = TString(s); } // use this flag to indicate whether you want to process Z or W events void setRunOption(int runoption) { _runoption = runoption; } void setRandomSeed(int r) { _randomseed = r; } void setNumEvents(int numEvents) { _numEvents = numEvents; } private: TString _parameter_filename; TString _output_root_filename; TFile *_file; int _runoption; int _randomseed; int _numEvents; bool _doPdfReweight; GlobalParameters *_globalparameters; ZAnalysis *_zanalysis; WAnalysis *_wanalysis; ZMuAnalysis *_zmuanalysis; JPsiMuAnalysis *_jpsimuanalysis; ZNuNuAnalysis *_znunuanalysis; TRandom3 *_dummy; // luminosity profile TH1F *_instlumi_profile; // luminosity vs runNo, only used for recoil library method TH2F *_instlumi_runNo_profile; TH1F *_instlumi_runNo_profile_X; TH1F *_instlumi_runNo_profile_Y; // photon merging probability and merged photon response bool _simulate_merge_fsr_photons_in_cone_prob, _simulate_merge_fsr_photons_in_cone_response; std::vector<float> _merge_fsr_photons_in_cone_prob_p0, _merge_fsr_photons_in_cone_prob_p1, _merge_fsr_photons_in_cone_prob_p2, _merge_fsr_photons_in_cone_prob_p3; std::vector<float> _merge_fsr_photons_in_cone_response_p0, _merge_fsr_photons_in_cone_response_p1, _merge_fsr_photons_in_cone_response_p2, _merge_fsr_photons_in_cone_response_p3, _merge_fsr_photons_in_cone_response_p4, _merge_fsr_photons_in_cone_response_p5, _merge_fsr_photons_in_cone_response_p6; bool _simulate_merge_fsr_photons_out_cone_prob, _simulate_merge_fsr_photons_out_cone_response; std::vector<float> _merge_fsr_photons_out_cone_prob_p0, _merge_fsr_photons_out_cone_prob_p1, _merge_fsr_photons_out_cone_prob_p2, _merge_fsr_photons_out_cone_prob_p3, _merge_fsr_photons_out_cone_prob_p4; std::vector<float> _merge_fsr_photons_out_cone_response_p0, _merge_fsr_photons_out_cone_response_p1, _merge_fsr_photons_out_cone_response_p2, _merge_fsr_photons_out_cone_response_p3, _merge_fsr_photons_out_cone_response_p4, _merge_fsr_photons_out_cone_response_p5, _merge_fsr_photons_out_cone_response_p6; // Alternative FSR model(s) TH1D* _FSRmodel_eff[12]; TH1D* _FSRmodel_loss[12]; // TH1D* _FSRmodel_eff_eta[7][12]; TH1D* _FSRmodel_loss_eta[7][12]; // TH1D* _FSRmodel_eff_eta_e[7][4][12]; TH1D* _FSRmodel_loss_eta_e[7][4][12]; double _FSResummary[7][4]; // RunIIb34 model. // TProfile* _FSRmodel_eff_lumi_eta_e_dr[12][7][8][8]; // TProfile* _FSRmodel_loss_lumi_eta_e_dr[12][7][8][8]; // double _FSRlumisummary[7][8][8]; // double _FSResummary2[7][8][8]; std::vector < std::vector < std::vector < std::vector < TProfile* > > > > _FSRmodel_eff_lumi_eta_e_dr; std::vector < std::vector < std::vector < std::vector < TProfile* > > > > _FSRmodel_loss_lumi_eta_e_dr; std::vector < std::vector < std::vector < double > > > _FSRlumisummary; std::vector < std::vector < std::vector < double > > > _FSResummary2; std::vector < float > fsrmodel7_ebins; std::vector < float > fsrmodel7_etabins; std::vector < float > fsrmodel7_lumibins; std::vector < float > fsrmodel7_drbins; // Histograms for phi star reweighting TH1D* _phistarDist[3]; // TH1D* _phistarWT[3]; // beam spot weight BeamWeight *_beam; // for ZNuNuAnalysis (runoption = 4) double _NuLoose_EtaMax; double _NuLoose_PtMin; double _NuTight_EtaMax; double _NuTight_PtMin; Int_t _neigen; }; #endif #ifdef pmcsana_cxx void pmcsana::Init(TTree *tree) { // The Init() function is called when the selector needs to initialize // a new tree or chain. Typically here the branch addresses of the tree // will be set. It is normaly not necessary to make changes to the // generated code, but the routine can be extended by the user if needed. // Init() will be called many times when running with PROOF. // Set branch addresses if (tree == 0) return; fChain = tree; fChain->SetMakeClass(1); fChain->SetBranchAddress("pmcs_ana",&pmcs_ana_nevtp); fChain->SetBranchAddress("pmcs_em",&pmcs_em_nelg); fChain->SetBranchAddress("pmcs_met",&pmcs_met_nmetg); fChain->SetBranchAddress("pmcs_vtx",&pmcs_vtx_nvtxg); } Bool_t pmcsana::Notify() { // The Notify() function is called when a new file is opened. This // can be either for a new TTree in a TChain or when when a new TTree // is started when using PROOF. Typically here the branch pointers // will be retrieved. It is normaly not necessary to make changes // to the generated code, but the routine can be extended by the // user if needed. // Get branch pointers b_pmcs_ana = fChain->GetBranch("pmcs_ana"); b_pmcs_em = fChain->GetBranch("pmcs_em"); b_pmcs_met = fChain->GetBranch("pmcs_met"); b_pmcs_vtx = fChain->GetBranch("pmcs_vtx"); return kTRUE; } #ifdef __USE_PDFS__ #include "LHAPDF/FortranWrappers.h" #ifdef FC_DUMMY_MAIN int FC_DUMMY_MAIN() { return 1; } #endif #endif #endif // #ifdef pmcsana_cxx
[ "Hengne.Li@cern.ch" ]
Hengne.Li@cern.ch
1c5eba93e243fb55017b098a527e73dc5c8a0efa
8bf28c7391b97c89a26c7ab312a6750196b22493
/ExcelEx/ExcelEx.cpp
f680812ca61865096d1a9069848ae553014c7133
[]
no_license
IanSlumber/MFC_Samples
2026b5a33ec4c88bdfee2ab6165aa70d34715482
84587f6fff38d4d6329d45ee80cc177d99e4df8e
refs/heads/master
2022-03-30T00:39:47.453192
2019-12-20T05:11:52
2019-12-20T05:11:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,818
cpp
#include "stdafx.h" #include "ExcelEx.h" #include "tlhelp32.h" const short xlBorderWeightThin = 2; const double dbThresholdPicture = 1.333; CExcelEx::CExcelEx(void) { Initialize(); } CExcelEx::~CExcelEx(void) { QuitExcel(); } void CExcelEx::SaveData(void) { TRY { // save m_book.Save(); } //Clean up if something went wrong. CATCH(CException, e) { AfxMessageBox("Could not save data"); } END_CATCH } void CExcelEx::SetFont(int nCol, int nRow, long lValue) { CExcelRange range; CExcelBorder border; CExcelFont font; CString strPos = GetExcelPos(nCol,nRow); range = m_sheet.get_Range(COleVariant(strPos), COleVariant(strPos)); font = range.get_Font(); font.put_Color(COleVariant(COleVariant(lValue))); } void CExcelEx::SaveAs(CString strFilePath) { TRY { // save m_book.SaveAs(COleVariant(strFilePath), m_covOptional,m_covOptional,m_covOptional,m_covOptional, m_covOptional,1,m_covOptional,m_covOptional, m_covOptional,m_covOptional); } //Clean up if something went wrong. CATCH(CException, e) { AfxMessageBox("Could not save data"); } END_CATCH } void CExcelEx::InsertString(int nCol, int nRow, CString strValue) { CExcelRange range; CExcelBorder border; CString strPos = GetExcelPos(nCol,nRow); if(m_bIsSheetSelected==TRUE) { range = m_sheet.get_Range(COleVariant(strPos), COleVariant(strPos)); range.Select(); //range.get_Font(); //border = range.get_Borders(); //border.put_Weight(COleVariant(xlBorderWeightThin)); range.put_Value(COleVariant(strValue)); } else { AfxMessageBox ("Sheet is not selected. Select a sheet first."); } } CString CExcelEx::GetExcelPos(int nCol, int nRow) { CString strRet; int nDiv=0, nMod=0; if(nCol>26) { nDiv = nCol / 26; nMod = nCol % 26; strRet.Format("%c%c%d", 0x40+nDiv, 0x40+nMod, nRow); } else { strRet.Format("%c%d", 0x40+nCol, nRow); } return strRet; } int CExcelEx::InsertPicture(int nCol, int nRow, CString strPicPath) { POSITION pos; CRange range; CPicture pic; CPictures pics; CBorder border; CString strPos = GetExcelPos(nCol,nRow); int nNextRow; if(m_bIsSheetSelected==TRUE) { pics = m_sheet.Pictures(m_covOptional); //pics.Cut(); //시트 내 사진 지우기 // get pointer to the first image // insert first picture and put a border on it range = m_sheet.get_Range(COleVariant(strPos), COleVariant(strPos)); range.Select (); pic = pics.Insert (strPicPath, m_covOptional); border = pic.get_Border (); border.put_Weight(COleVariant(xlBorderWeightThin)); // get cell height VARIANT var = range.get_Height (); double d = var.dblVal; // get picture height (in cell units) double w = pic.get_Width (); double h = pic.get_Height ()*dbThresholdPicture; // in row height units int cells = (int) (h/d)+1; cells += ((h/d - cells) > 0); nNextRow = cells + 1; // jump to the top of the sheet range = m_sheet.get_Range(COleVariant("A1"), COleVariant("A1")); range.Show (); } else { AfxMessageBox ("Sheet is not selected. Select a sheet first."); return -1; } return nNextRow; } void CExcelEx::CloseWorkBook(void) { TRY { // close already-opened workbook m_book.ReleaseDispatch(); m_books.Close(); m_books.ReleaseDispatch(); m_bIsSheetSelected=FALSE; } //Clean up if something went wrong. CATCH(CException, e) { AfxMessageBox ("Could not clean up workbook."); } END_CATCH } void CExcelEx::OpenWorkBook(CString strFilePath) { // close already-opened workbook CloseWorkBook(); // open the specified workbook TRY { if(m_bIsExcelStarted==TRUE) { // Get Workbooks collection. LPDISPATCH lpDisp; lpDisp = m_app.get_Workbooks(); // Get an IDispatch pointer ASSERT(lpDisp); m_books.AttachDispatch( lpDisp ); // Attach the IDispatch pointer to the books object. // open the document lpDisp = m_books.Open(strFilePath, m_covOptional, m_covOptional, m_covOptional, m_covOptional, m_covOptional, m_covOptional, m_covOptional, m_covOptional, m_covOptional, m_covOptional, m_covOptional, m_covOptional ); ASSERT(lpDisp); //Set CWorkbook to use lpDisp, the IDispatch* of the actual workbook. m_book.AttachDispatch(lpDisp); } else { AfxMessageBox ("Excel is not started. Start Excel first."); } } //Clean up if something went wrong. CATCH(CException, e) { AfxMessageBox ("Could not open workbook."); Initialize(); return; } END_CATCH } void CExcelEx::CreateWorkBook(CString strFilePath) { // close already-opened workbook CloseWorkBook(); // open the specified workbook TRY { if(m_bIsExcelStarted==TRUE) { // Get Workbooks collection. LPDISPATCH lpDisp; lpDisp = m_app.get_Workbooks(); // Get an IDispatch pointer ASSERT(lpDisp); m_books.AttachDispatch( lpDisp ); // Attach the IDispatch pointer to the books object. // Create the document lpDisp = m_books.Add(m_covOptional); ASSERT(lpDisp); // Set CWorkbook to use lpDisp, the IDispatch* of the actual workbook. m_book.AttachDispatch(lpDisp); m_book.SaveAs(COleVariant(strFilePath), m_covOptional,m_covOptional,m_covOptional,m_covOptional, m_covOptional,1,m_covOptional,m_covOptional, m_covOptional,m_covOptional); } else { AfxMessageBox ("Excel is not started. Start Excel first."); } } //Clean up if something went wrong. CATCH(CException, e) { AfxMessageBox ("Could not create workbook."); Initialize(); return; } END_CATCH } void CExcelEx::usrTerminateProcess(LPCTSTR szImageName) { HANDLE hProcessSnap = NULL; BOOL bRet = FALSE; PROCESSENTRY32 pe32 = { 0 }; // Take a snapshot of all processes in the system. hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) return; // Fill in the size of the structure before using it. pe32.dwSize = sizeof(PROCESSENTRY32); // Walk the snapshot of the processes, and for each process, // display information. if (Process32First(hProcessSnap, &pe32)) { do { BOOL bTerminate = FALSE; if (_stricmp(pe32.szExeFile, szImageName) == 0) { bTerminate = TRUE; } else { int nCount = strlen(pe32.szExeFile), nCount2 = strlen(szImageName) + 1; char szExeFile[255] = { 0, }; for (; ; ) { if (nCount2 == -1) break; szExeFile[nCount2] = pe32.szExeFile[nCount]; nCount2--; nCount--; } if (szExeFile[0] == '\\') { strcpy_s(szExeFile, &(szExeFile[1])); } if (_stricmp(szExeFile, szImageName) == 0) { bTerminate = TRUE; } } if (bTerminate) { // terminate HANDLE hProcess = NULL; if (hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pe32.th32ProcessID)) { bRet = TerminateProcess(hProcess, 0); CloseHandle(hProcess); } } } while (Process32Next(hProcessSnap, &pe32)); bRet = TRUE; } else bRet = FALSE; // could not walk the list of processes // Do not forget to clean up the snapshot object. CloseHandle(hProcessSnap); } void CExcelEx::AddSheet(CString strName) { TRY { CWorksheets sheets=m_book.get_Worksheets(); CWorksheet sheetLast = sheets.get_Item(COleVariant((short)(sheets.get_Count()))); // sheets are indexed starting from 1 CWorksheet sheetFirst = sheets.get_Item(COleVariant(1L)); // sheets are indexed starting from 1 COleVariant vDefault; vDefault.vt = VT_DISPATCH; vDefault.pdispVal = (LPDISPATCH)sheetLast; CWorksheet sheetAdded = sheets.Add(m_covOptional, vDefault, COleVariant(1L),COleVariant(-4167L)); if(strName!="") sheetAdded.put_Name(strName); sheetFirst.Activate(); } //Clean up if something went wrong. CATCH(CException, e) { AfxMessageBox("Could not add sheet"); } END_CATCH } void CExcelEx::ViewSheetNamesExist(CComboBox* pCbBox) { // populate combo fields TRY { CWorksheets sheets; CWorksheet sheet; sheets = m_book.get_Worksheets(); // get all the worksheet names and populate the combo box int count = sheets.get_Count(); if (count) { for (int i = 0; i < count; i++) { sheet = sheets.get_Item(COleVariant((short)(i+1))); // sheets are indexed starting from 1 CString name = sheet.get_Name (); pCbBox->AddString (name); } pCbBox->SetCurSel(0); //pCbBox->EnableWindow(); } } //Clean up if something went wrong. CATCH(CException, e) { AfxMessageBox ("Could not get sheet names."); } END_CATCH } void CExcelEx::StartExcel(void) { // start excel process TRY { if(!m_app.CreateDispatch("Excel.Application")) { AfxMessageBox("Could not start Excel."); } m_app.put_DisplayAlerts (VARIANT_FALSE); m_app.put_UserControl(FALSE); m_bIsExcelStarted=TRUE; } //Clean up if something went wrong. CATCH(CException, e) { AfxMessageBox ("Could not start Excel."); } END_CATCH } void CExcelEx::QuitExcel(void) { CloseWorkBook(); TRY { m_app.Quit(); m_app.ReleaseDispatch(); } //Clean up if something went wrong. CATCH(CException, e) { AfxMessageBox ("Could not quit Excel."); } END_CATCH usrTerminateProcess("EXCEL.EXE"); } void CExcelEx::SelectSheet(int nNum) { int nCnt; m_sheets = m_book.get_Worksheets(); nCnt = m_sheets.get_Count(); if(nNum<=nCnt) { m_sheet = m_sheets.get_Item(COleVariant((short)nNum)); m_bIsSheetSelected=TRUE; m_sheet.Select(m_covOptional); m_app.put_UserControl(TRUE); } else { AfxMessageBox("There is no sheet number you select."); //선택한 번호보다 Sheet 카운트가 적은 경우 } } void CExcelEx::SelectSheet(CString strName) { m_sheets = m_book.get_Worksheets(); m_sheet = m_sheets.get_Item(COleVariant(strName)); m_sheet.Select(m_covOptional); m_bIsSheetSelected=TRUE; m_app.put_UserControl(TRUE); } void CExcelEx::SetSheetName(CString strName) { if(m_bIsSheetSelected) { m_sheet.put_Name(strName); } else { AfxMessageBox("There is no sheet number you select."); //선택한 번호보다 Sheet 카운트가 적은 경우 } } void CExcelEx::ShowExcel(BOOL bShow) { if(m_bIsExcelStarted==TRUE) { m_app.put_Visible(bShow); } else { AfxMessageBox("Excel is not started yet. Start excel first."); } } void CExcelEx::Initialize(void) { m_covTrue = ((short)TRUE); m_covFalse = ((short)FALSE); m_covOptional = COleVariant((long)DISP_E_PARAMNOTFOUND, VT_ERROR); m_bIsExcelStarted=FALSE; m_bIsSheetSelected=FALSE; QuitExcel(); //처음 시작시 엑셀 프로그램 열기 오류 방지 } CString CExcelEx::ReadData(int nCol, int nRow) { CString strPos; CString strRet=""; CRange range; if(m_bIsSheetSelected==TRUE) { strPos = GetExcelPos(nCol,nRow); range = m_sheet.get_Range(COleVariant(strPos), COleVariant(strPos)); strRet = range.get_Value(); } else { AfxMessageBox("Sheet is not selected yet. Select sheet first."); } return strRet; }
[ "noreply@github.com" ]
noreply@github.com
d1c8a202aaa9e5edb0a9b5b4566221bcde2aa5e4
794b4c922419d0d2b77c6fe5e40f62dff8055d07
/engine/modellistclass.cpp
9ae2478de755eb1d2600f575ceaa49aae844d978
[]
no_license
xdiv/dev
05c1d99c0bb73e90a48a145c75fa50cbf65457ad
8d0768d002130ee760eae4eddbd7467be6a77aca
refs/heads/master
2021-01-19T17:44:33.155464
2013-09-04T18:25:48
2013-09-04T18:25:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,423
cpp
#include "modellistclass.h" ModelListClass::ModelListClass() { m_ModelInfoList = 0; } ModelListClass::ModelListClass(const ModelListClass& other) { } ModelListClass::~ModelListClass() { } bool ModelListClass::Initialize(int numModels) { int i; float red, green, blue; //First store the number of models that will be used and then create the list array of them using the ModelInfoType structure. // Store the number of models. m_modelCount = numModels; // Create a list array of the model information. m_ModelInfoList = new ModelInfoType[m_modelCount]; if(!m_ModelInfoList) { return false; } // Seed the random number generator with the current time and then randomly generate the position of color of the models and // store them in the list array. // Seed the random generator with the current time. srand((unsigned int)time(NULL)); // Go through all the models and randomly generate the model color and position. for(i=0; i<m_modelCount; i++) { // Generate a random color for the model. red = (float)rand() / RAND_MAX; green = (float)rand() / RAND_MAX; blue = (float)rand() / RAND_MAX; m_ModelInfoList[i].color = D3DXVECTOR4(red, green, blue, 1.0f); // Generate a random position in front of the viewer for the mode. m_ModelInfoList[i].positionX = (((float)rand()-(float)rand())/RAND_MAX) * 60.0f; m_ModelInfoList[i].positionY = (((float)rand()-(float)rand())/RAND_MAX) * 60.0f; m_ModelInfoList[i].positionZ = ((((float)rand()-(float)rand())/RAND_MAX) * 60.0f) + 5.0f; } return true; } //The Shutdown function releases the model information list array. void ModelListClass::Shutdown() { // Release the model information list. if(m_ModelInfoList) { delete [] m_ModelInfoList; m_ModelInfoList = 0; } return; } //GetModelCount returns the number of models that this class maintains information about. int ModelListClass::GetModelCount() { return m_modelCount; } //The GetData function extracts the position and color of a sphere at the given input index location. void ModelListClass::GetData(int index, float& positionX, float& positionY, float& positionZ, D3DXVECTOR4& color) { positionX = m_ModelInfoList[index].positionX; positionY = m_ModelInfoList[index].positionY; positionZ = m_ModelInfoList[index].positionZ; color = m_ModelInfoList[index].color; return; }
[ "agotovtas@gmail.com" ]
agotovtas@gmail.com
09af971f2143bb9494d9bce75b2221dc3b108b2b
8ce47e73afa904a145a1104fa8eaa71e3a237907
/Robot/controller/NXTBluetooth/io_8574.cpp
b03b494a8ac2e53121cb62c7f2630613234a93d9
[]
no_license
nobody/magiclegoblimps
bc4f1459773773599ec397bdd1a43b1c341ff929
d66fe634cc6727937a066118f25847fa7d71b8f6
refs/heads/master
2021-01-23T15:42:15.729310
2010-05-05T03:15:00
2010-05-05T03:15:00
39,790,220
1
0
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
#include "io_8574.h" #include <sstream> #include <string> Io_8574::Io_8574(Sensor_port port, Connection *connection, unsigned char i2c_address):I2c(port,connection, LOWSPEED, i2c_address){ } Io_8574::~Io_8574(){} void Io_8574::init(bool reply){ I2c::init(reply); read(); read(); this->has_init=true; } void Io_8574::set(unsigned int value){ if(!this->has_init){ init(); } unsigned char command[2]; command[0] = i2c_address; command[1] = value; i2c_write(&command[0], 2, 0); wait_for_bytes(0);//wait for byte to be ready } int Io_8574::read(){ if(!this->has_init){ init(); } unsigned char rx_buffer[I2C_BUFFER_SIZE]; unsigned char command[1]; command[0]=i2c_address; i2c_write(&command[0], 1, 1); wait_for_bytes(1); i2c_read(&rx_buffer[0], 1); return rx_buffer[1] & 0xff; //returns unsigned value } Sensor_type Io_8574::get_type(){ return IO_8574_SENSOR; } std::string Io_8574::print(){ std::stringstream out; out << read(); return out.str(); }
[ "eXceLynX@445d4ad4-0937-11df-b996-818f58f34e26" ]
eXceLynX@445d4ad4-0937-11df-b996-818f58f34e26
ec05c88f658ef68cc164fcf3e368312314c69c43
0ff1697daf968d2f22b1385aec885a6ca4e08696
/CounterStrike(DirectX9)/CounterStrike(DirectX9)/ExitButton.h
e3402dfa0636d14ec3edc59ae3583bbdc7c4631a
[]
no_license
doo9713/CS2D_DirectX9_2Dproject
31ce7af6472cb965d3f510dc8fdb74680256e9e3
53273ac149048d065acc6a468debc1f2e12bafa3
refs/heads/master
2021-08-30T06:28:45.194218
2017-12-16T12:53:25
2017-12-16T12:53:25
110,411,052
0
0
null
null
null
null
UTF-8
C++
false
false
230
h
#pragma once #include "UIButton.h" class CExitButton : public CUIButton { RTTICHECK public : void Start(); void OnButton(); void OutButton(); void ClickButton(); public : CExitButton(CGameObj* Owner); ~CExitButton(); };
[ "doo9713@gmail.com" ]
doo9713@gmail.com
599d29f825a99ef7eedb1a9d9ff7ac9c1783d92a
b26a8e14cfaa1bc2e8086b99ad03ddd686ace72d
/1053 笨小猴.cpp
651d37fbd7c5ab4b3480ee2e112b2f5005a2aafd
[]
no_license
makixi/codevs
ed2013ed5a9699c3db14f8b4ad62222b139083d0
cf5893d57ea1bf19ef9e552b9091fc052e8ba214
refs/heads/master
2021-04-06T20:51:46.667991
2018-04-12T14:39:50
2018-04-12T14:39:50
125,339,266
0
0
null
null
null
null
UTF-8
C++
false
false
602
cpp
#include<iostream> #include<map> #include<cstdio> #include<string> #include<algorithm> using namespace std; const int inf=0x3f3f3f3f; bool is_prime(int n){ if(n<=1)return false; for(int i=2;i*i<=n;++i)if(n%i==0)return false; return true; } int main(){ map<char,int> m; string str; cin>>str; int maxn=-inf,minn=inf; for(int i=0;i<str.length();++i)m[str[i]]++; for(map<char,int>::iterator it=m.begin();it!=m.end();++it){ maxn=max(maxn,it->second); minn=min(minn,it->second); } if(is_prime(maxn-minn)) cout<<"Lucky Word\n"<<maxn-minn; else cout<<"No Answer\n"<<0; return 0; }
[ "lynseychen97@gmail.com" ]
lynseychen97@gmail.com
fd9bb3aaca3110b4ff13376934a816ad6d487edd
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_5/Z6.1+dmb.ld+dmb.ld+addr.c.cbmc.cpp
70fe74e0ca9f3f6708cc1919e636b65ee74f8141
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
36,302
cpp
// Global variabls: // 0:vars:3 // 3:atom_2_X0_1:1 // Local global variabls: // 0:thr0:1 // 1:thr1:1 // 2:thr2:1 #define ADDRSIZE 4 #define LOCALADDRSIZE 3 #define NTHREAD 4 #define NCONTEXT 5 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // Declare arrays for intial value version in contexts int local_mem[LOCALADDRSIZE]; // Dumping initializations local_mem[0+0] = 0; local_mem[1+0] = 0; local_mem[2+0] = 0; int cstart[NTHREAD]; int creturn[NTHREAD]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NTHREAD*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NTHREAD*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NTHREAD*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NTHREAD*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NTHREAD*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NTHREAD*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NTHREAD*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NTHREAD*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NTHREAD*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NTHREAD]; int cdy[NTHREAD]; int cds[NTHREAD]; int cdl[NTHREAD]; int cisb[NTHREAD]; int caddr[NTHREAD]; int cctrl[NTHREAD]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(3+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; mem(0,1) = meminit(0,1); co(0,1) = coinit(0,1); delta(0,1) = deltainit(0,1); mem(0,2) = meminit(0,2); co(0,2) = coinit(0,2); delta(0,2) = deltainit(0,2); mem(0,3) = meminit(0,3); co(0,3) = coinit(0,3); delta(0,3) = deltainit(0,3); mem(0,4) = meminit(0,4); co(0,4) = coinit(0,4); delta(0,4) = deltainit(0,4); co(1,0) = 0; delta(1,0) = -1; mem(1,1) = meminit(1,1); co(1,1) = coinit(1,1); delta(1,1) = deltainit(1,1); mem(1,2) = meminit(1,2); co(1,2) = coinit(1,2); delta(1,2) = deltainit(1,2); mem(1,3) = meminit(1,3); co(1,3) = coinit(1,3); delta(1,3) = deltainit(1,3); mem(1,4) = meminit(1,4); co(1,4) = coinit(1,4); delta(1,4) = deltainit(1,4); co(2,0) = 0; delta(2,0) = -1; mem(2,1) = meminit(2,1); co(2,1) = coinit(2,1); delta(2,1) = deltainit(2,1); mem(2,2) = meminit(2,2); co(2,2) = coinit(2,2); delta(2,2) = deltainit(2,2); mem(2,3) = meminit(2,3); co(2,3) = coinit(2,3); delta(2,3) = deltainit(2,3); mem(2,4) = meminit(2,4); co(2,4) = coinit(2,4); delta(2,4) = deltainit(2,4); co(3,0) = 0; delta(3,0) = -1; mem(3,1) = meminit(3,1); co(3,1) = coinit(3,1); delta(3,1) = deltainit(3,1); mem(3,2) = meminit(3,2); co(3,2) = coinit(3,2); delta(3,2) = deltainit(3,2); mem(3,3) = meminit(3,3); co(3,3) = coinit(3,3); delta(3,3) = deltainit(3,3); mem(3,4) = meminit(3,4); co(3,4) = coinit(3,4); delta(3,4) = deltainit(3,4); // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !34, metadata !DIExpression()), !dbg !43 // br label %label_1, !dbg !44 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !42), !dbg !45 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !35, metadata !DIExpression()), !dbg !46 // call void @llvm.dbg.value(metadata i64 2, metadata !38, metadata !DIExpression()), !dbg !46 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !47 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l19_c3 old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l19_c3 // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 2; mem(0,cw(1,0)) = 2; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // call void (...) @dmbld(), !dbg !48 // dumbld: Guess cdl[1] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdl[1] >= cdy[1]); ASSUME(cdl[1] >= cr(1,0+0)); ASSUME(cdl[1] >= cr(1,0+1)); ASSUME(cdl[1] >= cr(1,0+2)); ASSUME(cdl[1] >= cr(1,3+0)); ASSUME(creturn[1] >= cdl[1]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !39, metadata !DIExpression()), !dbg !49 // call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !49 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !50 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l21_c3 old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l21_c3 // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !51 ret_thread_1 = (- 1); goto T1BLOCK_END; T1BLOCK_END: // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !54, metadata !DIExpression()), !dbg !62 // br label %label_2, !dbg !44 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !61), !dbg !64 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !55, metadata !DIExpression()), !dbg !65 // call void @llvm.dbg.value(metadata i64 2, metadata !57, metadata !DIExpression()), !dbg !65 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !47 // ST: Guess iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l27_c3 old_cw = cw(2,0+1*1); cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l27_c3 // Check ASSUME(active[iw(2,0+1*1)] == 2); ASSUME(active[cw(2,0+1*1)] == 2); ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(iw(2,0+1*1) >= 0); ASSUME(cw(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cw(2,0+1*1) >= old_cw); ASSUME(cw(2,0+1*1) >= cr(2,0+1*1)); ASSUME(cw(2,0+1*1) >= cl[2]); ASSUME(cw(2,0+1*1) >= cisb[2]); ASSUME(cw(2,0+1*1) >= cdy[2]); ASSUME(cw(2,0+1*1) >= cdl[2]); ASSUME(cw(2,0+1*1) >= cds[2]); ASSUME(cw(2,0+1*1) >= cctrl[2]); ASSUME(cw(2,0+1*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+1*1) = 2; mem(0+1*1,cw(2,0+1*1)) = 2; co(0+1*1,cw(2,0+1*1))+=1; delta(0+1*1,cw(2,0+1*1)) = -1; ASSUME(creturn[2] >= cw(2,0+1*1)); // call void (...) @dmbld(), !dbg !48 // dumbld: Guess cdl[2] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdl[2] >= cdy[2]); ASSUME(cdl[2] >= cr(2,0+0)); ASSUME(cdl[2] >= cr(2,0+1)); ASSUME(cdl[2] >= cr(2,0+2)); ASSUME(cdl[2] >= cr(2,3+0)); ASSUME(creturn[2] >= cdl[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !58, metadata !DIExpression()), !dbg !68 // call void @llvm.dbg.value(metadata i64 1, metadata !60, metadata !DIExpression()), !dbg !68 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !50 // ST: Guess iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l29_c3 old_cw = cw(2,0+2*1); cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l29_c3 // Check ASSUME(active[iw(2,0+2*1)] == 2); ASSUME(active[cw(2,0+2*1)] == 2); ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(cw(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cw(2,0+2*1) >= old_cw); ASSUME(cw(2,0+2*1) >= cr(2,0+2*1)); ASSUME(cw(2,0+2*1) >= cl[2]); ASSUME(cw(2,0+2*1) >= cisb[2]); ASSUME(cw(2,0+2*1) >= cdy[2]); ASSUME(cw(2,0+2*1) >= cdl[2]); ASSUME(cw(2,0+2*1) >= cds[2]); ASSUME(cw(2,0+2*1) >= cctrl[2]); ASSUME(cw(2,0+2*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+2*1) = 1; mem(0+2*1,cw(2,0+2*1)) = 1; co(0+2*1,cw(2,0+2*1))+=1; delta(0+2*1,cw(2,0+2*1)) = -1; ASSUME(creturn[2] >= cw(2,0+2*1)); // ret i8* null, !dbg !51 ret_thread_2 = (- 1); goto T2BLOCK_END; T2BLOCK_END: // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !73, metadata !DIExpression()), !dbg !84 // br label %label_3, !dbg !47 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !83), !dbg !86 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !75, metadata !DIExpression()), !dbg !87 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !50 // LD: Guess old_cr = cr(3,0+2*1); cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l35_c15 // Check ASSUME(active[cr(3,0+2*1)] == 3); ASSUME(cr(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cr(3,0+2*1) >= 0); ASSUME(cr(3,0+2*1) >= cdy[3]); ASSUME(cr(3,0+2*1) >= cisb[3]); ASSUME(cr(3,0+2*1) >= cdl[3]); ASSUME(cr(3,0+2*1) >= cl[3]); // Update creg_r0 = cr(3,0+2*1); crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1)); caddr[3] = max(caddr[3],0); if(cr(3,0+2*1) < cw(3,0+2*1)) { r0 = buff(3,0+2*1); ASSUME((!(( (cw(3,0+2*1) < 1) && (1 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,1)> 0)); ASSUME((!(( (cw(3,0+2*1) < 2) && (2 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,2)> 0)); ASSUME((!(( (cw(3,0+2*1) < 3) && (3 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,3)> 0)); ASSUME((!(( (cw(3,0+2*1) < 4) && (4 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,4)> 0)); } else { if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) { ASSUME(cr(3,0+2*1) >= old_cr); } pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1)); r0 = mem(0+2*1,cr(3,0+2*1)); } ASSUME(creturn[3] >= cr(3,0+2*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !77, metadata !DIExpression()), !dbg !87 // %conv = trunc i64 %0 to i32, !dbg !51 // call void @llvm.dbg.value(metadata i32 %conv, metadata !74, metadata !DIExpression()), !dbg !84 // %xor = xor i32 %conv, %conv, !dbg !52 creg_r1 = creg_r0; r1 = r0 ^ r0; // call void @llvm.dbg.value(metadata i32 %xor, metadata !78, metadata !DIExpression()), !dbg !84 // %add = add nsw i32 0, %xor, !dbg !53 creg_r2 = max(0,creg_r1); r2 = 0 + r1; // %idxprom = sext i32 %add to i64, !dbg !53 // %arrayidx = getelementptr inbounds [3 x i64], [3 x i64]* @vars, i64 0, i64 %idxprom, !dbg !53 r3 = 0+r2*1; creg_r3 = creg_r2; // call void @llvm.dbg.value(metadata i64* %arrayidx, metadata !79, metadata !DIExpression()), !dbg !92 // call void @llvm.dbg.value(metadata i64 1, metadata !81, metadata !DIExpression()), !dbg !92 // store atomic i64 1, i64* %arrayidx monotonic, align 8, !dbg !53 // ST: Guess iw(3,r3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l37_c3 old_cw = cw(3,r3); cw(3,r3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l37_c3 // Check ASSUME(active[iw(3,r3)] == 3); ASSUME(active[cw(3,r3)] == 3); ASSUME(sforbid(r3,cw(3,r3))== 0); ASSUME(iw(3,r3) >= 0); ASSUME(iw(3,r3) >= creg_r3); ASSUME(cw(3,r3) >= iw(3,r3)); ASSUME(cw(3,r3) >= old_cw); ASSUME(cw(3,r3) >= cr(3,r3)); ASSUME(cw(3,r3) >= cl[3]); ASSUME(cw(3,r3) >= cisb[3]); ASSUME(cw(3,r3) >= cdy[3]); ASSUME(cw(3,r3) >= cdl[3]); ASSUME(cw(3,r3) >= cds[3]); ASSUME(cw(3,r3) >= cctrl[3]); ASSUME(cw(3,r3) >= caddr[3]); // Update caddr[3] = max(caddr[3],creg_r3); buff(3,r3) = 1; mem(r3,cw(3,r3)) = 1; co(r3,cw(3,r3))+=1; delta(r3,cw(3,r3)) = -1; ASSUME(creturn[3] >= cw(3,r3)); // %cmp = icmp eq i32 %conv, 1, !dbg !55 creg__r0__1_ = max(0,creg_r0); // %conv1 = zext i1 %cmp to i32, !dbg !55 // call void @llvm.dbg.value(metadata i32 %conv1, metadata !82, metadata !DIExpression()), !dbg !84 // store i32 %conv1, i32* @atom_2_X0_1, align 4, !dbg !56, !tbaa !57 // ST: Guess iw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l39_c15 old_cw = cw(3,3); cw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l39_c15 // Check ASSUME(active[iw(3,3)] == 3); ASSUME(active[cw(3,3)] == 3); ASSUME(sforbid(3,cw(3,3))== 0); ASSUME(iw(3,3) >= creg__r0__1_); ASSUME(iw(3,3) >= 0); ASSUME(cw(3,3) >= iw(3,3)); ASSUME(cw(3,3) >= old_cw); ASSUME(cw(3,3) >= cr(3,3)); ASSUME(cw(3,3) >= cl[3]); ASSUME(cw(3,3) >= cisb[3]); ASSUME(cw(3,3) >= cdy[3]); ASSUME(cw(3,3) >= cdl[3]); ASSUME(cw(3,3) >= cds[3]); ASSUME(cw(3,3) >= cctrl[3]); ASSUME(cw(3,3) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,3) = (r0==1); mem(3,cw(3,3)) = (r0==1); co(3,cw(3,3))+=1; delta(3,cw(3,3)) = -1; ASSUME(creturn[3] >= cw(3,3)); // ret i8* null, !dbg !61 ret_thread_3 = (- 1); goto T3BLOCK_END; T3BLOCK_END: // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !107, metadata !DIExpression()), !dbg !137 // call void @llvm.dbg.value(metadata i8** %argv, metadata !108, metadata !DIExpression()), !dbg !137 // %0 = bitcast i64* %thr0 to i8*, !dbg !69 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !69 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !109, metadata !DIExpression()), !dbg !139 // %1 = bitcast i64* %thr1 to i8*, !dbg !71 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !71 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !113, metadata !DIExpression()), !dbg !141 // %2 = bitcast i64* %thr2 to i8*, !dbg !73 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !73 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !114, metadata !DIExpression()), !dbg !143 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !115, metadata !DIExpression()), !dbg !144 // call void @llvm.dbg.value(metadata i64 0, metadata !117, metadata !DIExpression()), !dbg !144 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !76 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l48_c3 old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l48_c3 // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !118, metadata !DIExpression()), !dbg !146 // call void @llvm.dbg.value(metadata i64 0, metadata !120, metadata !DIExpression()), !dbg !146 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !78 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l49_c3 old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l49_c3 // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !121, metadata !DIExpression()), !dbg !148 // call void @llvm.dbg.value(metadata i64 0, metadata !123, metadata !DIExpression()), !dbg !148 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !80 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l50_c3 old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l50_c3 // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // store i32 0, i32* @atom_2_X0_1, align 4, !dbg !81, !tbaa !82 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l51_c15 old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l51_c15 // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !86 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call5 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !87 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call6 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !88 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !89, !tbaa !90 r5 = local_mem[0]; // %call7 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !92 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !93, !tbaa !90 r6 = local_mem[1]; // %call8 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !94 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !95, !tbaa !90 r7 = local_mem[2]; // %call9 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !96 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !125, metadata !DIExpression()), !dbg !162 // %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !98 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l61_c12 // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r8 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r8 = buff(0,0); ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0)); ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0)); ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0)); ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0)); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r8 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %6, metadata !127, metadata !DIExpression()), !dbg !162 // %conv = trunc i64 %6 to i32, !dbg !99 // call void @llvm.dbg.value(metadata i32 %conv, metadata !124, metadata !DIExpression()), !dbg !137 // %cmp = icmp eq i32 %conv, 2, !dbg !100 creg__r8__2_ = max(0,creg_r8); // %conv10 = zext i1 %cmp to i32, !dbg !100 // call void @llvm.dbg.value(metadata i32 %conv10, metadata !128, metadata !DIExpression()), !dbg !137 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !130, metadata !DIExpression()), !dbg !166 // %7 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !102 // LD: Guess old_cr = cr(0,0+1*1); cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l63_c12 // Check ASSUME(active[cr(0,0+1*1)] == 0); ASSUME(cr(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cr(0,0+1*1) >= 0); ASSUME(cr(0,0+1*1) >= cdy[0]); ASSUME(cr(0,0+1*1) >= cisb[0]); ASSUME(cr(0,0+1*1) >= cdl[0]); ASSUME(cr(0,0+1*1) >= cl[0]); // Update creg_r9 = cr(0,0+1*1); crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+1*1) < cw(0,0+1*1)) { r9 = buff(0,0+1*1); ASSUME((!(( (cw(0,0+1*1) < 1) && (1 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,1)> 0)); ASSUME((!(( (cw(0,0+1*1) < 2) && (2 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,2)> 0)); ASSUME((!(( (cw(0,0+1*1) < 3) && (3 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,3)> 0)); ASSUME((!(( (cw(0,0+1*1) < 4) && (4 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,4)> 0)); } else { if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) { ASSUME(cr(0,0+1*1) >= old_cr); } pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1)); r9 = mem(0+1*1,cr(0,0+1*1)); } ASSUME(creturn[0] >= cr(0,0+1*1)); // call void @llvm.dbg.value(metadata i64 %7, metadata !132, metadata !DIExpression()), !dbg !166 // %conv14 = trunc i64 %7 to i32, !dbg !103 // call void @llvm.dbg.value(metadata i32 %conv14, metadata !129, metadata !DIExpression()), !dbg !137 // %cmp15 = icmp eq i32 %conv14, 2, !dbg !104 creg__r9__2_ = max(0,creg_r9); // %conv16 = zext i1 %cmp15 to i32, !dbg !104 // call void @llvm.dbg.value(metadata i32 %conv16, metadata !133, metadata !DIExpression()), !dbg !137 // %8 = load i32, i32* @atom_2_X0_1, align 4, !dbg !105, !tbaa !82 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l65_c12 // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r10 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r10 = buff(0,3); ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0)); ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0)); ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0)); ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0)); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r10 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i32 %8, metadata !134, metadata !DIExpression()), !dbg !137 // %and = and i32 %conv16, %8, !dbg !106 creg_r11 = max(creg__r9__2_,creg_r10); r11 = (r9==2) & r10; // call void @llvm.dbg.value(metadata i32 %and, metadata !135, metadata !DIExpression()), !dbg !137 // %and17 = and i32 %conv10, %and, !dbg !107 creg_r12 = max(creg__r8__2_,creg_r11); r12 = (r8==2) & r11; // call void @llvm.dbg.value(metadata i32 %and17, metadata !136, metadata !DIExpression()), !dbg !137 // %cmp18 = icmp eq i32 %and17, 1, !dbg !108 creg__r12__1_ = max(0,creg_r12); // br i1 %cmp18, label %if.then, label %if.end, !dbg !110 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg__r12__1_); if((r12==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([108 x i8], [108 x i8]* @.str.1, i64 0, i64 0), i32 noundef 68, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !111 // unreachable, !dbg !111 r13 = 1; goto T0BLOCK_END; T0BLOCK2: // %9 = bitcast i64* %thr2 to i8*, !dbg !114 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !114 // %10 = bitcast i64* %thr1 to i8*, !dbg !114 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !114 // %11 = bitcast i64* %thr0 to i8*, !dbg !114 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !114 // ret i32 0, !dbg !115 ret_thread_0 = 0; goto T0BLOCK_END; T0BLOCK_END: ASSUME(meminit(0,1) == mem(0,0)); ASSUME(coinit(0,1) == co(0,0)); ASSUME(deltainit(0,1) == delta(0,0)); ASSUME(meminit(0,2) == mem(0,1)); ASSUME(coinit(0,2) == co(0,1)); ASSUME(deltainit(0,2) == delta(0,1)); ASSUME(meminit(0,3) == mem(0,2)); ASSUME(coinit(0,3) == co(0,2)); ASSUME(deltainit(0,3) == delta(0,2)); ASSUME(meminit(0,4) == mem(0,3)); ASSUME(coinit(0,4) == co(0,3)); ASSUME(deltainit(0,4) == delta(0,3)); ASSUME(meminit(1,1) == mem(1,0)); ASSUME(coinit(1,1) == co(1,0)); ASSUME(deltainit(1,1) == delta(1,0)); ASSUME(meminit(1,2) == mem(1,1)); ASSUME(coinit(1,2) == co(1,1)); ASSUME(deltainit(1,2) == delta(1,1)); ASSUME(meminit(1,3) == mem(1,2)); ASSUME(coinit(1,3) == co(1,2)); ASSUME(deltainit(1,3) == delta(1,2)); ASSUME(meminit(1,4) == mem(1,3)); ASSUME(coinit(1,4) == co(1,3)); ASSUME(deltainit(1,4) == delta(1,3)); ASSUME(meminit(2,1) == mem(2,0)); ASSUME(coinit(2,1) == co(2,0)); ASSUME(deltainit(2,1) == delta(2,0)); ASSUME(meminit(2,2) == mem(2,1)); ASSUME(coinit(2,2) == co(2,1)); ASSUME(deltainit(2,2) == delta(2,1)); ASSUME(meminit(2,3) == mem(2,2)); ASSUME(coinit(2,3) == co(2,2)); ASSUME(deltainit(2,3) == delta(2,2)); ASSUME(meminit(2,4) == mem(2,3)); ASSUME(coinit(2,4) == co(2,3)); ASSUME(deltainit(2,4) == delta(2,3)); ASSUME(meminit(3,1) == mem(3,0)); ASSUME(coinit(3,1) == co(3,0)); ASSUME(deltainit(3,1) == delta(3,0)); ASSUME(meminit(3,2) == mem(3,1)); ASSUME(coinit(3,2) == co(3,1)); ASSUME(deltainit(3,2) == delta(3,1)); ASSUME(meminit(3,3) == mem(3,2)); ASSUME(coinit(3,3) == co(3,2)); ASSUME(deltainit(3,3) == delta(3,2)); ASSUME(meminit(3,4) == mem(3,3)); ASSUME(coinit(3,4) == co(3,3)); ASSUME(deltainit(3,4) == delta(3,3)); ASSERT(r13== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
c80972b957158242702ab0100b0f6695cdc4ba92
b4d84760314d60fe50ed1df76a73135e6e5a9572
/tests/idempotency/bs-webapi/tests/Webapi/Webapi__Url__test.re
486b5887bd72ce756314969435a20cb0c6d5987a
[ "MIT" ]
permissive
jchavarri/syntax
6a6422c75230eeabd9ba74451efe83cf6d4a29f1
f9207caad19aa92a6256107ae211c70d81106feb
refs/heads/master
2023-01-01T22:40:54.677489
2020-10-21T04:31:46
2020-10-21T04:31:46
291,485,751
0
0
MIT
2020-08-30T14:25:33
2020-08-30T14:25:33
null
UTF-8
C++
false
false
121
re
open Webapi.Url; let params = URLSearchParams.make("key1=value1&key2=value2"); URLSearchParams.forEach(Js.log2, params);
[ "chenglou92@gmail.com" ]
chenglou92@gmail.com
3082454053553bf55f3c8eda0ef71af1ba45052f
11d18956ac0d6872309c69430db35d7f25daff4d
/Backends/Qt5/GUI/Property/Qt5Tree.h
c8edf612a336f305f78bd6239217e3115858fa51
[ "WTFPL" ]
permissive
richard-vock/graphene_legacy
34f285ce28cbd4fca8b64e16ef422b559b9f2895
5a3b23199dda085516749d2b1e88f4076c851e98
refs/heads/master
2021-09-26T08:51:39.683425
2014-01-14T15:50:31
2014-01-14T15:50:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,387
h
/* This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * the COPYING file for more details */ #ifndef QT5TREE_H_ #define QT5TREE_H_ #include <QtWidgets/QWidget> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QTreeWidget> #include <GUI/Property/PropTree.h> namespace GUI { namespace Property { class Qt5Tree : public QObject, public Tree { Q_OBJECT public: typedef std::shared_ptr<Qt5Tree> Ptr; typedef std::weak_ptr<Qt5Tree> WPtr; public: Qt5Tree(std::string label); virtual ~Qt5Tree(); void removePath(const std::vector<std::string>& path); void show(); void hide(); bool visible() const; void enable(); void disable(); bool enabled() const; void setLabel(std::string label); QWidget* widget(); public slots: void itemChanged(QTreeWidgetItem* item, int); protected: void add(const std::vector<std::string>& path, bool checked); QTreeWidgetItem* getItem(const std::vector<std::string>& path, QTreeWidgetItem* parent); protected: QWidget* m_area; QVBoxLayout* m_vBox; QLabel* m_labelWidget; QTreeWidget* m_tree; }; } // Property } // GUI #endif /* QT5TREE_H_ */
[ "me@sicgraph.org" ]
me@sicgraph.org
8011abbbbbcfbec483c28355afb0c4edb0ea419a
092e98a6e217e42ecc1137e9f9c455de23da2fdc
/02 SD Card/03_Read_Available/03_Read_Available.ino
bda953e5a3acc165725e700524848233bbc95c8e
[]
no_license
josiahthinklab/imakewemake2019
518da7dbc846c64b67a09db9bbc2ded421fdfa35
fb7eecfb4bee353527e8eb9be1ce0fcfc2f1ecb2
refs/heads/master
2020-07-23T19:14:06.389838
2019-09-11T20:07:34
2019-09-11T20:07:34
207,679,320
0
0
null
null
null
null
UTF-8
C++
false
false
814
ino
#include <SD.h> #include <SPI.h> #define FILEPATH "test.txt" #define PIN_SD_CS 10 File myFile; void setup() { Serial.begin(9600); pinMode(PIN_SD_CS, OUTPUT); // SD CARD INITIALIZATION if (SD.begin(PIN_SD_CS)) { Serial.println("SD card is ready to use."); } else { Serial.println("SD card initialization failed"); return; } // READING THE FILE myFile = SD.open(FILEPATH); if (myFile) { while (myFile.available()) { int numBytesLeft = myFile.available(); char c = myFile.read(); Serial.print(numBytesLeft); Serial.print("\t"); Serial.print(c); Serial.print("\t"); Serial.println(int(c)); } myFile.close(); } else { Serial.println("error opening test.txt"); } } void loop() { // Do nothing }
[ "josiah@thinklab.ph" ]
josiah@thinklab.ph
e8156d4963e4e1a557c0e421a2ea96158fb38174
c075cfe521103977789d600b61ad05b605f4fb10
/div 231/ZAD_B.cpp
9140e08e3c6ede60d44f05769adf55d147bf59e7
[]
no_license
igoroogle/codeforces
dd3c99b6a5ceb19d7d9495b370d4b2ef8949f534
579cd1d2aa30a0b0b4cc61d104a02499c69ac152
refs/heads/master
2020-07-20T12:37:07.225539
2019-09-05T19:21:27
2019-09-05T19:35:26
206,639,451
0
0
null
null
null
null
UTF-8
C++
false
false
1,067
cpp
#include <string> #include <algorithm> #include <cstdio> #include <iostream> using namespace std; typedef long long ll; char s[1000002], s1[1000002]; int main() { int p, x, i, j, ost, val; cin >> p >> x; for (i = 0; i < 1000002; i++) { s[i] = '\0'; s1[i] = '\0'; } s[0] = '$'; for (j = 0; j <= 9; j++) { val = j; ost = 0; s1[0] = '$'; for (i = 0; i < p; i++) { s1[i] = char(val + '0'); val = val * x + ost; if (val > 99) { s1[0] = '$'; break; } ost = val / 10; val = val % 10; } reverse(s1, s1 + p); if ((s1[0] != '$') && (s1[0] != '0') && (ost == 0) && (val == j) && ((s[0] == '$') || (s1 < s))) for (i = 0; i < p; i++) s[i] = s1[i]; } if (s[0] == '$') cout << "Impossible\n"; else { for (i = 0; i < p; i++) printf("%c", s[i]); } return 0; }
[ "160698qnigor98" ]
160698qnigor98
7b1abbe0152fe43eb3272828512b15d2ec7d6658
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2463486_0/C++/frag/3.cpp
c1ed012ac96abd971eb2c27545c9cf88efb19a66
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
833
cpp
#include<iostream> #include<cstdio> #include<cmath> using namespace std; long long ans[44]={1,4,9,121,484,10201,12321,14641,40804,44944,1002001,1234321,4008004,100020001,102030201,104060401,121242121,123454321,125686521,400080004,404090404,10000200001,10221412201,12102420121,12345654321,40000800004,1000002000001,1002003002001,1004006004001,1020304030201,1022325232201,1024348434201,1210024200121,1212225222121,1214428244121,1232346432321,1234567654321,4000008000004,4004009004004}; long long l,r,cnt; void Doit() { for(long long i=0;i<=40;i++) if(ans[i]>=l&&ans[i]<=r) cnt++; } int main() { freopen("3.in","r",stdin); freopen("3.out","w",stdout); int k; scanf("%d",&k); for(int i=1;i<=k;i++) { scanf("%I64d%I64d",&l,&r); cnt=0; Doit(); printf("Case #%d: %d\n",i,cnt); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
0290365fecb4d87d3f3529f740c0412fab941850
8089be715a10455b50edb5a282cde86e15713f28
/include/UnitIndicator.hpp
d8ecca8325bc3d5d12d0c79b9f8a95ac888eeff1
[]
no_license
WoodenBrickProductions/RTGBcpp
7cfa3c7ddf71fb366c9cfbf1a9f81c4d66c00eb2
2d4e668f179d3177c60fbb9fb2105958355e863f
refs/heads/main
2023-08-26T00:43:53.819685
2021-10-28T12:48:42
2021-10-28T12:48:42
396,448,263
0
0
null
null
null
null
UTF-8
C++
false
false
540
hpp
#ifndef UNITINDICATOR_HPP #define UNITINDICATOR_HPP #include "GameObject.hpp" class UnitController; class UnitIndicator : public GameObject { public: const float maxSize = 0.30f; UnitIndicator(); virtual ~UnitIndicator() = default; virtual void Start(GameObject* scene, GameState* gameState) override; virtual void Update(GameObject* scene, GameState* gameState) override; virtual void Draw(); void LoadTextureUnIn(Texture2D* texture); protected: Texture2D* texture; UnitController* unit; }; #endif
[ "tautvisceponis@gmail.com" ]
tautvisceponis@gmail.com
52fa4411437e3e86efa041e0872e52c7caff7870
ab0ccba4574cbd645e09fffd66ea0da73ecead5a
/yaps/main.cpp
ba46798646b4e1fd328839538534874c928f2b63
[ "MIT" ]
permissive
alexeibs/YAPS
0f66f8d6a77e16e19cc0dbce70c45b9f0b698524
8fd57c7d8e7cb14aa03c3f67e57ca04a6a08c019
refs/heads/master
2016-09-05T22:42:20.618614
2014-04-21T18:44:47
2014-04-21T18:47:13
12,282,889
0
0
null
null
null
null
UTF-8
C++
false
false
2,597
cpp
#include <QApplication> #include <QScopedPointer> #include <QSharedMemory> #include <QAbstractItemView> #include <QFile> #include <QTranslator> #include <QJsonDocument> #include <QJsonObject> #include <QJsonObject> #include "mainwindow.h" #include "MainActions.h" #include "Database.h" #include "Crypto.h" #define YAPS_ID "YAPS-6d049d5f-2a4a-4910-8713-249dacbbd700" static QSharedMemory* createSharedMemory(); static void setupTranslations(); static QJsonDocument loadConfig(); static QString getDatabasePath(const QJsonDocument&); int main(int argc, char *argv[]) { QApplication application(argc, argv); QScopedPointer<QSharedMemory> singleAppGuard(createSharedMemory()); if (!singleAppGuard) return 0; application.setApplicationName("YAPS"); application.setWindowIcon(QIcon(":/icons/app")); setupTranslations(); if (!Crypto::instance()) return 2; QJsonDocument config = loadConfig(); if (!setupDatabase(getDatabasePath(config))) return 1; MainWindow mainWindow; // MainWindow should be created before first call Actions::instance auto& actions = Actions::instance(); actions.initialize(); mainWindow.setMainWidget(actions.view()); mainWindow.toggleWindow(); return application.exec(); } QSharedMemory *createSharedMemory() { QScopedPointer<QSharedMemory> shared(new QSharedMemory(YAPS_ID)); if (shared->attach()) return nullptr; if (!shared->create(1)) return nullptr; return shared.take(); } static void loadTranslation(const QString& translation) { if (QFile::exists(translation)) { QTranslator* translator = new QTranslator; translator->load(translation); QApplication::installTranslator(translator); } } void setupTranslations() { QString locale = QLocale::system().name(); loadTranslation(":/tr/" + QLocale::system().name() + ".qm"); loadTranslation(":/tr/qtbase_" + QLocale::system().name() + ".qm"); } static QJsonDocument loadConfig() { QJsonDocument config; QFile configFile("yaps.json"); if (configFile.open(QIODevice::ReadOnly)) config = QJsonDocument::fromJson(configFile.readAll()); return config; } static QString getDatabasePath(const QJsonDocument& config) { QString path = "yaps.db"; if (!config.isObject()) return path; auto root = config.object(); if (root.contains("database")) path = root.value("database").toString(path); return path; }
[ "alexei4203@yandex.ru" ]
alexei4203@yandex.ru
c956eeb998569a146321a04511b90e4c03db7008
6b580bb5e7bbf83e0d9845818678fbb85ea14450
/aws-cpp-sdk-ec2/include/aws/ec2/model/PeeringTgwInfo.h
4013b4506df1b2561f7fe883b9d104a3d4785cb8
[ "MIT", "Apache-2.0", "JSON" ]
permissive
dimatd/aws-sdk-cpp
870634473781731822e2636005bc215ad43a0339
3d3f3d0f98af842e06d3d74648a0fca383538bb3
refs/heads/master
2022-12-21T20:54:25.033076
2022-12-13T18:18:00
2022-12-13T18:18:00
219,980,346
0
0
Apache-2.0
2019-11-06T11:23:20
2019-11-06T11:23:20
null
UTF-8
C++
false
false
5,630
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/ec2/EC2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace EC2 { namespace Model { /** * <p>Information about the transit gateway in the peering * attachment.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/PeeringTgwInfo">AWS * API Reference</a></p> */ class AWS_EC2_API PeeringTgwInfo { public: PeeringTgwInfo(); PeeringTgwInfo(const Aws::Utils::Xml::XmlNode& xmlNode); PeeringTgwInfo& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; void OutputToStream(Aws::OStream& oStream, const char* location) const; /** * <p>The ID of the transit gateway.</p> */ inline const Aws::String& GetTransitGatewayId() const{ return m_transitGatewayId; } /** * <p>The ID of the transit gateway.</p> */ inline bool TransitGatewayIdHasBeenSet() const { return m_transitGatewayIdHasBeenSet; } /** * <p>The ID of the transit gateway.</p> */ inline void SetTransitGatewayId(const Aws::String& value) { m_transitGatewayIdHasBeenSet = true; m_transitGatewayId = value; } /** * <p>The ID of the transit gateway.</p> */ inline void SetTransitGatewayId(Aws::String&& value) { m_transitGatewayIdHasBeenSet = true; m_transitGatewayId = std::move(value); } /** * <p>The ID of the transit gateway.</p> */ inline void SetTransitGatewayId(const char* value) { m_transitGatewayIdHasBeenSet = true; m_transitGatewayId.assign(value); } /** * <p>The ID of the transit gateway.</p> */ inline PeeringTgwInfo& WithTransitGatewayId(const Aws::String& value) { SetTransitGatewayId(value); return *this;} /** * <p>The ID of the transit gateway.</p> */ inline PeeringTgwInfo& WithTransitGatewayId(Aws::String&& value) { SetTransitGatewayId(std::move(value)); return *this;} /** * <p>The ID of the transit gateway.</p> */ inline PeeringTgwInfo& WithTransitGatewayId(const char* value) { SetTransitGatewayId(value); return *this;} /** * <p>The ID of the Amazon Web Services account that owns the transit gateway.</p> */ inline const Aws::String& GetOwnerId() const{ return m_ownerId; } /** * <p>The ID of the Amazon Web Services account that owns the transit gateway.</p> */ inline bool OwnerIdHasBeenSet() const { return m_ownerIdHasBeenSet; } /** * <p>The ID of the Amazon Web Services account that owns the transit gateway.</p> */ inline void SetOwnerId(const Aws::String& value) { m_ownerIdHasBeenSet = true; m_ownerId = value; } /** * <p>The ID of the Amazon Web Services account that owns the transit gateway.</p> */ inline void SetOwnerId(Aws::String&& value) { m_ownerIdHasBeenSet = true; m_ownerId = std::move(value); } /** * <p>The ID of the Amazon Web Services account that owns the transit gateway.</p> */ inline void SetOwnerId(const char* value) { m_ownerIdHasBeenSet = true; m_ownerId.assign(value); } /** * <p>The ID of the Amazon Web Services account that owns the transit gateway.</p> */ inline PeeringTgwInfo& WithOwnerId(const Aws::String& value) { SetOwnerId(value); return *this;} /** * <p>The ID of the Amazon Web Services account that owns the transit gateway.</p> */ inline PeeringTgwInfo& WithOwnerId(Aws::String&& value) { SetOwnerId(std::move(value)); return *this;} /** * <p>The ID of the Amazon Web Services account that owns the transit gateway.</p> */ inline PeeringTgwInfo& WithOwnerId(const char* value) { SetOwnerId(value); return *this;} /** * <p>The Region of the transit gateway.</p> */ inline const Aws::String& GetRegion() const{ return m_region; } /** * <p>The Region of the transit gateway.</p> */ inline bool RegionHasBeenSet() const { return m_regionHasBeenSet; } /** * <p>The Region of the transit gateway.</p> */ inline void SetRegion(const Aws::String& value) { m_regionHasBeenSet = true; m_region = value; } /** * <p>The Region of the transit gateway.</p> */ inline void SetRegion(Aws::String&& value) { m_regionHasBeenSet = true; m_region = std::move(value); } /** * <p>The Region of the transit gateway.</p> */ inline void SetRegion(const char* value) { m_regionHasBeenSet = true; m_region.assign(value); } /** * <p>The Region of the transit gateway.</p> */ inline PeeringTgwInfo& WithRegion(const Aws::String& value) { SetRegion(value); return *this;} /** * <p>The Region of the transit gateway.</p> */ inline PeeringTgwInfo& WithRegion(Aws::String&& value) { SetRegion(std::move(value)); return *this;} /** * <p>The Region of the transit gateway.</p> */ inline PeeringTgwInfo& WithRegion(const char* value) { SetRegion(value); return *this;} private: Aws::String m_transitGatewayId; bool m_transitGatewayIdHasBeenSet; Aws::String m_ownerId; bool m_ownerIdHasBeenSet; Aws::String m_region; bool m_regionHasBeenSet; }; } // namespace Model } // namespace EC2 } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
a947b64a844b88cdcd86e4aba4e42b281e821f65
9a78e69e2b72e7fec0bc9b6b5d34934443291501
/PIC10A_Introduction_to_Programming_TA/future_lessons/demo09_class_basics/Cat.h
f60b899b31f46f08c5ec04bced2aa923bb4defb2
[]
no_license
evastgh/ps
b60623629d85951c1951421481a7e99728d7ba0c
2b4d3d04573e2940efca0fc959783ec7b95a9255
refs/heads/master
2022-10-27T19:01:57.684281
2020-06-19T05:16:57
2020-06-19T05:16:57
79,401,284
2
1
null
null
null
null
UTF-8
C++
false
false
434
h
#ifndef __CAT__ #define __CAT__ #include<string> class Cat { public: std::string breed; int age; /** Default constructor */ Cat(); /** function that returns cat meow @return the string "meow" */ // std::string talk() const; std::string talk(int number); int getAge(); std::string getBreed(); /** function that sets the breed * @param breed_in */ void setBreed(std::string breed_in); }; #endif
[ "7941538+evastgh@users.noreply.github.com" ]
7941538+evastgh@users.noreply.github.com
f251ecfa3fbe9277b0ce93453b546a8a5bf72f2a
98b1e51f55fe389379b0db00365402359309186a
/homework_6/problem_2/100x100/system/blockMeshDict
3051f0f830502be1600f62c3a93edddc23a9f217
[]
no_license
taddyb/597-009
f14c0e75a03ae2fd741905c4c0bc92440d10adda
5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927
refs/heads/main
2023-01-23T08:14:47.028429
2020-12-03T13:24:27
2020-12-03T13:24:27
311,713,551
1
0
null
null
null
null
UTF-8
C++
false
false
1,620
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 5.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; object blockMeshDict; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // convertToMeters 1; vertices ( (0 0 0) (1 0 0) (1 1 0) (0 1 0) (0 0 0.01) (1 0 0.01) (1 1 0.01) (0 1 0.01) ); blocks ( hex (0 1 2 3 4 5 6 7) (100 100 1) simpleGrading (1 1 1) ); edges ( ); boundary ( left { type patch; faces ( (0 4 7 3) ); } right { type patch; faces ( (2 6 5 1) ); } up { type wall; faces ( (2 3 7 6) ); } down { type wall; faces ( (0 1 5 4) ); } frontAndBack { type empty; faces ( (0 1 2 3) (4 5 6 7) ); } ); mergePatchPairs ( ); // ************************************************************************* //
[ "tbindas@pop-os.localdomain" ]
tbindas@pop-os.localdomain
10ad18630c92728c7ffff3e74023481ba39f933b
d6d4e9dda8fa6ac9f66d124db465121e5a287e0f
/includes/auxiliary/shader.h
5ea7326716889d0b68b871ca23658242afe7efcb
[]
no_license
IlyaZadyabin/OpenGL
35bff1458c8ce7bdccbb5317f7131b29e95406a8
dfaf9bac0426aef98edab64e419e416e8635094c
refs/heads/master
2023-02-06T04:27:07.883544
2020-12-26T13:23:17
2020-12-26T13:23:17
312,682,295
1
0
null
null
null
null
UTF-8
C++
false
false
6,561
h
#ifndef SHADER_H #define SHADER_H #include <glad/glad.h> #include <glm/glm.hpp> #include <string> #include <fstream> #include <sstream> #include <iostream> class Shader { public: unsigned int ID; // constructor generates the shader Shader() = default; Shader(const char* vertexPath, const char* fragmentPath, const char* geometryPath = nullptr) { //retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::string geometryCode; std::ifstream vShaderFile; std::ifstream fShaderFile; std::ifstream gShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); gShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit); try { // open files vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // read each file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); // if geometry shader path is present, also load a geometry shader if(geometryPath != nullptr) { gShaderFile.open(geometryPath); std::stringstream gShaderStream; gShaderStream << gShaderFile.rdbuf(); gShaderFile.close(); geometryCode = gShaderStream.str(); } } catch (std::ifstream::failure& e) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << e.what() << std::endl; } const char* vShaderCode = vertexCode.c_str(); const char * fShaderCode = fragmentCode.c_str(); //compile shaders unsigned int vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, nullptr); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, nullptr); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); // if geometry shader is given, compile geometry shader unsigned int geometry = 0; if (geometryPath != nullptr) { const char * gShaderCode = geometryCode.c_str(); geometry = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(geometry, 1, &gShaderCode, nullptr); glCompileShader(geometry); checkCompileErrors(geometry, "GEOMETRY"); } // shader Program ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); if (geometryPath != nullptr) glAttachShader(ID, geometry); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessery glDeleteShader(vertex); glDeleteShader(fragment); if(geometryPath != nullptr) glDeleteShader(geometry); } // activate the shader void use() const { glUseProgram(ID); } // uniform functions void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } void setVec2(const std::string &name, const glm::vec2 &value) const { glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec2(const std::string &name, float x, float y) const { glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y); } void setVec3(const std::string &name, const glm::vec3 &value) const { glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec3(const std::string &name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z); } void setVec4(const std::string &name, const glm::vec4 &value) const { glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]); } void setVec4(const std::string &name, float x, float y, float z, float w) { glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w); } void setMat2(const std::string &name, const glm::mat2 &mat) const { glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } void setMat3(const std::string &name, const glm::mat3 &mat) const { glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } void setMat4(const std::string &name, const glm::mat4 &mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]); } private: // function for checking shader compilation/linking errors. static void checkCompileErrors(GLuint shader, const std::string& type) { GLint success; GLchar infoLog[1024]; if (type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, nullptr, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 1024, nullptr, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } }; #endif
[ "z.ilya.007@gmail.com" ]
z.ilya.007@gmail.com
8a652303876f28c286f1606ef4c643011a2284a3
24004e1c3b8005af26d5890091d3c207427a799e
/Win32/NXOPEN/NXOpen/Annotations_TextWithSymbolsBuilder.hxx
f6a1022082fd01b3678178c3051e5865ebb718e0
[]
no_license
15831944/PHStart
068ca6f86b736a9cc857d7db391b2f20d2f52ba9
f79280bca2ec7e5f344067ead05f98b7d592ae39
refs/heads/master
2022-02-20T04:07:46.994182
2019-09-29T06:15:37
2019-09-29T06:15:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,217
hxx
#ifndef NXOpen_ANNOTATIONS_TEXTWITHSYMBOLSBUILDER_HXX_INCLUDED #define NXOpen_ANNOTATIONS_TEXTWITHSYMBOLSBUILDER_HXX_INCLUDED //-------------------------------------------------------------------------- // Header for C++ interface to JA API //-------------------------------------------------------------------------- // // Source File: // Annotations_TextWithSymbolsBuilder.ja // // Generated by: // apiwrap // // WARNING: // This file is automatically generated - do not edit by hand // #ifdef _MSC_VER #pragma once #endif #include <NXOpen/NXDeprecation.hxx> #include <vector> #include <NXOpen/NXString.hxx> #include <NXOpen/Callback.hxx> #include <NXOpen/Annotations_TextWithSymbolsBuilder.hxx> #include <NXOpen/GeometricUtilities_IComponentBuilder.hxx> #include <NXOpen/TaggedObject.hxx> #include <NXOpen/libnxopencpp_annotations_exports.hxx> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif namespace NXOpen { namespace Annotations { class TextWithSymbolsBuilder; } namespace GeometricUtilities { class IComponentBuilder; } class NXObject; namespace Annotations { class _TextWithSymbolsBuilderBuilder; class TextWithSymbolsBuilderImpl; /** Represents a @link Annotations::TextWithSymbolsBuilder Annotations::TextWithSymbolsBuilder@endlink which collects internationalized text strings from the user for processing on an annotation object. <br> This is a sub-builder class and cannot be directly instantiated <br> <br> Created in NX6.0.0. <br> */ class NXOPENCPP_ANNOTATIONSEXPORT TextWithSymbolsBuilder : public TaggedObject, public virtual GeometricUtilities::IComponentBuilder { /** sizing method for embedded user-defined symbols */ public: enum SymbolSizingMethod { SymbolSizingMethodScaleAndAspectRatio/** Size using scale and aspect ratio */, SymbolSizingMethodLengthAndHeight/** Size using length and height */ }; /** Enum for the symbol preferences */ public: enum SymbolPreferencesType { SymbolPreferencesTypeUseCurrent/** Use Current*/, SymbolPreferencesTypeUseDefinition/** Use Definition*/ }; private: TextWithSymbolsBuilderImpl * m_textwithsymbolsbuilder_impl; private: friend class _TextWithSymbolsBuilderBuilder; protected: TextWithSymbolsBuilder(); public: ~TextWithSymbolsBuilder(); /** Returns the text of the annotation @return <br> Created in NX6.0.0. <br> <br> License requirements : None */ public: std::vector<NXString> GetText ( ); /** Sets the text of the annotation <br> Created in NX6.0.0. <br> <br> License requirements : drafting ("DRAFTING") OR geometric_tol ("GDT") */ public: void SetText ( const std::vector<NXString> & text /** text */ ); /**Returns the method in which embedded user-defined symbols are scaled <br> Created in NX6.0.0. <br> <br> License requirements : None */ public: NXOpen::Annotations::TextWithSymbolsBuilder::SymbolSizingMethod SymbolSizeMethod ( ); /**Sets the method in which embedded user-defined symbols are scaled <br> Created in NX6.0.0. <br> <br> License requirements : drafting ("DRAFTING") OR geometric_tol ("GDT") */ public: void SetSymbolSizeMethod ( NXOpen::Annotations::TextWithSymbolsBuilder::SymbolSizingMethod symbolSizeMethod /** symbolsizemethod */ ); /**Returns the scale of the embedded user-defined symbols if the symbol size method is @link Annotations::TextWithSymbolsBuilder::SymbolSizingMethodScaleAndAspectRatio Annotations::TextWithSymbolsBuilder::SymbolSizingMethodScaleAndAspectRatio@endlink <br> Created in NX6.0.0. <br> <br> License requirements : None */ public: double SymbolScale ( ); /**Sets the scale of the embedded user-defined symbols if the symbol size method is @link Annotations::TextWithSymbolsBuilder::SymbolSizingMethodScaleAndAspectRatio Annotations::TextWithSymbolsBuilder::SymbolSizingMethodScaleAndAspectRatio@endlink <br> Created in NX6.0.0. <br> <br> License requirements : drafting ("DRAFTING") OR geometric_tol ("GDT") */ public: void SetSymbolScale ( double symbolScale /** symbolscale */ ); /**Returns the aspect ratio of the embedded user-defined symbols if the symbol size method is @link Annotations::TextWithSymbolsBuilder::SymbolSizingMethodScaleAndAspectRatio Annotations::TextWithSymbolsBuilder::SymbolSizingMethodScaleAndAspectRatio@endlink <br> Created in NX6.0.0. <br> <br> License requirements : None */ public: double SymbolAspectRatio ( ); /**Sets the aspect ratio of the embedded user-defined symbols if the symbol size method is @link Annotations::TextWithSymbolsBuilder::SymbolSizingMethodScaleAndAspectRatio Annotations::TextWithSymbolsBuilder::SymbolSizingMethodScaleAndAspectRatio@endlink <br> Created in NX6.0.0. <br> <br> License requirements : drafting ("DRAFTING") OR geometric_tol ("GDT") */ public: void SetSymbolAspectRatio ( double symbolAspectRatio /** symbolaspectratio */ ); /**Returns the length of the embedded user-defined symbols if the symbol size method is @link Annotations::TextWithSymbolsBuilder::SymbolSizingMethodLengthAndHeight Annotations::TextWithSymbolsBuilder::SymbolSizingMethodLengthAndHeight@endlink <br> Created in NX6.0.0. <br> <br> License requirements : None */ public: double SymbolLength ( ); /**Sets the length of the embedded user-defined symbols if the symbol size method is @link Annotations::TextWithSymbolsBuilder::SymbolSizingMethodLengthAndHeight Annotations::TextWithSymbolsBuilder::SymbolSizingMethodLengthAndHeight@endlink <br> Created in NX6.0.0. <br> <br> License requirements : drafting ("DRAFTING") OR geometric_tol ("GDT") */ public: void SetSymbolLength ( double symbolLength /** symbollength */ ); /**Returns the height of the embedded user-defined symbols if the symbol size method is @link Annotations::TextWithSymbolsBuilder::SymbolSizingMethodLengthAndHeight Annotations::TextWithSymbolsBuilder::SymbolSizingMethodLengthAndHeight@endlink <br> Created in NX6.0.0. <br> <br> License requirements : None */ public: double SymbolHeight ( ); /**Sets the height of the embedded user-defined symbols if the symbol size method is @link Annotations::TextWithSymbolsBuilder::SymbolSizingMethodLengthAndHeight Annotations::TextWithSymbolsBuilder::SymbolSizingMethodLengthAndHeight@endlink <br> Created in NX6.0.0. <br> <br> License requirements : drafting ("DRAFTING") OR geometric_tol ("GDT") */ public: void SetSymbolHeight ( double symbolHeight /** symbolheight */ ); /**Returns the scale of the custom symbols <br> Created in NX7.5.0. <br> <br> License requirements : None */ public: double CustomSymbolScale ( ); /**Sets the scale of the custom symbols <br> Created in NX7.5.0. <br> <br> License requirements : drafting ("DRAFTING") OR geometric_tol ("GDT") */ public: void SetCustomSymbolScale ( double customSymbolScale /** customsymbolscale */ ); /** Adds a symbol <br> Created in NX7.0.0. <br> <br> License requirements : drafting ("DRAFTING") */ public: void AddSymbol ( NXOpen::NXObject * newObject /** symbol instance object */, const NXString & name /** symbol name */, int lineNo /** line number to insert token with index from 1 */, int cursorPos /** cursor position in the line with index from 1 */ ); /** Adds a symbol <br> Created in NX7.0.0. <br> <br> License requirements : drafting ("DRAFTING") */ void AddSymbol ( NXOpen::NXObject * newObject /** symbol instance object */, const char * name /** symbol name */, int lineNo /** line number to insert token with index from 1 */, int cursorPos /** cursor position in the line with index from 1 */ ); /** Removes specified symbol <br> Created in NX7.0.0. <br> <br> License requirements : drafting ("DRAFTING") */ public: void RemoveSymbol ( const NXString & path /** Symbol name */ ); /** Removes specified symbol <br> Created in NX7.0.0. <br> <br> License requirements : drafting ("DRAFTING") */ void RemoveSymbol ( const char * path /** Symbol name */ ); /**Returns the symbol preferences <br> Created in NX8.0.0. <br> <br> License requirements : None */ public: NXOpen::Annotations::TextWithSymbolsBuilder::SymbolPreferencesType SymbolPreferences ( ); /**Sets the symbol preferences <br> Created in NX8.0.0. <br> <br> License requirements : drafting ("DRAFTING") */ public: void SetSymbolPreferences ( NXOpen::Annotations::TextWithSymbolsBuilder::SymbolPreferencesType symbolPreferences /** symbolpreferences */ ); /** Adds an attribute reference <br> Created in NX8.0.0. <br> <br> License requirements : drafting ("DRAFTING") */ public: void AddAttributeReference ( NXOpen::NXObject * ownerTag /** object that owns the attribute. If we are trying to reference a part attribute then this should be the part object */, const NXString & title /** title of attribute */, bool displayTokens /** True to display using TC tokens. False to display as plain text. */, int lineNo /** line number to insert token with index from 1 */, int cursorPos /** cursor position in the line with index from 1 */ ); /** Adds an attribute reference <br> Created in NX8.0.0. <br> <br> License requirements : drafting ("DRAFTING") */ void AddAttributeReference ( NXOpen::NXObject * ownerTag /** object that owns the attribute. If we are trying to reference a part attribute then this should be the part object */, const char * title /** title of attribute */, bool displayTokens /** True to display using TC tokens. False to display as plain text. */, int lineNo /** line number to insert token with index from 1 */, int cursorPos /** cursor position in the line with index from 1 */ ); /** Adds an expression reference <br> Created in NX8.0.0. <br> <br> License requirements : drafting ("DRAFTING") */ public: void AddExpressionReference ( const NXString & expName /** expression name */, const NXString & format /** format to use for displaying an expression. 'A' for displaying the expression formula, or 'm.n' where 'm' is the minimum number of characters displayed and 'n' is the number of decimal places to display */, int lineNo /** line number to insert token with index from 1 */, int cursorPos /** cursor position in the line with index from 1 */ ); /** Adds an expression reference <br> Created in NX8.0.0. <br> <br> License requirements : drafting ("DRAFTING") */ void AddExpressionReference ( const char * expName /** expression name */, const char * format /** format to use for displaying an expression. 'A' for displaying the expression formula, or 'm.n' where 'm' is the minimum number of characters displayed and 'n' is the number of decimal places to display */, int lineNo /** line number to insert token with index from 1 */, int cursorPos /** cursor position in the line with index from 1 */ ); /** Validate whether the inputs to the component are sufficient for commit to be called. If the component is not in a state to commit then an exception is thrown. For example, if the component requires you to set some property, this method will throw an exception if you haven't set it. This method throws a not-yet-implemented NXException for some components. @return Was self validation successful <br> Created in NX3.0.1. <br> <br> License requirements : None */ public: virtual bool Validate ( ); }; } } #ifdef _MSC_VER #pragma warning(pop) #endif #ifdef __GNUC__ #ifndef NX_NO_GCC_DEPRECATION_WARNINGS #pragma GCC diagnostic warning "-Wdeprecated-declarations" #endif #endif #undef EXPORTLIBRARY #endif
[ "1075087594@qq.com" ]
1075087594@qq.com
43e4057a91f24414e403c0c63258522bd7ddd3df
ec87cc769d7c23990f637b906f59f9573a655cb5
/The eighth Homework/陈昱硕-2017201976/search_engine.h
9b334e3fa6f39e219afceb49fef6142ec65933c5
[]
no_license
hzy9819/Student-Code-RUC
94d6c5e9ef12a4b7dbf1c4ba9f5d95d7cb5b8fcd
64aa4bcf0a20c7090321c27d0233a2d1e6030004
refs/heads/master
2021-04-12T10:24:24.652470
2018-07-09T03:22:30
2018-07-09T03:22:30
126,282,794
0
0
null
2018-07-09T00:42:37
2018-03-22T05:10:18
C++
UTF-8
C++
false
false
1,477
h
#ifndef SEARCH_ENGINE_H #define SEARCH_ENGINE_H #include <string> #include "filter.h" #include "document.h" #include "index.h" #include "query.h" #include "search_result.h" class SearchEngine{ private: enum FlagStatus{ none = 000, plus_flag = 001, minus_flag = 002, and_flag = 004, or_flag = 010, xor_flag = 020 }; const std::string file_list_; Document doc_list_; Index title_index_, body_index_; void *segmentor_; Filter filter_; static void LoadFile(const size_t idx, const std::string &file_name, Index &index, const Filter &filter); static PostingList BasicAccurateSearch(const std::vector<Words> &query, const Index &idx); static void BasicRankedSearch(const std::vector<std::string> &words, const std::vector<double> &term_frequency, const Index &idx, std::vector<double> &final_scores, const double rate); PostingList AccurateSearch(const std::vector<Words> &query); PostingList RankedSearch(const std::vector<Words> &query); public: SearchEngine(const std::string &file_list = "file_list.txt", const std::string &stop_word = "stop_words.txt"); SearchResult Search(const Query &query, const size_t limits = 10); void Run(); ~SearchEngine() = default; }; #endif
[ "297086016@qq.com" ]
297086016@qq.com
25885270846d25200b21092d3c98495fc8b0c5f4
bfb71fe39958ad98dafd55d9683e0c99f21333aa
/src/util.h
b497c1ea10becc2ce727bd2cbf8b7ff46cdc5375
[ "MIT" ]
permissive
DUELIUM-CORE/DUELIUM2.0_unofficial
5c9f3ed86b4798bb79f5e518e15aa1d45e21d12c
1ccfab25717a70d3167fcd1877edb09c73ceb266
refs/heads/master
2020-04-17T07:02:04.557142
2019-02-17T00:55:34
2019-02-17T00:55:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,295
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * Server/client environment: argument handling, config file parsing, * logging, thread wrappers */ #ifndef BITCOIN_UTIL_H #define BITCOIN_UTIL_H #if defined(HAVE_CONFIG_H) #include "config/DUELIUM-config.h" #endif #include "compat.h" #include "tinyformat.h" #include "utiltime.h" #include <exception> #include <map> #include <stdint.h> #include <string> #include <vector> #include <boost/filesystem/path.hpp> #include <boost/thread/exceptions.hpp> //DUELIUM only features extern bool fMasterNode; extern bool fLiteMode; extern bool fEnableSwiftTX; extern int nSwiftTXDepth; extern int nZeromintPercentage; extern const int64_t AUTOMINT_DELAY; extern int nPreferredDenom; extern int nAnonymizeDUELIUMAmount; extern int nLiquidityProvider; extern bool fEnableZeromint; extern int64_t enforceMasternodePaymentsTime; extern std::string strMasterNodeAddr; extern int keysLoaded; extern bool fSucessfullyLoaded; extern std::vector<int64_t> obfuScationDenominations; extern std::string strBudgetMode; extern std::map<std::string, std::string> mapArgs; extern std::map<std::string, std::vector<std::string> > mapMultiArgs; extern bool fDebug; extern bool fPrintToConsole; extern bool fPrintToDebugLog; extern bool fServer; extern std::string strMiscWarning; extern bool fLogTimestamps; extern bool fLogIPs; extern volatile bool fReopenDebugLog; void SetupEnvironment(); bool SetupNetworking(); /** Return true if log accepts specified category */ bool LogAcceptCategory(const char* category); /** Send a string to the log output */ int LogPrintStr(const std::string& str); #define LogPrintf(...) LogPrint(NULL, __VA_ARGS__) /** * When we switch to C++11, this can be switched to variadic templates instead * of this macro-based construction (see tinyformat.h). */ #define MAKE_ERROR_AND_LOG_FUNC(n) \ /** Print to debug.log if -debug=category switch is given OR category is NULL. */ \ template <TINYFORMAT_ARGTYPES(n)> \ static inline int LogPrint(const char* category, const char* format, TINYFORMAT_VARARGS(n)) \ { \ if (!LogAcceptCategory(category)) return 0; \ return LogPrintStr(tfm::format(format, TINYFORMAT_PASSARGS(n))); \ } \ /** Log error and return false */ \ template <TINYFORMAT_ARGTYPES(n)> \ static inline bool error(const char* format, TINYFORMAT_VARARGS(n)) \ { \ LogPrintStr(std::string("ERROR: ") + tfm::format(format, TINYFORMAT_PASSARGS(n)) + "\n"); \ return false; \ } TINYFORMAT_FOREACH_ARGNUM(MAKE_ERROR_AND_LOG_FUNC) /** * Zero-arg versions of logging and error, these are not covered by * TINYFORMAT_FOREACH_ARGNUM */ static inline int LogPrint(const char* category, const char* format) { if (!LogAcceptCategory(category)) return 0; return LogPrintStr(format); } static inline bool error(const char* format) { LogPrintStr(std::string("ERROR: ") + format + "\n"); return false; } double double_safe_addition(double fValue, double fIncrement); double double_safe_multiplication(double fValue, double fmultiplicator); void PrintExceptionContinue(std::exception* pex, const char* pszThread); void ParseParameters(int argc, const char* const argv[]); void FileCommit(FILE* fileout); bool TruncateFile(FILE* file, unsigned int length); int RaiseFileDescriptorLimit(int nMinFD); void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length); bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest); bool TryCreateDirectory(const boost::filesystem::path& p); boost::filesystem::path GetDefaultDataDir(); const boost::filesystem::path& GetDataDir(bool fNetSpecific = true); boost::filesystem::path GetConfigFile(); boost::filesystem::path GetMasternodeConfigFile(); #ifndef WIN32 boost::filesystem::path GetPidFile(); void CreatePidFile(const boost::filesystem::path& path, pid_t pid); #endif void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet); #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif boost::filesystem::path GetTempPath(); void ShrinkDebugFile(); void runCommand(std::string strCommand); inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault); /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64_t GetArg(const std::string& strArg, int64_t nDefault); /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault); /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); /** * Format a string to be used as group of options in help messages * * @param message Group name (e.g. "RPC server options:") * @return the formatted string */ std::string HelpMessageGroup(const std::string& message); /** * Format a string to be used as option description in help messages * * @param option Option message (e.g. "-rpcuser=<user>") * @param message Option description (e.g. "Username for JSON-RPC connections") * @return the formatted string */ std::string HelpMessageOpt(const std::string& option, const std::string& message); void SetThreadPriority(int nPriority); void RenameThread(const char* name); /** * .. and a wrapper that just calls func once */ template <typename Callable> void TraceThread(const char* name, Callable func) { std::string s = strprintf("DUELIUM-%s", name); RenameThread(s.c_str()); try { LogPrintf("%s thread start\n", name); func(); LogPrintf("%s thread exit\n", name); } catch (boost::thread_interrupted) { LogPrintf("%s thread interrupt\n", name); throw; } catch (std::exception& e) { PrintExceptionContinue(&e, name); throw; } catch (...) { PrintExceptionContinue(NULL, name); throw; } } /** Parse number as fixed point according to JSON number syntax. * See http://json.org/number.gif * @returns true on success, false on error. * @note The result must be in the range (-10^18,10^18), otherwise an overflow error will trigger. */ bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out); #endif // BITCOIN_UTIL_H
[ "noreply@github.com" ]
noreply@github.com
f8c4868174dd60ba4460657d6e0ef8b705cc10b0
c22ee7cc5972e0ac9c586e94ebea261c5eb412a0
/3.0/m_joinpartsno.cpp
43d6e46f80408e26ff7c004fbc0d3ca25a4404f4
[]
no_license
bhyvex/inspircd-extras
d46d2556810d390e875e501e702cb2cc5781ae69
07de5e0210037ac3a3fe8f7a7639e5fcd232a18a
refs/heads/master
2020-05-21T01:41:20.646610
2019-05-06T02:15:39
2019-05-06T09:33:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,781
cpp
/* * InspIRCd -- Internet Relay Chat Daemon * * Copyright (C) 2012 Shawn Smith <ShawnSmith0828@gmail.com> * * This file is part of InspIRCd. InspIRCd 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, version 2. * * 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 "inspircd.h" /// $ModAuthor: Shawn Smith /// $ModDesc: Sends server notices when a user joins/parts a channel. /// $ModDepends: core 3.0 class ModuleJoinPartSNO : public Module { public: void init() CXX11_OVERRIDE { ServerInstance->SNO->EnableSnomask('e', "JOIN"); ServerInstance->SNO->EnableSnomask('p', "PART"); } Version GetVersion() CXX11_OVERRIDE { return Version("Creates SNOMask for user joins/parts"); } void OnUserJoin(Membership* memb, bool sync, bool created, CUList& except) CXX11_OVERRIDE { /* If it's a local user do e, else E. */ ServerInstance->SNO->WriteToSnoMask((IS_LOCAL(memb->user) ? 'e' : 'E'), "User %s joined %s", memb->user->GetFullRealHost().c_str(), memb->chan->name.c_str()); } void OnUserPart(Membership* memb, std::string& partmessage, CUList& except) CXX11_OVERRIDE { ServerInstance->SNO->WriteToSnoMask((IS_LOCAL(memb->user) ? 'p' : 'P'), "User %s parted %s", memb->user->GetFullRealHost().c_str(), memb->chan->name.c_str()); } }; MODULE_INIT(ModuleJoinPartSNO)
[ "petpow@saberuk.com" ]
petpow@saberuk.com
2463de95270efa2ac6659ebd76ad2ace1c92cf95
b348b4e4eaed363ff5dd50c7b141dbf487e30b34
/src/task/tmp/retinanet.cpp
95279c1e60b0dc30ec9a3e8c8eec43bb6b24d105
[ "Apache-2.0" ]
permissive
seeker1943/cheetahinfer
265cc79c28effd93710a48a62eea6fa3c520a769
777d144024fe3f815859af3b21379586578083b4
refs/heads/master
2022-11-01T20:54:53.130442
2020-06-09T10:08:39
2020-06-09T10:08:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,558
cpp
#include <iostream> #include <cstdlib> #include <fstream> //#include <sstream> #include <string> #include <cmath> #include <opencv2/opencv.hpp> #include <NvInfer.h> #include <NvOnnxConfig.h> #include <cuda_runtime_api.h> #include "trtcommon/argsParser.h" #include "trtcommon/buffers.h" #include "trtcommon/logger.h" #include "timer.h" #include "task/retinanet.h" #include "plugin/decode_plugin.h" #include "plugin/nms_plugin.h" namespace cheetahinfer{ bool RetinaNet::build(bool isFromOnnx) { if(isFromOnnx) { buildFromOnnx(); } else { buildFromPlan(); } //for(int ii=0; ii<mEngine->getNbBindings(); ii++) //{ // auto mOutputDims = mEngine->getBindingDimensions(ii); // std::cout<<" Engine:mOutputDims "<<ii<<" "<<mOutputDims.nbDims<<" "<<mOutputDims.d[0]<<" "<<mOutputDims.d[1]<<" "<<mOutputDims.d[2]<<std::endl; //} if (!mEngine) { return false; } return true; } bool RetinaNet::buildFromOnnx() { auto builder = SampleUniquePtr<nvinfer1::IBuilder>(nvinfer1::createInferBuilder(gLogger.getTRTLogger())); if (!builder) { return false; } auto network = SampleUniquePtr<nvinfer1::INetworkDefinition>(builder->createNetwork()); if (!network) { return false; } auto config = SampleUniquePtr<nvinfer1::IBuilderConfig>(builder->createBuilderConfig()); if (!config) { return false; } auto parser = SampleUniquePtr<nvonnxparser::IParser>(nvonnxparser::createParser(*network, gLogger.getTRTLogger())); if (!parser) { return false; } auto constructed = constructNetwork(builder, network, config, parser); if (!constructed) { return false; } network->getInput(0)->setDimensions(mParams.input_dims); assert(network->getNbInputs() == 1); mInputDims = network->getInput(0)->getDimensions(); //std::cout<<"tdims"<<tdims.d[0]<<" "<<tdims.d[1]<<" "<<tdims.d[2]<<std::endl; //std::cout<<"mInputDims"<<mInputDims.d[0]<<" "<<mInputDims.d[1]<<" "<<mInputDims.d[2]<<std::endl; assert(mInputDims.nbDims == 3); assert(network->getNbOutputs() == 10); /* for(int i=0; i<10; i++) { nvinfer1::Dims mOutputDims = network->getOutput(i)->getDimensions(); std::cout<<i<<" mOutputDims"<<" "<<mOutputDims.nbDims<<" "<<mOutputDims.d[0]<<" "<<mOutputDims.d[1]<<" "<<mOutputDims.d[2]<<std::endl; assert(mOutputDims.nbDims == 3); mOutputDimsVec.push_back(mOutputDims); } */ // PULUGIN STARTS // Add decode plugins //std::cout << "Building accelerated plugins..." << std::endl; std::vector<nvinfer1::ITensor *> scores, boxes, classes; int nbOutputs = network->getNbOutputs(); //int nbOutputs = mParams.outputTensorNames.size(); //assert(nbOutputs == netNbOutputs); for (int i = 0; i < nbOutputs / 2; i++) { auto classOutput = network->getOutput(2 * i); std::cout << classOutput->getName() << std::endl; auto boxOutput = network->getOutput(2 * i + 1); auto outputDims = classOutput->getDimensions(); int scale = mInputDims.d[2] / outputDims.d[2]; //cout << "scale " << scale << " anchors " << endl; //auto a = anchors_[i]; //for (int i = 0; i < a.size(); i++) //{ // cout << a[i] << endl; //} auto decodePlugin = DecodePlugin(score_thresh_, top_n_, anchors_[i], scale); std::vector<nvinfer1::ITensor *> inputs = {classOutput, boxOutput}; auto layer = network->addPluginV2(inputs.data(), inputs.size(), decodePlugin); scores.push_back(layer->getOutput(0)); boxes.push_back(layer->getOutput(1)); classes.push_back(layer->getOutput(2)); } // Cleanup outputs for (int i = 0; i < nbOutputs; i++) { auto output = network->getOutput(0); network->unmarkOutput(*output); } // Concat tensors from each feature map std::vector<nvinfer1::ITensor *> concat; for (auto tensors : {scores, boxes, classes}) { auto layer = network->addConcatenation(tensors.data(), tensors.size()); concat.push_back(layer->getOutput(0)); } // Add NMS plugin auto nmsPlugin = NMSPlugin(nms_thresh_, detections_per_im_); auto layer = network->addPluginV2(concat.data(), concat.size(), nmsPlugin); //std::vector<std::string> &names = mParams.outputTensorNames; //{"scores", "boxes", "classes"}; for (int i = 0; i < layer->getNbOutputs(); i++) { auto output = layer->getOutput(i); nvinfer1::Dims mOutputDims = output->getDimensions(); //std::cout<<i<<" mOutputDims"<<" "<<mOutputDims.nbDims<<" "<<mOutputDims.d[0]<<" "<<mOutputDims.d[1]<<" "<<mOutputDims.d[2]<<std::endl; network->markOutput(*output); mOutputDimsVec.push_back(mOutputDims); //output->setName(names[i].c_str()); } // Build engine //std::cout << "Applying optimizations and building TRT CUDA engine..." << std::endl; //_engine = builder->buildEngineWithConfig(*network, *builderConfig); // PLUGIN ENDS //mEngine = std::shared_ptr<nvinfer1::ICudaEngine>(builder->buildEngineWithConfig(*network, *config), samplesCommon::InferDeleter()); mEngine = SampleUniquePtr<nvinfer1::ICudaEngine>(builder->buildEngineWithConfig(*network, *config)); auto serializedModel = SampleUniquePtr<nvinfer1::IHostMemory>(mEngine->serialize()); //nvinfer1::IHostMemory *serializedModel = mEngine->serialize(); std::ofstream file(mParams.engine_fp, std::ios::out | std::ios::binary); file.write(reinterpret_cast<const char*>(serializedModel->data()), serializedModel->size()); //serializedModel->destroy(); return true; } bool RetinaNet::buildFromPlan() { std::ifstream ifile(mParams.engine_fp, std::ios::in | std::ios::binary); ifile.seekg (0, ifile.end); size_t size = ifile.tellg(); ifile.seekg (0, ifile.beg); //char *buffer = new char[size]; std::unique_ptr<char> buffer(new char[size]); ifile.read(buffer.get(), size); ifile.close(); //nvinfer1::IRuntime *_runtime = nvinfer1::createInferRuntime(gLogger.getTRTLogger()); auto _runtime = SampleUniquePtr<nvinfer1::IRuntime>(nvinfer1::createInferRuntime(gLogger.getTRTLogger())); //auto tEngine = _runtime->deserializeCudaEngine(buffer, size, nullptr); mEngine = SampleUniquePtr<nvinfer1::ICudaEngine>(_runtime->deserializeCudaEngine(buffer.get(), size, nullptr)); //delete[] buffer; //_runtime->destroy(); //mEngine = std::shared_ptr<nvinfer1::ICudaEngine>(tEngine, samplesCommon::InferDeleter()); mInputDims = mEngine->getBindingDimensions(0); for(int ii = 1; ii < mEngine->getNbBindings(); ii++) { auto mOutputDims = mEngine->getBindingDimensions(ii); //std::cout<<" Engine:mOutputDims "<<ii<<" "<<mOutputDims.nbDims<<" "<<mOutputDims.d[0]<<" "<<mOutputDims.d[1]<<" "<<mOutputDims.d[2]<<std::endl; mOutputDimsVec.push_back(mOutputDims); } return true; } bool RetinaNet::constructNetwork(SampleUniquePtr<nvinfer1::IBuilder>& builder, SampleUniquePtr<nvinfer1::INetworkDefinition>& network, SampleUniquePtr<nvinfer1::IBuilderConfig>& config, SampleUniquePtr<nvonnxparser::IParser>& parser) { auto parsed = parser->parseFromFile( mParams.onnx_fp.c_str(), static_cast<int>(gLogger.getReportableSeverity())); if (!parsed) { return false; } builder->setMaxBatchSize(mParams.batch_size); config->setMaxWorkspaceSize(1ULL << 30); if (mParams.fp16) { config->setFlag(nvinfer1::BuilderFlag::kFP16); } if (mParams.int8) { config->setFlag(nvinfer1::BuilderFlag::kINT8); samplesCommon::setAllTensorScales(network.get(), 127.0f, 127.0f); } samplesCommon::enableDLA(builder.get(), config.get(), mParams.dla_core); return true; } bool RetinaNet::infer() { // Create RAII buffer manager object std::cout<<"xxxxxxx buffer def"<<std::endl; samplesCommon::BufferManager buffers(mEngine, mParams.batch_size); auto context = SampleUniquePtr<nvinfer1::IExecutionContext>(mEngine->createExecutionContext()); if (!context) { return false; } // Read the input data into the managed buffers //assert(mParams.inputTensorNames.size() == 1); cheetahinfer::Timer timer; timer.start(); if (!processInput(buffers)) { return false; } timer.stop(); std::cout<<"processInput#Elapse "<<timer.timeSpan()<<"s"<<std::endl; // Memcpy from host input buffers to device input buffers timer.start(); buffers.copyInputToDevice(); cudaDeviceSynchronize(); timer.stop(); std::cout<<"copyInputToDevice#Elapse "<<timer.timeSpan()<<"s"<<std::endl; timer.start(); //bool status = context->execute(mParams.batchSize, buffers.getDeviceBindings().data()); //cudaDeviceSynchronize(); bool status = context->enqueue(mParams.batch_size, buffers.getDeviceBindings().data(), _stream, nullptr); cudaStreamSynchronize(_stream); //cudaDeviceSynchronize(); timer.stop(); std::cout<<"execute#Elapse "<<timer.timeSpan()<<"s"<<std::endl; if (!status) { return false; } // Memcpy from device output buffers to host output buffers timer.start(); buffers.copyOutputToHost(); cudaDeviceSynchronize(); timer.stop(); std::cout<<"copyOutputToHost#Elapse "<<timer.timeSpan()<<"s"<<std::endl; // Verify results if (!verifyOutput(buffers)) { return false; } return true; } bool RetinaNet::processInput(const samplesCommon::BufferManager& buffers) { float* hostDataBuffer = static_cast<float*>(buffers.getHostBufferByIndex(0)); //Name(mParams.inputTensorNames[0])); readImage("data/resized.png", hostDataBuffer); return true; } bool RetinaNet::readImage(const std::string fp, float* host_data) { const int inputH = mInputDims.d[1]; const int inputW = mInputDims.d[2]; std::cout << "inputH " << inputH << ", inputW " << inputW<<std::endl; std::cout << "Preparing data..." << std::endl; //auto image = cv::imread(fp.c_str(), cv::IMREAD_COLOR); orig_image_ = cv::imread(fp.c_str(), cv::IMREAD_COLOR); if (orig_image_.empty()) { std::cout << "Image read failure" << std::endl; } std::cout << "Read image successfully" << std::endl; cv::resize(orig_image_, orig_image_, cv::Size(inputW, inputH)); cv::Mat pixels; orig_image_.convertTo(pixels, CV_32FC3, 1.0, 0); // / 255 int channels = 3; std::vector<float> img; if (pixels.isContinuous()) img.assign((float*)pixels.datastart, (float*)pixels.dataend); else { std::cerr << "Error reading image " << fp << std::endl; return false; } std::vector<float> mean {123.675, 116.28, 103.53}; //{0.485, 0.456, 0.406}; std::vector<float> std {58.395, 57.12, 57.375}; //{0.229, 0.224, 0.225}; for (int c = 0; c < channels; c++) { for (int j = 0, hw = inputW * inputH; j < hw; j++) { host_data[c * hw + j] = (img[channels * j + 2 - c] - mean[c]) / std[c]; } } //for (int ii = 0; ii < channels * inputW * inputH; ii++) { // cout << host_data[ii] << endl; //} return true; } bool RetinaNet::verifyOutput(const samplesCommon::BufferManager& buffers) { const int outputSize = mOutputDimsVec[0].d[0]; float* scores = static_cast<float*>(buffers.getHostBufferByIndex(1)); //Name("scores")); //mParams.outputTensorNames[0])); float* boxes = static_cast<float*>(buffers.getHostBufferByIndex(2)); //Name("boxes")); //mParams.outputTensorNames[0])); float* classes = static_cast<float*>(buffers.getHostBufferByIndex(3)); //Name("classes")); //mParams.outputTensorNames[0])); // Calculate Softmax for (int i = 0; i < outputSize; i++) { scores[i] = 1 / ( 1 + exp(-scores[i])); } std::cout << "Output:" << std::endl; for (int i = 0; i < outputSize; i++) { if (scores[i] > 0.9 && 0 == int(classes[i])) { int x1 = boxes[i*4+0]; int y1 = boxes[i*4+1]; int x2 = boxes[i*4+2]; int y2 = boxes[i*4+3]; std::cout << "Found box {" << x1 << ", " << y1 << ", " << x2 << ", " << y2 << "} with score " << scores[i] << " and class " << classes[i] << std::endl; cv::rectangle(orig_image_, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 255, 0)); } } std::string out_file = "det.jpg"; cv::imwrite(out_file, orig_image_); gLogInfo << std::endl; return true; } /* bool RetinaNet::verifyOutput(const samplesCommon::BufferManager& buffers) { char buffer[50]; for(int ii = 0; ii < 5; ii ++) { // cls //sprintf(buffer, "output.%d.0"); unsigned long long outputSize = mOutputDimsVec[2 * ii].d[0] * mOutputDimsVec[2 * ii].d[1] * mOutputDimsVec[2 * ii].d[2]; float* cls = static_cast<float*>(buffers.getHostBuffer(mParams.outputTensorNames[2 * ii])); float* reg = static_cast<float*>(buffers.getHostBuffer(mParams.outputTensorNames[2 * ii + 1])); // reg //sprintf(buffer, "output.%d.1"); cout << "====stride " << pow(2, ii + 3) << "====" << endl; cout << "####cls####" << endl; for (unsigned long long ii = 0; ii < outputSize; ii++) { //cout << cls[ii] << endl; cout << ii << "/" << outputSize << ":" << 1 / ( 1 + exp(-cls[ii])) << endl; } cout << "####reg####" << endl; for (unsigned long long ii = 0; ii < outputSize; ii++) { cout << ii << "/" << outputSize << ":" << reg[ii] << endl; } } gLogInfo << std::endl; return true; } */ void RetinaNet::_prepare() { cudaStreamCreate(&_stream); } void RetinaNet::_set_hp() { top_n_ = 1000; detections_per_im_ = 100; score_thresh_ = 0.9f; nms_thresh_ = 0.5; /* anchors_ = { {-12.0, -12.0, 20.0, 20.0, -7.31, -18.63, 15.31, 26.63, -18.63, -7.31, 26.63, 15.31, -16.16, -16.16, 24.16, 24.16, -10.25, -24.51, 18.25, 32.51, -24.51, -10.25, 32.51, 18.25, -21.4, -21.4, 29.4, 29.4, -13.96, -31.92, 21.96, 39.92, -31.92, -13.96, 39.92, 21.96}, {-24.0, -24.0, 40.0, 40.0, -14.63, -37.25, 30.63, 53.25, -37.25, -14.63, 53.25, 30.63, -32.32, -32.32, 48.32, 48.32, -20.51, -49.02, 36.51, 65.02, -49.02, -20.51, 65.02, 36.51, -42.8, -42.8, 58.8, 58.8, -27.92, -63.84, 43.92, 79.84, -63.84, -27.92, 79.84, 43.92}, {-48.0, -48.0, 80.0, 80.0, -29.25, -74.51, 61.25, 106.51, -74.51, -29.25, 106.51, 61.25, -64.63, -64.63, 96.63, 96.63, -41.02, -98.04, 73.02, 130.04, -98.04, -41.02, 130.04, 73.02, -85.59, -85.59, 117.59, 117.59, -55.84, -127.68, 87.84, 159.68, -127.68, -55.84, 159.68, 87.84}, {-96.0, -96.0, 160.0, 160.0, -58.51, -149.02, 122.51, 213.02, -149.02, -58.51, 213.02, 122.51, -129.27, -129.27, 193.27, 193.27, -82.04, -196.07, 146.04, 260.07, -196.07, -82.04, 260.07, 146.04, -171.19, -171.19, 235.19, 235.19, -111.68, -255.35, 175.68, 319.35, -255.35, -111.68, 319.35, 175.68}, {-192.0, -192.0, 320.0, 320.0, -117.02, -298.04, 245.02, 426.04, -298.04, -117.02, 426.04, 245.02, -258.54, -258.54, 386.54, 386.54, -164.07, -392.14, 292.07, 520.14, -392.14, -164.07, 520.14, 292.07, -342.37, -342.37, 470.37, 470.37, -223.35, -510.7, 351.35, 638.7, -510.7, -223.35, 638.7, 351.35} }; */ anchors_ = { { -19., -7., 26., 14., -25., -10., 32., 17., -32., -14., 39., 21., -12., -12., 19., 19., -16., -16., 23., 23., -21., -21., 28., 28., -7., -19., 14., 26., -10., -25., 17., 32., -14., -32., 21., 39., }, { -37., -15., 52., 30., -49., -21., 64., 36., -64., -28., 79., 43., -24., -24., 39., 39, -32., -32., 47., 47., -43., -43., 58., 58., -15., -37., 30., 52., -21., -49., 36., 64., -28., -64., 43., 79., }, { -75., -29., 106., 60., -98., -41., 129., 72., -128., -56., 159., 87., -48., -48., 79., 79., -65., -65., 96., 96., -86., -86., 117., 117., -29., -75., 60., 106., -41., -98., 72., 129., -56., -128., 87., 159., }, { -149., -59., 212., 122., -196., -82., 259., 145., -255., -112., 318., 175., -96., -96., 159., 159., -129., -129., 192., 192., -171., -171., 234., 234., -59., -149., 122., 212., -82., -196., 145., 259., -112., -255., 175., 318., }, { -298., -117., 425., 244., -392., -164., 519., 291., -511., -223., 638., 350., -192., -192., 319., 319., -259., -259., 386., 386., -342., -342., 469., 469., -117., -298., 244., 425., -164., -392., 291., 519., -223., -511., 350., 638., } }; } } /* anchors_ = { { -19., -7., 26., 14., -25., -10., 32., 17., -32., -14., 39., 21., -12., -12., 19., 19., -16., -16., 23., 23., -21., -21., 28., 28., -7., -19., 14., 26., -10., -25., 17., 32., -14., -32., 21., 39., }, { -37., -15., 52., 30., -49., -21., 64., 36., -64., -28., 79., 43., -24., -24., 39., 39, -32., -32., 47., 47., -43., -43., 58., 58., -15., -37., 30., 52., -21., -49., 36., 64., -28., -64., 43., 79., }, { -75., -29., 106., 60., -98., -41., 129., 72., -128., -56., 159., 87., -48., -48., 79., 79., -65., -65., 96., 96., -86., -86., 117., 117., -29., -75., 60., 106., -41., -98., 72., 129., -56., -128., 87., 159., }, { -149., -59., 212., 122., -196., -82., 259., 145., -255., -112., 318., 175., -96., -96., 159., 159., -129., -129., 192., 192., -171., -171., 234., 234., -59., -149., 122., 212., -82., -196., 145., 259., -112., -255., 175., 318., }, { -298., -117., 425., 244., -392., -164., 519., 291., -511., -223., 638., 350., -192., -192., 319., 319., -259., -259., 386., 386., -342., -342., 469., 469., -117., -298., 244., 425., -164., -392., 291., 519., -223., -511., 350., 638., } }; */
[ "yichao.xiong@media-smart.cn" ]
yichao.xiong@media-smart.cn
3cf86ca418567636834f5892d9a2cb8212ecb8c6
d94b6845aeeb412aac6850b70e22628bc84d1d6d
/scann/scann/distance_measures/one_to_one/dot_product.cc
a4c4054890fbc2d1ce58e76f27ac25799c30bd34
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
ishine/google-research
541aea114a68ced68736340e037fc0f8257d1ea2
c1ae273841592fce4c993bf35cdd0a6424e73da4
refs/heads/master
2023-06-08T23:02:25.502203
2023-05-31T01:00:56
2023-05-31T01:06:45
242,478,569
0
0
Apache-2.0
2020-06-23T01:55:11
2020-02-23T07:59:42
Jupyter Notebook
UTF-8
C++
false
false
1,584
cc
// Copyright 2023 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "scann/distance_measures/one_to_one/dot_product.h" #include <cstdint> namespace research_scann { SCANN_DEFINE_DISTANCE_MEASURE_VIRTUAL_METHODS(DotProductDistance, kEarlyStoppingNotSupported); SCANN_REGISTER_DISTANCE_MEASURE(DotProductDistance); SCANN_DEFINE_DISTANCE_MEASURE_VIRTUAL_METHODS(AbsDotProductDistance, kEarlyStoppingNotSupported); SCANN_REGISTER_DISTANCE_MEASURE(AbsDotProductDistance); double BinaryDotProductDistance::GetDistanceDense( const DatapointPtr<uint8_t>& a, const DatapointPtr<uint8_t>& b) const { return -static_cast<double>(DenseBinaryDotProduct(a, b)); } double BinaryDotProductDistance::GetDistanceSparse( const DatapointPtr<uint8_t>& a, const DatapointPtr<uint8_t>& b) const { return -static_cast<double>(SparseBinaryDotProduct(a, b)); } SCANN_REGISTER_DISTANCE_MEASURE(BinaryDotProductDistance); } // namespace research_scann
[ "copybara-worker@google.com" ]
copybara-worker@google.com
7636df56baafc3923af44c5ffbe7c8d9f291dbd6
190a4e3f7ea2b58dbcf4bb394cea328cdb5322a7
/src/webots/widgets/WbIntSpinBox.cpp
106c7a03570719db636bb9aab98cb3cd82a908dc
[ "Apache-2.0" ]
permissive
congleetea/webots
e4bb1ec369572467cad3e6f036880aabc7a3d3c4
f7bf0cb385842478c5635e29db8e25689d3d0c65
refs/heads/master
2022-12-23T19:12:18.468134
2020-09-28T08:30:23
2020-09-28T08:30:23
299,242,767
1
0
Apache-2.0
2020-09-28T08:34:28
2020-09-28T08:34:28
null
UTF-8
C++
false
false
2,131
cpp
// Copyright 1996-2020 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "WbIntSpinBox.hpp" #include "WbClipboard.hpp" #include <QtGui/QKeyEvent> #include <QtWidgets/QLineEdit> #include <limits> WbIntSpinBox::WbIntSpinBox(QWidget *parent) : QSpinBox(parent), mClipboard(WbClipboard::instance()) { setButtonSymbols(PlusMinus); setMinimumHeight(sizeHint().height()); } WbIntSpinBox::~WbIntSpinBox() { } void WbIntSpinBox::keyPressEvent(QKeyEvent *event) { if (event->matches(QKeySequence::Cut)) cut(); else if (event->matches(QKeySequence::Copy)) copy(); else if (event->matches(QKeySequence::Paste)) paste(); else QSpinBox::keyPressEvent(event); }; void WbIntSpinBox::cut() { if (lineEdit()->hasSelectedText()) { copy(); lineEdit()->backspace(); // remove selected text } } void WbIntSpinBox::copy() const { if (lineEdit()->hasSelectedText()) { bool ok; const int value = lineEdit()->selectedText().toInt(&ok); if (ok) mClipboard->setInt(value); else mClipboard->setString(lineEdit()->selectedText()); } } void WbIntSpinBox::paste() { if (mClipboard->isEmpty()) return; QLineEdit *le = lineEdit(); const QString pastedText = mClipboard->stringValue(); QString newText = le->text(); if (le->hasSelectedText()) // remove selected text newText.remove(le->selectionStart(), le->selectedText().length()); // insert pasted text newText.insert(le->cursorPosition(), mClipboard->stringValue()); // check if valid value bool ok; newText.toInt(&ok); if (ok) le->insert(pastedText); }
[ "David.Mansolino@cyberbotics.com" ]
David.Mansolino@cyberbotics.com
071193e024f80d0ae5644ab433cf33899edc7872
1fbc499a87fb83e34a1838c39c7d46e5d5e30903
/app/src/client/client.h
b969407ec7dd115a0c01e675cbc2afa24e4b9621
[]
no_license
slarrx/coffee-chat
3f9882c63abb147bb587b915fea702c62f5d9f07
5a658132d918aa4c8690faab5adcdaee960ae052
refs/heads/master
2020-04-10T15:25:04.381896
2019-09-04T10:28:13
2019-09-04T10:28:13
161,108,868
1
0
null
null
null
null
UTF-8
C++
false
false
358
h
#ifndef COFFEE_CHAT_CLIENT_H_ #define COFFEE_CHAT_CLIENT_H_ #include <string> #include "connection.h" namespace coffee_chat { class Client : public Connection { public: explicit Client(char*, int = default_port_); void Run() override; private: static void InputHandling(Client*); }; } // namespace coffee_chat #endif // COFFEE_CHAT_CLIENT_H_
[ "slarrx@gmail.com" ]
slarrx@gmail.com
3dcd64c86902b25491d402ef24e927c6259ddb92
d1524d8828f573bd53a3be78a9451d1789c9dca7
/NetEventService/ChannelManager.cpp
3160e4bd4a097c110acc89b17f390cf58144ace7
[]
no_license
liunatural/NetEventServiceSolution
750b2aa1f482b07f4de20e1280eaa46446baf3fa
33e5dc785bcf6db21328d981a09d27d3502490ed
refs/heads/master
2020-03-30T12:38:19.391476
2019-08-02T06:07:12
2019-08-02T06:07:12
151,232,745
0
1
null
null
null
null
UTF-8
C++
false
false
1,160
cpp
//************************************************************************** // File......... : ChannelManager.cpp // Project...... : VR // Author....... : Liu Zhi // Date......... : 2018-10 // Description.. : implementation file for class ChannelManager used as channelID management // // History...... : First created by Liu Zhi 2018-10 // //************************************************************************** #include "ChannelManager.h" ChannelManager::ChannelManager() { m_size = 0; } ChannelManager::~ChannelManager() { } void ChannelManager::Init(int start, int size) { m_size = size; for (int i = start; i < start + m_size; i++) { m_ids.push(i); } } int ChannelManager::GetFreeID() { std::lock_guard<std::mutex> lock(m_cid_mtx); if (m_ids.empty()) return -1; int id = m_ids.front(); m_ids.pop(); return id; } void ChannelManager::ReleaseID(int id) { std::lock_guard<std::mutex> lock(m_cid_mtx); m_ids.push(id); } int ChannelManager::TotalIDs() { return m_size; } int ChannelManager::TotalFreeIDs() { return (int)m_ids.size(); }
[ "liunatural@sina.com" ]
liunatural@sina.com
af72192ed3400683308cc6b365a737c4ffd8d5e3
311525f7de84975434f55c00b545ccf7fe3dcce6
/schools/utpc/102921/formal.cpp
ae4ffe8b94c9c8eeedbb261ac244486346319e57
[]
no_license
fishy15/competitive_programming
60f485bc4022e41efb0b7d2e12d094213d074f07
d9bca2e6bea704f2bfe5a30e08aa0788be6a8022
refs/heads/master
2023-08-16T02:05:08.270992
2023-08-06T01:00:21
2023-08-06T01:00:21
171,861,737
29
5
null
null
null
null
UTF-8
C++
false
false
2,728
cpp
#include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <array> #include <algorithm> #include <utility> #include <map> #include <queue> #include <set> #include <cmath> #include <cstdio> #include <cstring> #include <functional> #include <numeric> #define ll long long #define ld long double #define eps 1e-8 #define MOD 1000000007 #define INF 0x3f3f3f3f #define INFLL 0x3f3f3f3f3f3f3f3f // change if necessary #define MAXN 100010 using namespace std; template<typename F> struct y_combinator_result { F f; template<typename T> explicit y_combinator_result(T &&f) : f(forward<T>(f)) {} template<typename... Args> decltype(auto) operator()(Args &&...args) { return f(ref(*this), forward<Args>(args)...); } }; template<typename F> decltype(auto) y_combinator(F &&f) { return y_combinator_result<decay_t<F>>(forward<F>(f)); } struct p2 { ll x, y; p2() : p2(0, 0) {} p2(ll x, ll y) : x(x), y(y) {} p2 operator+(const p2 a) const { return p2(x + a.x, y + a.y); } p2 operator-(const p2 a) const { return p2(x - a.x, y - a.y); } void operator+=(const p2 a) { x += a.x; y += a.y; } }; int n, k; vector<array<ll, 2>> adj[MAXN]; p2 max(p2 a, p2 b) { if (a.x < b.x) { return b; } return a; } p2 solve(int c) { vector<array<p2, 2>> dp(n); p2 ans; auto dfs = y_combinator([&](auto self, int v, int p) -> void { for (auto [e, w] : adj[v]) { if (e != p) { self(e, v); dp[v][0] += max(dp[e][0], dp[e][1]); } } dp[v][1] = dp[v][0]; p2 mm = dp[v][1]; for (auto [e, w] : adj[v]) { if (e != p) { p2 res = dp[v][1] - max(dp[e][0], dp[e][1]) + dp[e][0]; res.x += w - c; res.y++; mm = max(mm, res); } } dp[v][1] = mm; dp[v][0] = max(dp[v][0], p2()); dp[v][1] = max(dp[v][1], p2()); ans = max(dp[v][0], ans); ans = max(dp[v][1], ans); }); dfs(0, 0); return ans; } int main() { cin.tie(0)->sync_with_stdio(0); cin >> n >> k; for (int i = 0; i < n - 1; i++) { int a, b, c; cin >> a >> b >> c; a--; b--; adj[a].push_back({b, c}); adj[b].push_back({a, c}); } int l = -INF; int r = INF; ll opt = 0; while (l <= r) { int m = (l + r) / 2; p2 x = solve(m); if (x.y <= k) { opt = m; r = m - 1; } else { l = m + 1; } } p2 x = solve(opt); cout << x.x + k * opt << '\n'; return 0; }
[ "aaryan.prakash3.14@gmail.com" ]
aaryan.prakash3.14@gmail.com
2222d6610603ef8c925a43c16a33a90e9fe1ac3a
8e5fa8897f486ea60df660e8d6f60149ce815d25
/Constructors/Part1/constructors01.cpp
e52b7d628993a431941d80468f571999a1289121
[]
no_license
gregkorte/CISP1020
fbf85339aad1d333e8a63fd004e62c26e3986192
c3711af54d688787c66649bb73ed8a385ae7e2b2
refs/heads/master
2021-01-21T13:56:41.774461
2015-10-19T20:47:39
2015-10-19T20:47:39
41,424,504
0
0
null
null
null
null
UTF-8
C++
false
false
4,414
cpp
/************************************************************* * Name: constructors01(Card02) * Author: Greg Korte * Date due: 15-10-05 * Description: Create a Card class that has private data items, create two constructors, getters, setters, display the suit and value. Upload a test plan. **************************************************************/ /*************************** * libraries ****************************/ #include <string> // needed for string #include <string.h> // needed for string functions #include <iostream> // needed for Cin and Cout #include <cmath> using namespace std; /************************************ * defines *************************************/ /**************************************** * class definitions ****************************************/ class Card // capital letter { private: /**** comments line up ****/ int value; // value char suit; // suit public: /******************************************************* * the word 'set' * data item name starting with an upper case letter ********************************************************/ // constructors Card(); Card(char, int); // setters void setSuit(char s) {suit = s;} void setValue(int val) {value = val;} /******************************************************* * the word 'get' * data item name starting with an upper case letter * example string getRow() ********************************************************/ // getters char getSuit() {return suit;} int getValue() {return value;} string chooseSuit(char); void display(); }; /**************************************** * member functions for above class ****************************************/ Card::Card() { setSuit(' '); setValue(0); } Card::Card(char suit, int val) { setSuit(suit); setValue(val); } string Card::chooseSuit(char s) { switch(s){ case 'c': return "clubs"; case 'd': return "diamonds"; case 'h': return "hearts"; case 's': return "spades"; case ' ': return "default state"; } } /******************************************** * displays data items and calculated fields ********************************************/ void Card::display() { // use 'getters' cout << "\n"; cout << "Value is " << getValue() << "\n"; cout << "Suit is " << chooseSuit(getSuit()) << "\n"; cout << "\n"; } /************************************* * function prototype *************************************/ void testClass(); void testDisplay(); void testSetters(); void testGetters(); void testChooseSuit(); /************************************ * global variables *************************************/ int main() { /************************************ * local variables *************************************/ testClass(); testDisplay(); testSetters(); testGetters(); testChooseSuit(); system("pause"); return 0; } /************************************ * non-member functions *************************************/ /************************************/ // TEST class constructor void testClass() { cout << "\n***** TestCard01 *****\n"; Card card01; card01.display(); Card card02('d', 10); card02.display(); } // TEST display output void testDisplay() { cout << "\n***** TestCard02 *****\n"; Card card('c', 9); card.display(); } // TEST setters void testSetters() { cout << "\n***** TestCard03 *****\n"; Card card; card.setSuit('h'); card.display(); } // TEST getters void testGetters() { cout << "\n***** TestCard04 *****\n"; Card card('d', 8); cout << card.getSuit() << "\n"; cout << card.getValue() << "\n"; } // TEST suit char to string void testChooseSuit() { cout << "\n***** TestCard05 *****\n"; Card card('s', 7); card.display(); cout << "\n"; }
[ "gryphionsroost@yahoo.com" ]
gryphionsroost@yahoo.com
759e56f267a48f156888130391edf5fbfffbd852
21f599250699a8bfe5e2f8be2ec9855e0e04b2cd
/SoftDropJetClustering/src/analysis/FragF.cc
c67038c46d49fbc190bfd25dbf8b35f1385ebca2
[]
no_license
amitkr2410/HPC_data_analysis
36f313968c2667e0d30c1d5ad7381973e91dbcf1
3ae572b354ea8a95eb5d6e5f828487e1137f62ff
refs/heads/main
2023-05-31T02:10:02.814571
2023-05-15T05:03:48
2023-05-15T05:03:48
209,374,028
0
0
null
null
null
null
UTF-8
C++
false
false
2,980
cc
#include "FragF.h" #include "TMath.h" //using namespace Analysis; // Register the module with the base class RegisterAnalysisModule<FragF> FragF::reg("FragF"); FragF::FragF(std::string name_in): name(name_in) { std::cout << "-@-Creating " << name << std::endl; } FragF::~FragF(){ std::cout << "-$-Deleting " << name << std::endl; } void FragF::SetObservable (fastjet::PseudoJet jet, std::vector<std::shared_ptr<Particle>> particle_list, int ir, int ijp, int ijr ){ //-------------------------------------------------------------------------------------------------- for( int iv = 0; iv < variables.size(); iv++ ){ for( int ipp = 0; ipp < particlePtMin.size(); ipp++ ){ for( int ipr = 0; ipr < particleRapMin.size(); ipr++ ){ int index = GetHistIndex(iv,ir,ijp,ijr,ipp,ipr,0); hist_list[index]->JetTriggered(); for( auto p : particle_list ){ if( ParticleTrigger(p, ipp, ipr) ){ double delta_eta = p->eta() - jet.eta() ; double delta_phi = jet.delta_phi_to( p->GetPseudoJet() ); double delta_r = TMath::Sqrt( delta_eta*delta_eta + delta_phi*delta_phi); //-------------------------------------------------------------------------------------------------- if( delta_r <= jetR[ir] ){ double val = p->perp(); // particle pt double n = sub_ptr->nSub(p); if( variables[iv] == "z" ){ double jpt = jet.perp(); val =val*cos(delta_r)/jpt; } hist_list[index]->Fill( val, n ); } //-------------------------------------------------------------------------------------------------- } } }//ipr }//ipp }//iv //-------------------------------------------------------------------------------------------------- } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void FragF::CombineHist(int iv, int ir, int ijp, int ijr, int ipp, int ipr, int ip){ std::string hist_name = GetHistName( iv, ir, ijp, ijr, ipp, ipr, ip ); std::cout << "[FragF] hist_name = " << hist_name << std::endl; auto total_hist = CreateHist(hist_name, iv); total_hist->Init(); double nJetTotal = 0.0; for( auto hist: hist_list ){ double n_ev = hist->Nev(); if( n_ev != 0 ){ nJetTotal += hist->GetNjetSigmaOverEev(); double sigma = hist->Sigma(); total_hist->Add(hist, sigma/n_ev ); } } total_hist->Print("count_"); if(nJetTotal!=0){ total_hist->Scale(1.0/nJetTotal,"width"); total_hist->Print("fragf_"); }else{ std::cout << "[FragF] 0-total Jet" << std::endl; std::cout << "[FragF] Skip. "<< std::endl; } total_hist->DeleteTH(); }
[ "amitkr2410@gmail.com" ]
amitkr2410@gmail.com
5676ed512a19db737e0c1e286a8e21cfce6c34a3
54f8d27813332ac3e8bfbbe1a8e7001927b4605f
/src/tiny_dnn/io/display.h
a3dffd30ee6f0ccedc533d64c5a6f12d0cdc2916
[]
no_license
dselivanov/tinydnn
7ecd27f053750b5eeea09b3535adf9583827c30c
33c8e012c865180fd360845c7c9ec1ae126c508d
refs/heads/master
2021-01-22T10:59:58.046158
2017-02-14T20:24:49
2017-02-14T20:24:49
82,061,054
2
1
null
2017-02-15T12:59:42
2017-02-15T12:59:42
null
UTF-8
C++
false
false
3,681
h
// addapted from boost progress.hpp, made c++11 only // #ifndef PROGRESS_H #define PROGRESS_H #include <chrono> #include <iostream> // for ostream, cout, etc #include <string> // for string namespace tiny_dnn { class timer { public: timer() : t1(std::chrono::high_resolution_clock::now()) {} float_t elapsed() { return std::chrono::duration_cast<std::chrono::duration<float_t>>( std::chrono::high_resolution_clock::now() - t1) .count(); } void restart() { t1 = std::chrono::high_resolution_clock::now(); } void start() { t1 = std::chrono::high_resolution_clock::now(); } void stop() { t2 = std::chrono::high_resolution_clock::now(); } float_t total() { stop(); return std::chrono::duration_cast<std::chrono::duration<float_t>>(t2 - t1) .count(); } ~timer() {} private: std::chrono::high_resolution_clock::time_point t1, t2; }; // progress_display --------------------------------------------------------// // progress_display displays an appropriate indication of // progress at an appropriate place in an appropriate form. class progress_display { public: explicit progress_display(size_t expected_count_, std::ostream &os = std::cout, const std::string &s1 = "\n", // leading strings const std::string &s2 = "", const std::string &s3 = "") // os is hint; implementation may ignore, particularly in embedded systems : m_os(os), m_s1(s1), m_s2(s2), m_s3(s3) { restart(expected_count_); } void restart(size_t expected_count_) { // Effects: display appropriate scale // Postconditions: count()==0, expected_count()==expected_count_ _count = _next_tic_count = _tic = 0; _expected_count = expected_count_; m_os << m_s1 << "0% 10 20 30 40 50 60 70 80 90 100%\n" << m_s2 << "|----|----|----|----|----|----|----|----|----|----|" << std::endl // endl implies flush, which ensures display << m_s3; if (!_expected_count) _expected_count = 1; // prevent divide by zero } // restart size_t operator+=(size_t increment) { // Effects: Display appropriate progress tic if needed. // Postconditions: count()== original count() + increment // Returns: count(). if ((_count += increment) >= _next_tic_count) { display_tic(); } return _count; } size_t operator++() { return operator+=(1); } size_t count() const { return _count; } size_t expected_count() const { return _expected_count; } private: std::ostream &m_os; // may not be present in all imps const std::string m_s1; // string is more general, safer than const std::string m_s2; // const char *, and efficiency or size are const std::string m_s3; // not issues size_t _count, _expected_count, _next_tic_count; size_t _tic; void display_tic() { // use of floating point ensures that both large and small counts // work correctly. static_cast<>() is also used several places // to suppress spurious compiler warnings. size_t tics_needed = static_cast<size_t>( (static_cast<double>(_count) / _expected_count) * 50.0); do { m_os << '*' << std::flush; } while (++_tic < tics_needed); _next_tic_count = static_cast<size_t>((_tic / 50.0) * _expected_count); if (_count == _expected_count) { if (_tic < 51) m_os << '*'; m_os << std::endl; } } // display_tic progress_display &operator=(const progress_display &) = delete; }; } // namespace tiny_dnn #endif
[ "yixuan.qiu@cos.name" ]
yixuan.qiu@cos.name
8016a14be5e2e5a6caab8cb4c49c17261d2b2574
a3d2c1bcb581e161baa6b8da4a1f066cbfe6d13f
/gameSource/StateObjectDisplay.cpp
de5fd50d55cdec328571d093b183c70304596da5
[]
no_license
jasonrohrer/SleepIsDeath
24b67c95f50c2c8d7f7c19a4a8f76ec68a177d04
8270f84ff002938919cb053311f1c8331cb5d542
refs/heads/master
2022-07-09T04:51:38.542662
2022-03-19T18:12:22
2022-03-19T18:12:22
106,604,419
16
3
null
2022-07-05T18:56:03
2017-10-11T20:14:25
C++
UTF-8
C++
false
false
12,780
cpp
#include "StateObjectDisplay.h" #include "common.h" #include "SpriteResource.h" #include "TilePicker.h" #include "minorGems/graphics/openGL/gui/TextGL.h" #include "minorGems/util/stringUtils.h" extern TilePicker *mainTilePicker; static clickMask blankMask; StateObjectDisplay::StateObjectDisplay( int inAnchorX, int inAnchorY ) : GUIComponentGL( inAnchorX, inAnchorY, G * P, G * P ), mLastPixelClickX( 0 ), mLastPixelClickY( 0 ), mLastGridClickX( 0 ), mLastGridClickY( 0 ), mLastActionRelease( false ), mLastActionPress( false ), mMouseHover( false ), mLastHoverX( 0 ), mLastHoverY( 0 ), mShowSelected( true ), mShowGrid( true ), mUseTrans( true ), mLastSelected( -2 ), mBlinkCycle( 0 ) { for( int y=0; y<P; y++ ) { for( int x=0; x<P; x++ ) { blankMask.opaque[y][x] = false; } } mZoomFactor = 1.0; } StateObjectDisplay::~StateObjectDisplay() { int numSprites = mObjectSprites.size(); for( int s=0; s<numSprites; s++ ) { delete *( mObjectSprites.getElement( s ) ); delete *( mObjectSpriteHighlights.getElement( s ) ); } } void StateObjectDisplay::setStateObject( StateObject inStateObject, char inUseTrans ) { mUseTrans = inUseTrans; mStateObject = inStateObject; // clear old int numSprites = mObjectSprites.size(); int i; for( i=0; i<numSprites; i++ ) { delete *( mObjectSprites.getElement( i ) ); delete *( mObjectSpriteHighlights.getElement( i ) ); } mObjectSprites.deleteAll(); mObjectSpriteHighlights.deleteAll(); mObjectSpritePositions.deleteAll(); mObjectSpriteFades.deleteAll(); mObjectSpriteGlows.deleteAll(); mObjectMasks.deleteAll(); int centerScreenPosX = (int)( P * (G/2) / mZoomFactor ); int centerScreenPosY = (int)( P * (G/2 - mZoomFactor) / mZoomFactor ); // add new numSprites = mStateObject.getNumLayers(); for( int s=0; s<numSprites; s++ ) { SpriteResource resource( mStateObject.getLayerSprite( s ) ); mObjectSprites.push_back( resource.getSprite( mUseTrans ) ); mObjectSpriteHighlights.push_back( resource.getHighlightSprite() ); intPair p = mStateObject.getLayerOffset( s ); p.x += centerScreenPosX; p.y += centerScreenPosY; mObjectSpritePositions.push_back( p ); mObjectSpriteFades.push_back( mStateObject.getLayerTrans( s ) / 255.0f ); mObjectSpriteGlows.push_back( mStateObject.getLayerGlow( s ) ); clickMask mask; for( int y=0; y<P; y++ ) { for( int x=0; x<P; x++ ) { mask.opaque[y][x] = ! resource.getTrans( x, y ); } } mObjectMasks.push_back( mask ); } // last, add anchor sprite for this object, on top mObjectSprites.push_back( new Sprite( "anchor.tga", true ) ); // no special highlight for anchor mObjectSpriteHighlights.push_back( new Sprite( "anchor.tga", true ) ); intPair p = {0,0}; p.x += centerScreenPosX; p.y += centerScreenPosY; mObjectSpritePositions.push_back( p ); mObjectSpriteFades.push_back( 1.0f ); mObjectSpriteGlows.push_back( false ); mObjectMasks.push_back( blankMask ); } void StateObjectDisplay::updateSpritePositions( StateObject inStateObject ) { // don't need to touch masks mStateObject = inStateObject; int centerScreenPosX = (int)( P * (G/2) / mZoomFactor ); int centerScreenPosY = (int)( P * (G/2 - mZoomFactor) / mZoomFactor ); int numSprites = mStateObject.getNumLayers(); for( int s=0; s<numSprites; s++ ) { intPair p = mStateObject.getLayerOffset( s ); p.x += centerScreenPosX; p.y += centerScreenPosY; *( mObjectSpritePositions.getElement( s ) ) = p; *( mObjectSpriteFades.getElement( s ) ) = mStateObject.getLayerTrans( s ) / 255.0f; *( mObjectSpriteGlows.getElement( s ) ) = mStateObject.getLayerGlow( s ); } // anchor intPair p = {0,0}; p.x += centerScreenPosX; p.y += centerScreenPosY; *( mObjectSpritePositions.getElement( numSprites ) ) = p; } void StateObjectDisplay::showGrid( char inShow ) { mShowGrid = inShow; } double StateObjectDisplay::getZoom() { return mZoomFactor; } void StateObjectDisplay::setZoom( double inZoom ) { mZoomFactor = inZoom; updateSpritePositions( mStateObject ); } void StateObjectDisplay::fireRedraw() { int gridLimit = (int)( G / mZoomFactor ); int selected = mStateObject.mSelectedLayer; if( mLastSelected != selected || ! mShowGrid ) { // reset mBlinkCycle = 0; mLastSelected = selected; } else { mBlinkCycle ++; } if( mUseTrans ) { // background of selected tile Tile tile = (Tile)( mainTilePicker->getBackgroundTile() ); Sprite *tileSprite = tile.getSprite(); for( int y=0; y<gridLimit; y++ ) { for( int x=0; x<gridLimit; x++ ) { Vector3D pos( mAnchorX + ( x * P + P/2 ) * mZoomFactor, mAnchorY + (y * P + P/2) * mZoomFactor, 0 ); tileSprite->draw( 0, 0, &pos, mZoomFactor ); } } delete tileSprite; } // now draw all sprites int numSprites = mObjectSprites.size(); //printf( "Drawing %d sprites, %d selected\n", numSprites, selected ); for( int s=0; s<numSprites; s++ ) { Sprite *sprite = *( mObjectSprites.getElement( s ) ); intPair pixelPos = *( mObjectSpritePositions.getElement( s ) ); float fadeFactor = *( mObjectSpriteFades.getElement( s ) ); Vector3D pos( mAnchorX + mZoomFactor * (pixelPos.x + P/2), mAnchorY + mZoomFactor * (pixelPos.y + P/2), 0 ); char drawIt = true; Color c( 1, 1, 1, 1 ); char isAnchor = false; if( s == numSprites - 1 ) { // an anchor isAnchor = true; fadeFactor *= 0.25; if( !mShowGrid ) { // hide anchors drawIt = false; } } /* if( ! isAnchor && mShowGrid && s == selected ) { // make it blink double blinkFadeFactor = 0.35 * cos( mBlinkCycle / 3.0 ) + 0.65; fadeFactor *= blinkFadeFactor; } */ // skip sprites that are way out of bounds (due to zooming) if( pos.mX < mAnchorX || pos.mX > mAnchorX + mWidth || pos.mY < mAnchorY || pos.mY > mAnchorY + mHeight ) { drawIt = false; } if( drawIt ) { char glow = *( mObjectSpriteGlows.getElement( s ) ); if( glow ) { // brighten only glBlendFunc( GL_SRC_ALPHA, GL_ONE ); } sprite->draw( 0, 0, &pos, mZoomFactor, fadeFactor, &c ); if( glow ) { // back to normal blend glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); } if( ! isAnchor && mShowGrid && mShowSelected && s == selected ) { // blinking highlight on top double blinkFadeFactor = 0.25 * cos( mBlinkCycle / 3.0 ) + 0.25; Sprite *highlight = *( mObjectSpriteHighlights.getElement( s ) ); highlight->draw( 0, 0, &pos, mZoomFactor, blinkFadeFactor, &c ); } } } if( mShowGrid ) { //grid lines glColor4f( 1, 1, 1, 0.25f ); glBegin( GL_LINES ); { for( int x=0; x<gridLimit+1; x++ ) { glVertex2d( mAnchorX + x * P * mZoomFactor, mAnchorY ); glVertex2d( mAnchorX + x * P * mZoomFactor, mAnchorY + mHeight ); } for( int y=0; y<gridLimit+1; y++ ) { glVertex2d( mAnchorX, mAnchorY + y * P * mZoomFactor ); glVertex2d( mAnchorX + mWidth, mAnchorY + y * P * mZoomFactor ); } } glEnd(); } /* // thin white border, partly transparent glColor4f( 1, 1, 1, 0.25f ); glBegin( GL_LINE_LOOP ); { glVertex2d( mAnchorX, mAnchorY ); glVertex2d( mAnchorX + mWidth, mAnchorY ); glVertex2d( mAnchorX + mWidth, mAnchorY + mHeight ); glVertex2d( mAnchorX, mAnchorY + mHeight ); } glEnd(); */ } void StateObjectDisplay::setLastMouse( double inX, double inY ) { double tempX = ( inX - mAnchorX ) - P * (G/2); double tempY = ( inY - mAnchorY ) - P * (G/2 - mZoomFactor); mLastPixelClickX = (int)( floor( tempX / mZoomFactor ) ); mLastPixelClickY = (int)( floor( tempY / mZoomFactor ) ); mLastPixelClickX -= P/2; mLastPixelClickY -= P/2; mLastHoverX = mLastPixelClickX; mLastHoverY = mLastPixelClickY; mLastGridClickX = (int)( mLastPixelClickX / P ); mLastGridClickY = (int)( mLastPixelClickY / P ); } void StateObjectDisplay::mouseDragged( double inX, double inY ) { mLastActionRelease = false; mLastActionPress = false; if( isEnabled() && isInside( inX, inY ) ) { setLastMouse( inX, inY ); fireActionPerformed( this ); } } void StateObjectDisplay::mousePressed( double inX, double inY ) { mLastActionRelease = false; mLastActionPress = true; if( isEnabled() && isInside( inX, inY ) ) { setLastMouse( inX, inY ); fireActionPerformed( this ); } } void StateObjectDisplay::mouseReleased( double inX, double inY ) { mShowSelected = true; mLastActionRelease = true; mLastActionPress = false; if( isEnabled() && isInside( inX, inY ) ) { setLastMouse( inX, inY ); fireActionPerformed( this ); } } void StateObjectDisplay::mouseMoved( double inX, double inY ) { if( isEnabled() && isInside( inX, inY ) ) { mMouseHover = true; setLastMouse( inX, inY ); } else { mMouseHover = false; } } int StateObjectDisplay::getClickedLayer( int inPixelClickX, int inPixelClickY, int *outClickOffsetX, int *outClickOffsetY ) { //printf( "Checking clicked layer for %d, %d\n", // inPixelClickX, inPixelClickY ); int centerScreenPosX = (int)( P * (G/2) / mZoomFactor ) + P / 2; int centerScreenPosY = (int)( P * (G/2 - mZoomFactor) / mZoomFactor ) + P / 2; int numLayers = mObjectMasks.size(); // skip anchor, start at top, stop when a hit is found for( int i=numLayers-2; i>=0; i-- ) { intPair pos = *( mObjectSpritePositions.getElement( i ) ); int posX = pos.x - centerScreenPosX; int posY = pos.y - centerScreenPosY; //printf( " Layer %d at (%d,%d)\n", i, posX, posY ); // first, do bounding box if( inPixelClickX >= posX && inPixelClickX < posX + P && inPixelClickY >= posY && inPixelClickY < posY + P ) { clickMask *mask = mObjectMasks.getElement( i ); int offsetY = P - ( inPixelClickY - posY ) - 1; int offsetX = inPixelClickX - posX; if( mask->opaque[ offsetY ][ offsetX ] ) { // hit! *outClickOffsetX = offsetX - P/2; *outClickOffsetY = offsetY - P/2; return i; } } } return -1; }
[ "jasonrohrer@fastmail.fm" ]
jasonrohrer@fastmail.fm
f854efa3d5989ce1f076d2667a46237aa9b287c3
0c644d9604f248080bf49073ae61c4ff02a0feab
/C10/p569-13/소스.cpp
5f99614a8b7323fe20580f5de9e1238146d59eca
[]
no_license
0083tony/Core-C-Programming
12bbcc3b5b6dbdda692678cd95590e28f8bfe64f
d846e1544e170c4d010d88a09cf2fd5f91adaf6d
refs/heads/master
2020-08-10T00:19:16.341746
2019-11-08T10:57:04
2019-11-08T10:57:04
214,206,173
2
1
null
null
null
null
UHC
C++
false
false
506
cpp
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> struct POINT { int x1; int x2; int y1; int y2; }; void print_rect(struct POINT RECT) { printf("[RECT 좌하단점: (%d,%d) 우상단점: (%d,%d)]\n", RECT.x1, RECT.y1, RECT.x2, RECT.y2); } int main(void) { struct POINT RECT; printf("직사각형의 좌하단점(x,y)? "); scanf("%d %d", &RECT.x1, &RECT.y1); printf("직사각형의 우상단점(x,y)? "); scanf("%d %d", &RECT.x2, &RECT.y2); print_rect(RECT); return 0; }
[ "0083tony@gmail.com" ]
0083tony@gmail.com
32bde6a08f41a2a66fcf4a78659f9d8ecb4dda07
e3b6375bad3c3299c191476c0cea2b7490c93181
/main.cpp
9d72cdb57640e484fcd06e9c130d453febd8ee24
[]
no_license
ponyprediction/data-manager-2
a22e2b9ff123713ef07b15754c16ab831d08dad4
22188bd78c40a437958c4ef123406dd717d21792
refs/heads/master
2021-01-21T09:18:07.235615
2015-11-13T15:40:24
2015-11-13T15:40:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
#include <manager.h> #include "util.h" #include <QCoreApplication> int main(int argc, char *argv[]) { bool ok = true; QCoreApplication application(argc, argv); QString command; if(ok) { ok = Util::init(); } if(ok) { ok = !(command = Util::getCommand(argc, argv)).isEmpty(); } if(ok) { Manager::execute(command); } else { } return 0; }
[ "loicbourgois.web@gmail.com" ]
loicbourgois.web@gmail.com
209b0287a9b424446dc6a2425f13d68a84cd014c
710e6cfc6806e50a652621a3ec873fba2ee7062a
/src/ghost_unknown.cpp
05d25261dda9d8f1907000dad67acb18a558e9d8
[]
no_license
dawuweijun/Finite-Volumes-Immersed-Boundary-Methods
365e8024345c7eded97c18a639d4fd2f94f325e4
7f7bc00bc5cafabfa50fe0c1cdbe088cb3f04176
refs/heads/master
2021-06-01T02:01:25.075850
2016-05-22T18:23:36
2016-05-22T18:23:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
cpp
/* * ghost_unknown.cpp * * Created on: 18/gen/2012 * Author: ubuntu */ #include "ghost_unknown.hpp" ghost_unknown::ghost_unknown(grid& g, const unsigned int& n_unknown, const p_comp& comp_function) : unknown_map(comp_function) { std::vector<label> gcl = g.get_ghost_cells(); std::vector<ghost_value> gv; for (std::vector<label>::iterator it = gcl.begin(); it!= gcl.end(); it++) { unknown_map.insert(std::pair<label, std::vector<ghost_value> >(*it, gv)); } import_unknown(g, n_unknown); } ghost_unknown::ghost_unknown(const ghost_unknown& lhs): unknown_map(lhs.unknown_map) {} void ghost_unknown::import_unknown(grid& g, const unsigned int& n_unknown) { std::vector<ghost_quantities> gq; unsigned int ngq; // number of ghost quantities ghost_value gv; for (std::map<label, std::vector<ghost_value> >::iterator it = unknown_map.begin(); it != unknown_map.end(); it++) { it->second.clear(); gq = g.ghost_cells[it->first].get_GQs(); for (std::vector<ghost_quantities>::iterator itv = gq.begin(); itv != gq.end(); itv++) { gv.value = itv->RP_and_GP_unknowns.at(n_unknown-1)(1); gv.ass_wet_cell = itv->associated_WC; it->second.push_back(gv); } } }
[ "rinsim85@gmail.com" ]
rinsim85@gmail.com
7c9947bcd8fde6318167989e374972a953d2961d
60bb67415a192d0c421719de7822c1819d5ba7ac
/blazetest/src/mathtest/dmatdmatsub/M5x5aMDb.cpp
957791742366a22f839c852e855cbd58fa233443
[ "BSD-3-Clause" ]
permissive
rtohid/blaze
48decd51395d912730add9bc0d19e617ecae8624
7852d9e22aeb89b907cb878c28d6ca75e5528431
refs/heads/master
2020-04-16T16:48:03.915504
2018-12-19T20:29:42
2018-12-19T20:29:42
165,750,036
0
0
null
null
null
null
UTF-8
C++
false
false
3,721
cpp
//================================================================================================= /*! // \file src/mathtest/dmatdmatsub/M5x5aMDb.cpp // \brief Source file for the M5x5aMDb dense matrix/dense matrix subtraction math test // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. 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. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/StaticMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatdmatsub/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'M5x5aMDb'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions using M5x5a = blaze::StaticMatrix<TypeA,5UL,5UL>; using MDb = blaze::DynamicMatrix<TypeB>; // Creator type definitions using CM5x5a = blazetest::Creator<M5x5a>; using CMDb = blazetest::Creator<MDb>; // Running the tests RUN_DMATDMATSUB_OPERATION_TEST( CM5x5a(), CMDb( 5UL, 5UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix subtraction:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
32ccc6283429ed72df12999d9ebbe81ca4bfd3cb
d42c8cc7c8e4df67c80c74efef4fa1c0ae480cea
/2019-05-07-src/ParallelArraySum/Chrono.h
3d506db2c353fffa5416e4e0b8321d93e41a1eaa
[]
no_license
isel-leic-so/SO-1819v-LI42D
fbec6c46569238849233a768e61055a446825ba7
3d0c3808fc1977fee4635e89bd6a27c14ee0d200
refs/heads/master
2020-04-27T08:53:06.767136
2019-06-11T13:25:33
2019-06-11T13:25:33
174,190,410
22
1
null
null
null
null
UTF-8
C++
false
false
370
h
#pragma once class Chronometer { private: static __int64 getTicksPerSec(); static const __int64 ticksPerSec; DWORD beginCount, endCount; __int64 beginCountHP, endCountHP; public: void Start(); void End(); DWORD GetMilis() { return endCount - beginCount; } __int64 GetMicros() { return ((endCountHP - beginCountHP) * 1000000) / ticksPerSec; } };
[ "jmartins@isel.pt" ]
jmartins@isel.pt
a50e247199d49f2173567b8a31875ffd34a0e32a
eca687f22306a3bf16c0f27bc59d4ad100538be5
/phxrpc/rpc/server_config.h
9a995b5d3a4bfdf49dc1f2c082d3949ab331fdf6
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
AllenWangxiao/phxrpc
25da460149f406a0f832d41ae8168e8a707da5da
4a26c47a259af670c66f03ec0115c0dc1c7593cb
refs/heads/master
2020-04-06T03:49:14.686361
2016-09-16T11:53:19
2016-09-16T11:53:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,314
h
/* Tencent is pleased to support the open source community by making PhxRPC available. Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/BSD-3-Clause 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. See the AUTHORS file for names of contributors. */ #pragma once #include <string> #include <memory> #include "phxrpc/file.h" namespace phxrpc { class ServerConfig { public: ServerConfig(); virtual ~ServerConfig(); bool Read(const char * config_file); virtual bool DoRead(Config & config); void SetBindIP(const char * ip); const char * GetBindIP() const; void SetPort(int port); int GetPort() const; void SetMaxThreads(int max_threads); int GetMaxThreads() const; void SetSocketTimeoutMS(int socket_timeout_ms); int GetSocketTimeoutMS() const; void SetPackageName(const char * package_name); const char * GetPackageName() const; private: char bind_ip_[32]; int port_; int max_threads_; int socket_timeout_ms_; char package_name_[64]; }; class HshaServerConfig : public ServerConfig { public: HshaServerConfig(); ~HshaServerConfig(); bool DoRead(Config & config); void SetMaxConnections(const int max_connections); int GetMaxConnections() const; void SetMaxQueueLength(const int max_queue_length); int GetMaxQueueLength() const; void SetFastRejectThresholdMS(const int fast_reject_threshold_ms); int GetFastRejectThresholdMS() const; void SetFastRejectAdjustRate(const int fast_reject_adjust_rate); int GetFastRejectAdjustRate() const; void SetIOThreadCount(const int io_thread_count); int GetIOThreadCount() const; private: int max_connections_; int max_queue_length_; int fast_reject_threshold_ms_; int fast_reject_adjust_rate_; int io_thread_count_; }; }
[ "lynncui00@gmail.com" ]
lynncui00@gmail.com
39bb764db083c3ec6c5432d6244180e01c8afb2a
f1eb2e8396bb2af36a02a722b68f76f608706c18
/src/dasynq/dasynq-btree_set.h
2e2c09043c086a1666e96d561f0810a0fc64e299
[ "Apache-2.0" ]
permissive
SphinXORunixinskie/dinit
0830fbb0ce49189ebf410ce19772fdebab6214aa
370fc509d9e9c8b47c216fd9de917911597a4541
refs/heads/master
2021-09-04T02:51:07.030352
2018-01-14T23:34:21
2018-01-14T23:34:21
117,488,728
1
0
null
2018-01-15T02:42:08
2018-01-15T02:42:08
null
UTF-8
C++
false
false
19,208
h
#ifndef DASYNQ_BTREE_SET_H #define DASYNQ_BTREE_SET_H #include <functional> namespace dasynq { // A sorted set based on a B-Tree data structure, supporting pre-allocation of nodes. template <typename T, typename P, typename Compare = std::less<P>, int N = 8> class btree_set { struct HeapNode; public: using handle_t = HeapNode; using handle_t_r = HeapNode &; private: struct SeptNode { P prio[N]; handle_t * hn_p[N]; // pointer to handle SeptNode * children[N + 1]; SeptNode * parent; SeptNode() { // Do nothing; initialisation will be run later } void init() { for (int i = 0; i < N; i++) { hn_p[i] = nullptr; children[i] = nullptr; } children[N] = nullptr; parent = nullptr; } int num_vals() noexcept { // We expect to be >50% full, so count backwards: for (int i = N - 1; i >= 0; i--) { if (hn_p[i] != nullptr) { return i + 1; } } return 0; } bool is_leaf() noexcept { return children[0] == nullptr; } void shift_elems_left(int pos, int newpos, int num) { int diff = pos - newpos; int end = pos + num; for (int i = pos; i < end; i++) { prio[i - diff] = prio[i]; hn_p[i - diff] = hn_p[i]; children[i - diff] = children[i]; } children[end - diff] = children[end]; } void shift_elems_right(int pos, int newpos, int num) { int diff = newpos - pos; int end = pos + num; children[end + diff] = children[end]; for (int i = (end - 1); i >= pos; i--) { prio[i + diff] = prio[i]; hn_p[i + diff] = hn_p[i]; children[i + diff] = children[i]; } } }; struct HeapNode { T data; // TODO this should be obscured to avoid early construction SeptNode * parent = nullptr; HeapNode() { } template <typename ...U> HeapNode(U... u) : data(u...) { parent = nullptr; } }; SeptNode * root_sept = nullptr; // root of the B-Tree SeptNode * left_sept = nullptr; // leftmost child (cache) SeptNode * sn_reserve = nullptr; int num_alloced = 0; int num_septs = 0; int num_septs_needed = 0; int next_sept = 1; // next num_allocd for which we need another SeptNode in reserve. // Note that sept nodes are always at least half full, except for the root sept node. // For up to N nodes, one sept node is needed; // at N+1 nodes, three sept nodes are needed: a root and two leaves; // for every N/2 nodes thereafter, an additional sept node may be required. // A simple approximation is, s = (n * 2 + N - 1) / N. // (Actually we get away with much less, if nodes have the same priority, since they are // then linked in list and effectively become a single node). void alloc_slot() { num_alloced++; if (__builtin_expect(num_alloced == next_sept, 0)) { if (++num_septs_needed > num_septs) { try { SeptNode *new_res = new SeptNode(); new_res->parent = sn_reserve; sn_reserve = new_res; num_septs++; } catch (...) { num_septs_needed--; num_alloced--; throw; } } next_sept += N/2; } } SeptNode * alloc_sept() { SeptNode * r = sn_reserve; sn_reserve = r->parent; r->init(); return r; } void release_sept(SeptNode *s) { s->parent = sn_reserve; sn_reserve = s; } // Merge rsibling, and one value from the parent, into lsibling. // Index is the index of the parent value. void merge(SeptNode *lsibling, SeptNode *rsibling, int index) noexcept { int lchildren = lsibling->num_vals(); lsibling->hn_p[lchildren] = lsibling->parent->hn_p[index]; lsibling->prio[lchildren] = lsibling->parent->prio[index]; lsibling->hn_p[lchildren]->parent = lsibling; lchildren++; // bool leaf = lsibling->is_leaf(); int ri = 0; for (ri = 0; rsibling->hn_p[ri] != nullptr; ri++) { lsibling->hn_p[lchildren] = rsibling->hn_p[ri]; lsibling->prio[lchildren] = rsibling->prio[ri]; lsibling->children[lchildren] = rsibling->children[ri]; if (lsibling->children[lchildren]) lsibling->children[lchildren]->parent = lsibling; lsibling->hn_p[lchildren]->parent = lsibling; lchildren++; } lsibling->children[lchildren] = rsibling->children[ri]; if (lsibling->children[lchildren]) lsibling->children[lchildren]->parent = lsibling; release_sept(rsibling); // Now delete in the parent: for (int i = index; i < (N-1); i++) { lsibling->parent->hn_p[i] = lsibling->parent->hn_p[i + 1]; lsibling->parent->prio[i] = lsibling->parent->prio[i + 1]; lsibling->parent->children[i + 1] = lsibling->parent->children[i + 2]; } lsibling->parent->hn_p[N-1] = nullptr; if (lsibling->parent->hn_p[0] == nullptr) { // parent is now empty; it must be root. Make us the new root. release_sept(lsibling->parent); root_sept = lsibling; lsibling->parent = nullptr; } } // borrow values from, or merge with, a sibling node so that the node // is suitably (~>=50%) populated. void repop_node(SeptNode *sept, int children) noexcept { start: SeptNode *parent = sept->parent; if (parent == nullptr) { // It's the root node, so don't worry about it, unless empty if (sept->hn_p[0] == nullptr) { root_sept = nullptr; left_sept = nullptr; release_sept(sept); } return; } // Find a suitable sibling to the left or right: if (parent->children[0] == sept) { // take right sibling SeptNode *rsibling = parent->children[1]; if (rsibling->num_vals() + children + 1 <= N) { // We can merge merge(sept, rsibling, 0); if (sept->parent != nullptr) { children = sept->parent->num_vals(); if (children < N/2) { sept = sept->parent; goto start; } } } else { sept->hn_p[children] = parent->hn_p[0]; sept->prio[children] = parent->prio[0]; sept->hn_p[children]->parent = sept; sept->children[children + 1] = rsibling->children[0]; if (sept->children[children + 1]) sept->children[children + 1]->parent = sept; parent->hn_p[0] = rsibling->hn_p[0]; parent->prio[0] = rsibling->prio[0]; parent->hn_p[0]->parent = parent; rsibling->shift_elems_left(1, 0, N-1); rsibling->hn_p[N-1] = nullptr; return; } } else { // find left sibling int i; for (i = 1; i < N; i++) { if (parent->children[i] == sept) { break; } } SeptNode *lsibling = parent->children[i-1]; int lchildren = lsibling->num_vals(); if (lchildren + children + 1 <= N) { // merge merge(lsibling, sept, i - 1); if (lsibling->parent != nullptr) { children = lsibling->parent->num_vals(); if (children < N/2) { sept = lsibling->parent; goto start; } } } else { sept->shift_elems_right(0, 1, children); sept->hn_p[0] = parent->hn_p[i - 1]; sept->prio[0] = parent->prio[i - 1]; sept->hn_p[0]->parent = sept; sept->children[0] = lsibling->children[lchildren]; if (sept->children[0]) sept->children[0]->parent = sept; parent->hn_p[i - 1] = lsibling->hn_p[lchildren - 1]; parent->prio[i - 1] = lsibling->prio[lchildren - 1]; parent->hn_p[i - 1]->parent = parent; lsibling->hn_p[lchildren - 1] = nullptr; return; } } } public: T & node_data(handle_t & hn) noexcept { return hn.data; } static void init_handle(handle_t &hn) noexcept { // nothing to do } // Allocate a slot, but do not incorporate into the heap: template <typename ...U> void allocate(handle_t &hndl, U... u) { alloc_slot(); // TODO should not really new over an existing object. // T element in HeapNode should be obscured so we don't need a default-constructed // T in it. new (& hndl) HeapNode(u...); } void deallocate(handle_t & hn) noexcept { // hn.HeapNode::~HeapNode(); num_alloced--; // Potentially release reserved sept node if (__builtin_expect(num_alloced < next_sept - N/2, 0)) { next_sept -= N/2; num_septs_needed--; if (num_septs_needed < num_septs - 1) { // Note the "-1" margin is to alleviate bouncing allocation/deallocation SeptNode * r = sn_reserve; sn_reserve = r->parent; delete r; num_septs--; } } } // Insert an allocated slot into the heap. // Return true if it is the leftmost value. bool insert(handle_t & hndl, P pval = P()) noexcept { if (root_sept == nullptr) { root_sept = alloc_sept(); left_sept = root_sept; } SeptNode * srch_sept = root_sept; bool leftmost = true; while (! srch_sept->is_leaf()) { int min = 0; int max = N - 1; while (min <= max) { int i = (min + max) / 2; if (srch_sept->hn_p[i] == nullptr || pval < srch_sept->prio[i]) { max = i - 1; } else if (srch_sept->prio[i] == pval) { // Already present? return false; } else { min = i + 1; } } if (min != 0) { leftmost = false; } // go up to the right: srch_sept = srch_sept->children[max + 1]; } // We got to a leaf: does it have space? // First check if we can add to a linked list int children = srch_sept->num_vals(); { int min = 0; int max = children - 1; while (min <= max) { int i = (min + max) / 2; if (srch_sept->hn_p[i] == nullptr || pval < srch_sept->prio[i]) { max = i - 1; } else if (srch_sept->prio[i] == pval) { // Already present? return false; } else { min = i + 1; } } } SeptNode * left_down = nullptr; // left node going down SeptNode * right_down = nullptr; // right node going down leftmost = leftmost && pval < srch_sept->prio[0]; handle_t * hndl_p = &hndl; while (children == N) { // split and push value towards root SeptNode * new_sibling = alloc_sept(); new_sibling->parent = srch_sept->parent; // create new sibling to the right: for (int i = N/2; i < N; i++) { new_sibling->prio[i - N/2] = srch_sept->prio[i]; // new[0] = old[4] new_sibling->hn_p[i - N/2] = srch_sept->hn_p[i]; new_sibling->children[i - N/2 + 1] = srch_sept->children[i + 1]; if (new_sibling->children[i - N/2 + 1]) new_sibling->children[i - N/2 + 1]->parent = new_sibling; new_sibling->hn_p[i - N/2]->parent = new_sibling; srch_sept->hn_p[i] = nullptr; } // Note that new_sibling->children[0] has not yet been set. if (pval < srch_sept->prio[N/2 - 1]) { auto o_prio = srch_sept->prio[N/2 - 1]; auto o_hidx = srch_sept->hn_p[N/2 - 1]; new_sibling->children[0] = srch_sept->children[N/2]; if (new_sibling->children[0]) new_sibling->children[0]->parent = new_sibling; int i = N/2 - 1; for ( ; i > 0 && pval < srch_sept->prio[i - 1]; i--) { srch_sept->prio[i] = srch_sept->prio[i - 1]; srch_sept->children[i+1] = srch_sept->children[i]; srch_sept->hn_p[i] = srch_sept->hn_p[i - 1]; } srch_sept->prio[i] = pval; srch_sept->hn_p[i] = hndl_p; hndl_p->parent = srch_sept; srch_sept->children[i] = left_down; srch_sept->children[i+1] = right_down; hndl_p = o_hidx; pval = o_prio; } else if (pval < new_sibling->prio[0]) { // new value is right in the middle srch_sept->children[N/2] = left_down; new_sibling->children[0] = right_down; if (left_down) left_down->parent = srch_sept; if (right_down) right_down->parent = new_sibling; } else { auto o_prio = new_sibling->prio[0]; auto o_hidx = new_sibling->hn_p[0]; int i = 0; for ( ; i < (N/2 - 1) && new_sibling->prio[i + 1] < pval; i++) { new_sibling->prio[i] = new_sibling->prio[i + 1]; new_sibling->children[i] = new_sibling->children[i + 1]; new_sibling->hn_p[i] = new_sibling->hn_p[i + 1]; } new_sibling->prio[i] = pval; new_sibling->hn_p[i] = hndl_p; hndl_p->parent = new_sibling; new_sibling->children[i] = left_down; new_sibling->children[i+1] = right_down; if (left_down) left_down->parent = new_sibling; if (right_down) right_down->parent = new_sibling; hndl_p = o_hidx; pval = o_prio; } left_down = srch_sept; right_down = new_sibling; srch_sept = srch_sept->parent; if (srch_sept == nullptr) { // Need new root node: srch_sept = alloc_sept(); root_sept = srch_sept; left_down->parent = root_sept; right_down->parent = root_sept; children = 0; } else { children = srch_sept->num_vals(); } } // Insert into non-full node: int inspos; for (inspos = children; inspos > 0; inspos--) { if (srch_sept->prio[inspos - 1] < pval) { break; } srch_sept->prio[inspos] = srch_sept->prio[inspos-1]; srch_sept->hn_p[inspos] = srch_sept->hn_p[inspos-1]; srch_sept->children[inspos+1] = srch_sept->children[inspos]; } srch_sept->prio[inspos] = pval; srch_sept->hn_p[inspos] = hndl_p; srch_sept->children[inspos] = left_down; srch_sept->children[inspos+1] = right_down; hndl_p->parent = srch_sept; return leftmost; } // Remove a slot from the heap (but don't deallocate it) void remove(handle_t & hndl) noexcept { // we have to remove from the Btree itself // Pull nodes from a child, all the way down // the tree. Then re-balance back up the tree, // merging nodes if necessary. SeptNode * sept = hndl.parent; int i; for (i = 0; i < N; i++) { if (sept->hn_p[i] == &hndl) { // Ok, go right, then as far as we can to the left: SeptNode * lsrch = sept->children[i+1]; SeptNode * prev = sept; while (lsrch != nullptr) { prev = lsrch; lsrch = lsrch->children[0]; } if (prev != sept) { sept->hn_p[i] = prev->hn_p[0]; sept->prio[i] = prev->prio[0]; sept->hn_p[i]->parent = sept; prev->hn_p[0] = &hndl; sept = prev; i = 0; } // Now we have: // - sept is a leaf in the BTree // - i is the index of the child to remove from it for ( ; i < (N-1); i++) { sept->hn_p[i] = sept->hn_p[i+1]; sept->prio[i] = sept->prio[i+1]; if (sept->hn_p[i] == nullptr) { break; } } sept->hn_p[N-1] = nullptr; // Now if the node is underpopulated, we need to merge with or // borrow from a sibling if (i < N/2) { repop_node(sept, i); } return; } } } handle_t *find(const P &pval) { SeptNode * cursept = root_sept; while (cursept != nullptr) { int i; for (i = 0; i < N && cursept->hn_p[i] != nullptr; i++) { if (cursept->prio[i] == pval) { return cursept->hn_p[i]; } if (cursept->prio[i] > pval) { break; } } cursept = cursept->children[i]; } return nullptr; } bool is_queued(handle_t & hndl) noexcept { return hndl.parent != nullptr; } bool empty() noexcept { return root_sept == nullptr; } ~btree_set() { while (left_sept != nullptr) { remove(*(left_sept->hn_p[0])); } while (sn_reserve != nullptr) { auto *next = sn_reserve->parent; delete sn_reserve; sn_reserve = next; } } }; } #endif
[ "davmac@davmac.org" ]
davmac@davmac.org
f9179218d6bc73886f2bf8a643da83c9a086c171
2402e8faea0df1eedb7e3891556c00785025ccc0
/a286.cpp
4ee3e685423b76698a6cf386a0a0add9fcecbfaa
[]
no_license
vkt1992/OnlineCoding-Codeforce
86982bb8aa494727149de507c4b40f30df5d01f4
ad2105035bbcf8b300e5873a97120dbf742b0d5e
refs/heads/master
2021-01-10T01:29:58.410358
2015-11-30T03:08:29
2015-11-30T03:08:29
47,075,270
0
0
null
null
null
null
UTF-8
C++
false
false
2,141
cpp
#include <iostream> #include <stdio.h> #include <math.h> #include <utility> #include <algorithm> #include <set> #include <queue> #include <vector> #include <stack> #include <map> #include <stdlib.h> #include <string.h> using namespace std; char str[11],mystr[12]; int len,i; int palindrome(int pos1,int pos2) { while(pos1 < pos2) { if(str[pos1]!=str[pos2]) { return 0; } else { pos1++; pos2--; } } return 1; } int main() { int len,done=0,flag=0,stpos,lstpos; scanf("%s",str); len=strlen(str); stpos=0; lstpos=len; if(len==2) { if(str[0]==str[1]) { mystr[0]=str[0]; mystr[1]='c'; mystr[2]=str[1]; } else { mystr[0]=str[0]; mystr[1]=str[1]; mystr[2]=str[0]; } mystr[len+1]='\0'; printf("%s\n",mystr); } else if(len==1) { mystr[0]=str[0]; mystr[1]=str[0]; mystr[2]='\0'; printf("%s\n",mystr); } else { for(i=0;i<len/2;i++) { if(str[i]!=str[len-1-i]) { if(flag==1) { done=1; break; } if(palindrome(i+1,len-1-i)==1) { //cout<<"here\n"; mystr[stpos++]=str[i]; //cout<<"char: "<<str[i]<<endl; mystr[lstpos--]=str[i]; int lst=len-1-i,init=i+1; for(i=init;i<=lst;i++) { mystr[stpos++]=str[i]; //cout<<"inside char: "<<str[i]<<endl; } flag=1; break; } else if(palindrome(i,len-1-i-1)==1) { mystr[stpos++]=str[len-1-i]; mystr[lstpos--]=str[len-1-i]; int lst=len-1-i-1,init=i; for(i=init;i<=lst;i++) { mystr[stpos++]=str[i]; } flag=1; break; } else { done=1; break; } flag=1; } else { mystr[stpos++]=str[i]; mystr[lstpos--]=str[len-1-i]; } } if(done==1) { printf("NA\n"); } else { mystr[len+1]='\0'; if(len%2!=0 && flag==0) { mystr[len/2]=str[len/2]; mystr[(len/2)+1]=str[len/2]; } else if(len%2==0 && flag==0) { mystr[len/2]='c'; } printf("%s\n",mystr); } } return 0; }
[ "vivekthakur1992@gmail.com" ]
vivekthakur1992@gmail.com
03d3ad02fd6a977edff7b123cd7ca52e7c5053f8
524c0f8983fef4c282922a19a9437a320ccd0c45
/aws-cpp-sdk-greengrassv2/include/aws/greengrassv2/GreengrassV2Client.h
d6b71119dec129605ed187bbd2c362e4589306ce
[ "Apache-2.0", "MIT", "JSON" ]
permissive
hardikmdev/aws-sdk-cpp
e79c39ad35433fbf41b3df7a90ac3b7bdb56728b
f34953a3f4cbd327db7c5340fcc140d63ac63e87
refs/heads/main
2023-09-06T03:43:07.646588
2021-11-16T20:27:23
2021-11-16T20:27:23
429,030,795
0
0
Apache-2.0
2021-11-17T12:08:03
2021-11-17T12:08:02
null
UTF-8
C++
false
false
80,051
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/greengrassv2/GreengrassV2_EXPORTS.h> #include <aws/greengrassv2/GreengrassV2Errors.h> #include <aws/core/client/AWSError.h> #include <aws/core/client/ClientConfiguration.h> #include <aws/core/client/AWSClient.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/greengrassv2/model/BatchAssociateClientDeviceWithCoreDeviceResult.h> #include <aws/greengrassv2/model/BatchDisassociateClientDeviceFromCoreDeviceResult.h> #include <aws/greengrassv2/model/CancelDeploymentResult.h> #include <aws/greengrassv2/model/CreateComponentVersionResult.h> #include <aws/greengrassv2/model/CreateDeploymentResult.h> #include <aws/greengrassv2/model/DescribeComponentResult.h> #include <aws/greengrassv2/model/GetComponentResult.h> #include <aws/greengrassv2/model/GetComponentVersionArtifactResult.h> #include <aws/greengrassv2/model/GetCoreDeviceResult.h> #include <aws/greengrassv2/model/GetDeploymentResult.h> #include <aws/greengrassv2/model/ListClientDevicesAssociatedWithCoreDeviceResult.h> #include <aws/greengrassv2/model/ListComponentVersionsResult.h> #include <aws/greengrassv2/model/ListComponentsResult.h> #include <aws/greengrassv2/model/ListCoreDevicesResult.h> #include <aws/greengrassv2/model/ListDeploymentsResult.h> #include <aws/greengrassv2/model/ListEffectiveDeploymentsResult.h> #include <aws/greengrassv2/model/ListInstalledComponentsResult.h> #include <aws/greengrassv2/model/ListTagsForResourceResult.h> #include <aws/greengrassv2/model/ResolveComponentCandidatesResult.h> #include <aws/greengrassv2/model/TagResourceResult.h> #include <aws/greengrassv2/model/UntagResourceResult.h> #include <aws/core/NoResult.h> #include <aws/core/client/AsyncCallerContext.h> #include <aws/core/http/HttpTypes.h> #include <future> #include <functional> namespace Aws { namespace Http { class HttpClient; class HttpClientFactory; } // namespace Http namespace Utils { template< typename R, typename E> class Outcome; namespace Threading { class Executor; } // namespace Threading } // namespace Utils namespace Auth { class AWSCredentials; class AWSCredentialsProvider; } // namespace Auth namespace Client { class RetryStrategy; } // namespace Client namespace GreengrassV2 { namespace Model { class BatchAssociateClientDeviceWithCoreDeviceRequest; class BatchDisassociateClientDeviceFromCoreDeviceRequest; class CancelDeploymentRequest; class CreateComponentVersionRequest; class CreateDeploymentRequest; class DeleteComponentRequest; class DeleteCoreDeviceRequest; class DescribeComponentRequest; class GetComponentRequest; class GetComponentVersionArtifactRequest; class GetCoreDeviceRequest; class GetDeploymentRequest; class ListClientDevicesAssociatedWithCoreDeviceRequest; class ListComponentVersionsRequest; class ListComponentsRequest; class ListCoreDevicesRequest; class ListDeploymentsRequest; class ListEffectiveDeploymentsRequest; class ListInstalledComponentsRequest; class ListTagsForResourceRequest; class ResolveComponentCandidatesRequest; class TagResourceRequest; class UntagResourceRequest; typedef Aws::Utils::Outcome<BatchAssociateClientDeviceWithCoreDeviceResult, GreengrassV2Error> BatchAssociateClientDeviceWithCoreDeviceOutcome; typedef Aws::Utils::Outcome<BatchDisassociateClientDeviceFromCoreDeviceResult, GreengrassV2Error> BatchDisassociateClientDeviceFromCoreDeviceOutcome; typedef Aws::Utils::Outcome<CancelDeploymentResult, GreengrassV2Error> CancelDeploymentOutcome; typedef Aws::Utils::Outcome<CreateComponentVersionResult, GreengrassV2Error> CreateComponentVersionOutcome; typedef Aws::Utils::Outcome<CreateDeploymentResult, GreengrassV2Error> CreateDeploymentOutcome; typedef Aws::Utils::Outcome<Aws::NoResult, GreengrassV2Error> DeleteComponentOutcome; typedef Aws::Utils::Outcome<Aws::NoResult, GreengrassV2Error> DeleteCoreDeviceOutcome; typedef Aws::Utils::Outcome<DescribeComponentResult, GreengrassV2Error> DescribeComponentOutcome; typedef Aws::Utils::Outcome<GetComponentResult, GreengrassV2Error> GetComponentOutcome; typedef Aws::Utils::Outcome<GetComponentVersionArtifactResult, GreengrassV2Error> GetComponentVersionArtifactOutcome; typedef Aws::Utils::Outcome<GetCoreDeviceResult, GreengrassV2Error> GetCoreDeviceOutcome; typedef Aws::Utils::Outcome<GetDeploymentResult, GreengrassV2Error> GetDeploymentOutcome; typedef Aws::Utils::Outcome<ListClientDevicesAssociatedWithCoreDeviceResult, GreengrassV2Error> ListClientDevicesAssociatedWithCoreDeviceOutcome; typedef Aws::Utils::Outcome<ListComponentVersionsResult, GreengrassV2Error> ListComponentVersionsOutcome; typedef Aws::Utils::Outcome<ListComponentsResult, GreengrassV2Error> ListComponentsOutcome; typedef Aws::Utils::Outcome<ListCoreDevicesResult, GreengrassV2Error> ListCoreDevicesOutcome; typedef Aws::Utils::Outcome<ListDeploymentsResult, GreengrassV2Error> ListDeploymentsOutcome; typedef Aws::Utils::Outcome<ListEffectiveDeploymentsResult, GreengrassV2Error> ListEffectiveDeploymentsOutcome; typedef Aws::Utils::Outcome<ListInstalledComponentsResult, GreengrassV2Error> ListInstalledComponentsOutcome; typedef Aws::Utils::Outcome<ListTagsForResourceResult, GreengrassV2Error> ListTagsForResourceOutcome; typedef Aws::Utils::Outcome<ResolveComponentCandidatesResult, GreengrassV2Error> ResolveComponentCandidatesOutcome; typedef Aws::Utils::Outcome<TagResourceResult, GreengrassV2Error> TagResourceOutcome; typedef Aws::Utils::Outcome<UntagResourceResult, GreengrassV2Error> UntagResourceOutcome; typedef std::future<BatchAssociateClientDeviceWithCoreDeviceOutcome> BatchAssociateClientDeviceWithCoreDeviceOutcomeCallable; typedef std::future<BatchDisassociateClientDeviceFromCoreDeviceOutcome> BatchDisassociateClientDeviceFromCoreDeviceOutcomeCallable; typedef std::future<CancelDeploymentOutcome> CancelDeploymentOutcomeCallable; typedef std::future<CreateComponentVersionOutcome> CreateComponentVersionOutcomeCallable; typedef std::future<CreateDeploymentOutcome> CreateDeploymentOutcomeCallable; typedef std::future<DeleteComponentOutcome> DeleteComponentOutcomeCallable; typedef std::future<DeleteCoreDeviceOutcome> DeleteCoreDeviceOutcomeCallable; typedef std::future<DescribeComponentOutcome> DescribeComponentOutcomeCallable; typedef std::future<GetComponentOutcome> GetComponentOutcomeCallable; typedef std::future<GetComponentVersionArtifactOutcome> GetComponentVersionArtifactOutcomeCallable; typedef std::future<GetCoreDeviceOutcome> GetCoreDeviceOutcomeCallable; typedef std::future<GetDeploymentOutcome> GetDeploymentOutcomeCallable; typedef std::future<ListClientDevicesAssociatedWithCoreDeviceOutcome> ListClientDevicesAssociatedWithCoreDeviceOutcomeCallable; typedef std::future<ListComponentVersionsOutcome> ListComponentVersionsOutcomeCallable; typedef std::future<ListComponentsOutcome> ListComponentsOutcomeCallable; typedef std::future<ListCoreDevicesOutcome> ListCoreDevicesOutcomeCallable; typedef std::future<ListDeploymentsOutcome> ListDeploymentsOutcomeCallable; typedef std::future<ListEffectiveDeploymentsOutcome> ListEffectiveDeploymentsOutcomeCallable; typedef std::future<ListInstalledComponentsOutcome> ListInstalledComponentsOutcomeCallable; typedef std::future<ListTagsForResourceOutcome> ListTagsForResourceOutcomeCallable; typedef std::future<ResolveComponentCandidatesOutcome> ResolveComponentCandidatesOutcomeCallable; typedef std::future<TagResourceOutcome> TagResourceOutcomeCallable; typedef std::future<UntagResourceOutcome> UntagResourceOutcomeCallable; } // namespace Model class GreengrassV2Client; typedef std::function<void(const GreengrassV2Client*, const Model::BatchAssociateClientDeviceWithCoreDeviceRequest&, const Model::BatchAssociateClientDeviceWithCoreDeviceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > BatchAssociateClientDeviceWithCoreDeviceResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::BatchDisassociateClientDeviceFromCoreDeviceRequest&, const Model::BatchDisassociateClientDeviceFromCoreDeviceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > BatchDisassociateClientDeviceFromCoreDeviceResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::CancelDeploymentRequest&, const Model::CancelDeploymentOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > CancelDeploymentResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::CreateComponentVersionRequest&, const Model::CreateComponentVersionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > CreateComponentVersionResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::CreateDeploymentRequest&, const Model::CreateDeploymentOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > CreateDeploymentResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::DeleteComponentRequest&, const Model::DeleteComponentOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DeleteComponentResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::DeleteCoreDeviceRequest&, const Model::DeleteCoreDeviceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DeleteCoreDeviceResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::DescribeComponentRequest&, const Model::DescribeComponentOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DescribeComponentResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::GetComponentRequest&, const Model::GetComponentOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > GetComponentResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::GetComponentVersionArtifactRequest&, const Model::GetComponentVersionArtifactOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > GetComponentVersionArtifactResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::GetCoreDeviceRequest&, const Model::GetCoreDeviceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > GetCoreDeviceResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::GetDeploymentRequest&, const Model::GetDeploymentOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > GetDeploymentResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::ListClientDevicesAssociatedWithCoreDeviceRequest&, const Model::ListClientDevicesAssociatedWithCoreDeviceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListClientDevicesAssociatedWithCoreDeviceResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::ListComponentVersionsRequest&, const Model::ListComponentVersionsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListComponentVersionsResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::ListComponentsRequest&, const Model::ListComponentsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListComponentsResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::ListCoreDevicesRequest&, const Model::ListCoreDevicesOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListCoreDevicesResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::ListDeploymentsRequest&, const Model::ListDeploymentsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListDeploymentsResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::ListEffectiveDeploymentsRequest&, const Model::ListEffectiveDeploymentsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListEffectiveDeploymentsResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::ListInstalledComponentsRequest&, const Model::ListInstalledComponentsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListInstalledComponentsResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::ListTagsForResourceRequest&, const Model::ListTagsForResourceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListTagsForResourceResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::ResolveComponentCandidatesRequest&, const Model::ResolveComponentCandidatesOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ResolveComponentCandidatesResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::TagResourceRequest&, const Model::TagResourceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > TagResourceResponseReceivedHandler; typedef std::function<void(const GreengrassV2Client*, const Model::UntagResourceRequest&, const Model::UntagResourceOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > UntagResourceResponseReceivedHandler; /** * <p>IoT Greengrass brings local compute, messaging, data management, sync, and ML * inference capabilities to edge devices. This enables devices to collect and * analyze data closer to the source of information, react autonomously to local * events, and communicate securely with each other on local networks. Local * devices can also communicate securely with Amazon Web Services IoT Core and * export IoT data to the Amazon Web Services Cloud. IoT Greengrass developers can * use Lambda functions and components to create and deploy applications to fleets * of edge devices for local operation.</p> <p>IoT Greengrass Version 2 provides a * new major version of the IoT Greengrass Core software, new APIs, and a new * console. Use this API reference to learn how to use the IoT Greengrass V2 API * operations to manage components, manage deployments, and core devices.</p> * <p>For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/what-is-iot-greengrass.html">What * is IoT Greengrass?</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p> */ class AWS_GREENGRASSV2_API GreengrassV2Client : public Aws::Client::AWSJsonClient { public: typedef Aws::Client::AWSJsonClient BASECLASS; /** * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ GreengrassV2Client(const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); /** * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ GreengrassV2Client(const Aws::Auth::AWSCredentials& credentials, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); /** * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied, * the default http client factory will be used */ GreengrassV2Client(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); virtual ~GreengrassV2Client(); /** * <p>Associate a list of client devices with a core device. Use this API operation * to specify which client devices can discover a core device through cloud * discovery. With cloud discovery, client devices connect to IoT Greengrass to * retrieve associated core devices' connectivity information and certificates. For * more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/configure-cloud-discovery.html">Configure * cloud discovery</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p> * <p>Client devices are local IoT devices that connect to and communicate with an * IoT Greengrass core device over MQTT. You can connect client devices to a core * device to sync MQTT messages and data to Amazon Web Services IoT Core and * interact with client devices in Greengrass components. For more information, see * <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/interact-with-local-iot-devices.html">Interact * with local IoT devices</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p> * <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/BatchAssociateClientDeviceWithCoreDevice">AWS * API Reference</a></p> */ virtual Model::BatchAssociateClientDeviceWithCoreDeviceOutcome BatchAssociateClientDeviceWithCoreDevice(const Model::BatchAssociateClientDeviceWithCoreDeviceRequest& request) const; /** * <p>Associate a list of client devices with a core device. Use this API operation * to specify which client devices can discover a core device through cloud * discovery. With cloud discovery, client devices connect to IoT Greengrass to * retrieve associated core devices' connectivity information and certificates. For * more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/configure-cloud-discovery.html">Configure * cloud discovery</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p> * <p>Client devices are local IoT devices that connect to and communicate with an * IoT Greengrass core device over MQTT. You can connect client devices to a core * device to sync MQTT messages and data to Amazon Web Services IoT Core and * interact with client devices in Greengrass components. For more information, see * <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/interact-with-local-iot-devices.html">Interact * with local IoT devices</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p> * <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/BatchAssociateClientDeviceWithCoreDevice">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::BatchAssociateClientDeviceWithCoreDeviceOutcomeCallable BatchAssociateClientDeviceWithCoreDeviceCallable(const Model::BatchAssociateClientDeviceWithCoreDeviceRequest& request) const; /** * <p>Associate a list of client devices with a core device. Use this API operation * to specify which client devices can discover a core device through cloud * discovery. With cloud discovery, client devices connect to IoT Greengrass to * retrieve associated core devices' connectivity information and certificates. For * more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/configure-cloud-discovery.html">Configure * cloud discovery</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p> * <p>Client devices are local IoT devices that connect to and communicate with an * IoT Greengrass core device over MQTT. You can connect client devices to a core * device to sync MQTT messages and data to Amazon Web Services IoT Core and * interact with client devices in Greengrass components. For more information, see * <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/interact-with-local-iot-devices.html">Interact * with local IoT devices</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p> * <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/BatchAssociateClientDeviceWithCoreDevice">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void BatchAssociateClientDeviceWithCoreDeviceAsync(const Model::BatchAssociateClientDeviceWithCoreDeviceRequest& request, const BatchAssociateClientDeviceWithCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Disassociate a list of client devices from a core device. After you * disassociate a client device from a core device, the client device won't be able * to use cloud discovery to retrieve the core device's connectivity information * and certificates.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/BatchDisassociateClientDeviceFromCoreDevice">AWS * API Reference</a></p> */ virtual Model::BatchDisassociateClientDeviceFromCoreDeviceOutcome BatchDisassociateClientDeviceFromCoreDevice(const Model::BatchDisassociateClientDeviceFromCoreDeviceRequest& request) const; /** * <p>Disassociate a list of client devices from a core device. After you * disassociate a client device from a core device, the client device won't be able * to use cloud discovery to retrieve the core device's connectivity information * and certificates.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/BatchDisassociateClientDeviceFromCoreDevice">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::BatchDisassociateClientDeviceFromCoreDeviceOutcomeCallable BatchDisassociateClientDeviceFromCoreDeviceCallable(const Model::BatchDisassociateClientDeviceFromCoreDeviceRequest& request) const; /** * <p>Disassociate a list of client devices from a core device. After you * disassociate a client device from a core device, the client device won't be able * to use cloud discovery to retrieve the core device's connectivity information * and certificates.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/BatchDisassociateClientDeviceFromCoreDevice">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void BatchDisassociateClientDeviceFromCoreDeviceAsync(const Model::BatchDisassociateClientDeviceFromCoreDeviceRequest& request, const BatchDisassociateClientDeviceFromCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Cancels a deployment. This operation cancels the deployment for devices that * haven't yet received it. If a device already received the deployment, this * operation doesn't change anything for that device.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/CancelDeployment">AWS * API Reference</a></p> */ virtual Model::CancelDeploymentOutcome CancelDeployment(const Model::CancelDeploymentRequest& request) const; /** * <p>Cancels a deployment. This operation cancels the deployment for devices that * haven't yet received it. If a device already received the deployment, this * operation doesn't change anything for that device.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/CancelDeployment">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::CancelDeploymentOutcomeCallable CancelDeploymentCallable(const Model::CancelDeploymentRequest& request) const; /** * <p>Cancels a deployment. This operation cancels the deployment for devices that * haven't yet received it. If a device already received the deployment, this * operation doesn't change anything for that device.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/CancelDeployment">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void CancelDeploymentAsync(const Model::CancelDeploymentRequest& request, const CancelDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Creates a component. Components are software that run on Greengrass core * devices. After you develop and test a component on your core device, you can use * this operation to upload your component to IoT Greengrass. Then, you can deploy * the component to other core devices.</p> <p>You can use this operation to do the * following:</p> <ul> <li> <p> <b>Create components from recipes</b> </p> * <p>Create a component from a recipe, which is a file that defines the * component's metadata, parameters, dependencies, lifecycle, artifacts, and * platform capability. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/component-recipe-reference.html">IoT * Greengrass component recipe reference</a> in the <i>IoT Greengrass V2 Developer * Guide</i>.</p> <p>To create a component from a recipe, specify * <code>inlineRecipe</code> when you call this operation.</p> </li> <li> <p> * <b>Create components from Lambda functions</b> </p> <p>Create a component from * an Lambda function that runs on IoT Greengrass. This creates a recipe and * artifacts from the Lambda function's deployment package. You can use this * operation to migrate Lambda functions from IoT Greengrass V1 to IoT Greengrass * V2.</p> <p>This function only accepts Lambda functions that use the following * runtimes:</p> <ul> <li> <p>Python 2.7 – <code>python2.7</code> </p> </li> <li> * <p>Python 3.7 – <code>python3.7</code> </p> </li> <li> <p>Python 3.8 – * <code>python3.8</code> </p> </li> <li> <p>Java 8 – <code>java8</code> </p> </li> * <li> <p>Node.js 10 – <code>nodejs10.x</code> </p> </li> <li> <p>Node.js 12 – * <code>nodejs12.x</code> </p> </li> </ul> <p>To create a component from a Lambda * function, specify <code>lambdaFunction</code> when you call this operation.</p> * <p>IoT Greengrass currently supports Lambda functions on only Linux core * devices.</p> </li> </ul><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/CreateComponentVersion">AWS * API Reference</a></p> */ virtual Model::CreateComponentVersionOutcome CreateComponentVersion(const Model::CreateComponentVersionRequest& request) const; /** * <p>Creates a component. Components are software that run on Greengrass core * devices. After you develop and test a component on your core device, you can use * this operation to upload your component to IoT Greengrass. Then, you can deploy * the component to other core devices.</p> <p>You can use this operation to do the * following:</p> <ul> <li> <p> <b>Create components from recipes</b> </p> * <p>Create a component from a recipe, which is a file that defines the * component's metadata, parameters, dependencies, lifecycle, artifacts, and * platform capability. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/component-recipe-reference.html">IoT * Greengrass component recipe reference</a> in the <i>IoT Greengrass V2 Developer * Guide</i>.</p> <p>To create a component from a recipe, specify * <code>inlineRecipe</code> when you call this operation.</p> </li> <li> <p> * <b>Create components from Lambda functions</b> </p> <p>Create a component from * an Lambda function that runs on IoT Greengrass. This creates a recipe and * artifacts from the Lambda function's deployment package. You can use this * operation to migrate Lambda functions from IoT Greengrass V1 to IoT Greengrass * V2.</p> <p>This function only accepts Lambda functions that use the following * runtimes:</p> <ul> <li> <p>Python 2.7 – <code>python2.7</code> </p> </li> <li> * <p>Python 3.7 – <code>python3.7</code> </p> </li> <li> <p>Python 3.8 – * <code>python3.8</code> </p> </li> <li> <p>Java 8 – <code>java8</code> </p> </li> * <li> <p>Node.js 10 – <code>nodejs10.x</code> </p> </li> <li> <p>Node.js 12 – * <code>nodejs12.x</code> </p> </li> </ul> <p>To create a component from a Lambda * function, specify <code>lambdaFunction</code> when you call this operation.</p> * <p>IoT Greengrass currently supports Lambda functions on only Linux core * devices.</p> </li> </ul><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/CreateComponentVersion">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::CreateComponentVersionOutcomeCallable CreateComponentVersionCallable(const Model::CreateComponentVersionRequest& request) const; /** * <p>Creates a component. Components are software that run on Greengrass core * devices. After you develop and test a component on your core device, you can use * this operation to upload your component to IoT Greengrass. Then, you can deploy * the component to other core devices.</p> <p>You can use this operation to do the * following:</p> <ul> <li> <p> <b>Create components from recipes</b> </p> * <p>Create a component from a recipe, which is a file that defines the * component's metadata, parameters, dependencies, lifecycle, artifacts, and * platform capability. For more information, see <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/component-recipe-reference.html">IoT * Greengrass component recipe reference</a> in the <i>IoT Greengrass V2 Developer * Guide</i>.</p> <p>To create a component from a recipe, specify * <code>inlineRecipe</code> when you call this operation.</p> </li> <li> <p> * <b>Create components from Lambda functions</b> </p> <p>Create a component from * an Lambda function that runs on IoT Greengrass. This creates a recipe and * artifacts from the Lambda function's deployment package. You can use this * operation to migrate Lambda functions from IoT Greengrass V1 to IoT Greengrass * V2.</p> <p>This function only accepts Lambda functions that use the following * runtimes:</p> <ul> <li> <p>Python 2.7 – <code>python2.7</code> </p> </li> <li> * <p>Python 3.7 – <code>python3.7</code> </p> </li> <li> <p>Python 3.8 – * <code>python3.8</code> </p> </li> <li> <p>Java 8 – <code>java8</code> </p> </li> * <li> <p>Node.js 10 – <code>nodejs10.x</code> </p> </li> <li> <p>Node.js 12 – * <code>nodejs12.x</code> </p> </li> </ul> <p>To create a component from a Lambda * function, specify <code>lambdaFunction</code> when you call this operation.</p> * <p>IoT Greengrass currently supports Lambda functions on only Linux core * devices.</p> </li> </ul><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/CreateComponentVersion">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void CreateComponentVersionAsync(const Model::CreateComponentVersionRequest& request, const CreateComponentVersionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Creates a continuous deployment for a target, which is a Greengrass core * device or group of core devices. When you add a new core device to a group of * core devices that has a deployment, IoT Greengrass deploys that group's * deployment to the new device.</p> <p>You can define one deployment for each * target. When you create a new deployment for a target that has an existing * deployment, you replace the previous deployment. IoT Greengrass applies the new * deployment to the target devices.</p> <p>Every deployment has a revision number * that indicates how many deployment revisions you define for a target. Use this * operation to create a new revision of an existing deployment. This operation * returns the revision number of the new deployment when you create it.</p> <p>For * more information, see the <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/create-deployments.html">Create * deployments</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/CreateDeployment">AWS * API Reference</a></p> */ virtual Model::CreateDeploymentOutcome CreateDeployment(const Model::CreateDeploymentRequest& request) const; /** * <p>Creates a continuous deployment for a target, which is a Greengrass core * device or group of core devices. When you add a new core device to a group of * core devices that has a deployment, IoT Greengrass deploys that group's * deployment to the new device.</p> <p>You can define one deployment for each * target. When you create a new deployment for a target that has an existing * deployment, you replace the previous deployment. IoT Greengrass applies the new * deployment to the target devices.</p> <p>Every deployment has a revision number * that indicates how many deployment revisions you define for a target. Use this * operation to create a new revision of an existing deployment. This operation * returns the revision number of the new deployment when you create it.</p> <p>For * more information, see the <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/create-deployments.html">Create * deployments</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/CreateDeployment">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::CreateDeploymentOutcomeCallable CreateDeploymentCallable(const Model::CreateDeploymentRequest& request) const; /** * <p>Creates a continuous deployment for a target, which is a Greengrass core * device or group of core devices. When you add a new core device to a group of * core devices that has a deployment, IoT Greengrass deploys that group's * deployment to the new device.</p> <p>You can define one deployment for each * target. When you create a new deployment for a target that has an existing * deployment, you replace the previous deployment. IoT Greengrass applies the new * deployment to the target devices.</p> <p>Every deployment has a revision number * that indicates how many deployment revisions you define for a target. Use this * operation to create a new revision of an existing deployment. This operation * returns the revision number of the new deployment when you create it.</p> <p>For * more information, see the <a * href="https://docs.aws.amazon.com/greengrass/v2/developerguide/create-deployments.html">Create * deployments</a> in the <i>IoT Greengrass V2 Developer Guide</i>.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/CreateDeployment">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void CreateDeploymentAsync(const Model::CreateDeploymentRequest& request, const CreateDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Deletes a version of a component from IoT Greengrass.</p> <p>This * operation deletes the component's recipe and artifacts. As a result, deployments * that refer to this component version will fail. If you have deployments that use * this component version, you can remove the component from the deployment or * update the deployment to use a valid version.</p> <p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DeleteComponent">AWS * API Reference</a></p> */ virtual Model::DeleteComponentOutcome DeleteComponent(const Model::DeleteComponentRequest& request) const; /** * <p>Deletes a version of a component from IoT Greengrass.</p> <p>This * operation deletes the component's recipe and artifacts. As a result, deployments * that refer to this component version will fail. If you have deployments that use * this component version, you can remove the component from the deployment or * update the deployment to use a valid version.</p> <p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DeleteComponent">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::DeleteComponentOutcomeCallable DeleteComponentCallable(const Model::DeleteComponentRequest& request) const; /** * <p>Deletes a version of a component from IoT Greengrass.</p> <p>This * operation deletes the component's recipe and artifacts. As a result, deployments * that refer to this component version will fail. If you have deployments that use * this component version, you can remove the component from the deployment or * update the deployment to use a valid version.</p> <p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DeleteComponent">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void DeleteComponentAsync(const Model::DeleteComponentRequest& request, const DeleteComponentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Deletes a Greengrass core device, which is an IoT thing. This operation * removes the core device from the list of core devices. This operation doesn't * delete the IoT thing. For more information about how to delete the IoT thing, * see <a * href="https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteThing.html">DeleteThing</a> * in the <i>IoT API Reference</i>.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DeleteCoreDevice">AWS * API Reference</a></p> */ virtual Model::DeleteCoreDeviceOutcome DeleteCoreDevice(const Model::DeleteCoreDeviceRequest& request) const; /** * <p>Deletes a Greengrass core device, which is an IoT thing. This operation * removes the core device from the list of core devices. This operation doesn't * delete the IoT thing. For more information about how to delete the IoT thing, * see <a * href="https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteThing.html">DeleteThing</a> * in the <i>IoT API Reference</i>.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DeleteCoreDevice">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::DeleteCoreDeviceOutcomeCallable DeleteCoreDeviceCallable(const Model::DeleteCoreDeviceRequest& request) const; /** * <p>Deletes a Greengrass core device, which is an IoT thing. This operation * removes the core device from the list of core devices. This operation doesn't * delete the IoT thing. For more information about how to delete the IoT thing, * see <a * href="https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteThing.html">DeleteThing</a> * in the <i>IoT API Reference</i>.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DeleteCoreDevice">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void DeleteCoreDeviceAsync(const Model::DeleteCoreDeviceRequest& request, const DeleteCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves metadata for a version of a component.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DescribeComponent">AWS * API Reference</a></p> */ virtual Model::DescribeComponentOutcome DescribeComponent(const Model::DescribeComponentRequest& request) const; /** * <p>Retrieves metadata for a version of a component.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DescribeComponent">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::DescribeComponentOutcomeCallable DescribeComponentCallable(const Model::DescribeComponentRequest& request) const; /** * <p>Retrieves metadata for a version of a component.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/DescribeComponent">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void DescribeComponentAsync(const Model::DescribeComponentRequest& request, const DescribeComponentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Gets the recipe for a version of a component. Core devices can call this * operation to identify the artifacts and requirements to install a * component.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetComponent">AWS * API Reference</a></p> */ virtual Model::GetComponentOutcome GetComponent(const Model::GetComponentRequest& request) const; /** * <p>Gets the recipe for a version of a component. Core devices can call this * operation to identify the artifacts and requirements to install a * component.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetComponent">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::GetComponentOutcomeCallable GetComponentCallable(const Model::GetComponentRequest& request) const; /** * <p>Gets the recipe for a version of a component. Core devices can call this * operation to identify the artifacts and requirements to install a * component.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetComponent">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void GetComponentAsync(const Model::GetComponentRequest& request, const GetComponentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Gets the pre-signed URL to download a public component artifact. Core devices * call this operation to identify the URL that they can use to download an * artifact to install.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetComponentVersionArtifact">AWS * API Reference</a></p> */ virtual Model::GetComponentVersionArtifactOutcome GetComponentVersionArtifact(const Model::GetComponentVersionArtifactRequest& request) const; /** * <p>Gets the pre-signed URL to download a public component artifact. Core devices * call this operation to identify the URL that they can use to download an * artifact to install.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetComponentVersionArtifact">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::GetComponentVersionArtifactOutcomeCallable GetComponentVersionArtifactCallable(const Model::GetComponentVersionArtifactRequest& request) const; /** * <p>Gets the pre-signed URL to download a public component artifact. Core devices * call this operation to identify the URL that they can use to download an * artifact to install.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetComponentVersionArtifact">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void GetComponentVersionArtifactAsync(const Model::GetComponentVersionArtifactRequest& request, const GetComponentVersionArtifactResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves metadata for a Greengrass core device.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetCoreDevice">AWS * API Reference</a></p> */ virtual Model::GetCoreDeviceOutcome GetCoreDevice(const Model::GetCoreDeviceRequest& request) const; /** * <p>Retrieves metadata for a Greengrass core device.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetCoreDevice">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::GetCoreDeviceOutcomeCallable GetCoreDeviceCallable(const Model::GetCoreDeviceRequest& request) const; /** * <p>Retrieves metadata for a Greengrass core device.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetCoreDevice">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void GetCoreDeviceAsync(const Model::GetCoreDeviceRequest& request, const GetCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Gets a deployment. Deployments define the components that run on Greengrass * core devices.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetDeployment">AWS * API Reference</a></p> */ virtual Model::GetDeploymentOutcome GetDeployment(const Model::GetDeploymentRequest& request) const; /** * <p>Gets a deployment. Deployments define the components that run on Greengrass * core devices.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetDeployment">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::GetDeploymentOutcomeCallable GetDeploymentCallable(const Model::GetDeploymentRequest& request) const; /** * <p>Gets a deployment. Deployments define the components that run on Greengrass * core devices.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/GetDeployment">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void GetDeploymentAsync(const Model::GetDeploymentRequest& request, const GetDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves a paginated list of client devices that are associated with a core * device.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListClientDevicesAssociatedWithCoreDevice">AWS * API Reference</a></p> */ virtual Model::ListClientDevicesAssociatedWithCoreDeviceOutcome ListClientDevicesAssociatedWithCoreDevice(const Model::ListClientDevicesAssociatedWithCoreDeviceRequest& request) const; /** * <p>Retrieves a paginated list of client devices that are associated with a core * device.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListClientDevicesAssociatedWithCoreDevice">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListClientDevicesAssociatedWithCoreDeviceOutcomeCallable ListClientDevicesAssociatedWithCoreDeviceCallable(const Model::ListClientDevicesAssociatedWithCoreDeviceRequest& request) const; /** * <p>Retrieves a paginated list of client devices that are associated with a core * device.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListClientDevicesAssociatedWithCoreDevice">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListClientDevicesAssociatedWithCoreDeviceAsync(const Model::ListClientDevicesAssociatedWithCoreDeviceRequest& request, const ListClientDevicesAssociatedWithCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves a paginated list of all versions for a component. Greater versions * are listed first.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListComponentVersions">AWS * API Reference</a></p> */ virtual Model::ListComponentVersionsOutcome ListComponentVersions(const Model::ListComponentVersionsRequest& request) const; /** * <p>Retrieves a paginated list of all versions for a component. Greater versions * are listed first.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListComponentVersions">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListComponentVersionsOutcomeCallable ListComponentVersionsCallable(const Model::ListComponentVersionsRequest& request) const; /** * <p>Retrieves a paginated list of all versions for a component. Greater versions * are listed first.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListComponentVersions">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListComponentVersionsAsync(const Model::ListComponentVersionsRequest& request, const ListComponentVersionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves a paginated list of component summaries. This list includes * components that you have permission to view.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListComponents">AWS * API Reference</a></p> */ virtual Model::ListComponentsOutcome ListComponents(const Model::ListComponentsRequest& request) const; /** * <p>Retrieves a paginated list of component summaries. This list includes * components that you have permission to view.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListComponents">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListComponentsOutcomeCallable ListComponentsCallable(const Model::ListComponentsRequest& request) const; /** * <p>Retrieves a paginated list of component summaries. This list includes * components that you have permission to view.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListComponents">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListComponentsAsync(const Model::ListComponentsRequest& request, const ListComponentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves a paginated list of Greengrass core devices.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListCoreDevices">AWS * API Reference</a></p> */ virtual Model::ListCoreDevicesOutcome ListCoreDevices(const Model::ListCoreDevicesRequest& request) const; /** * <p>Retrieves a paginated list of Greengrass core devices.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListCoreDevices">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListCoreDevicesOutcomeCallable ListCoreDevicesCallable(const Model::ListCoreDevicesRequest& request) const; /** * <p>Retrieves a paginated list of Greengrass core devices.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListCoreDevices">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListCoreDevicesAsync(const Model::ListCoreDevicesRequest& request, const ListCoreDevicesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves a paginated list of deployments.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListDeployments">AWS * API Reference</a></p> */ virtual Model::ListDeploymentsOutcome ListDeployments(const Model::ListDeploymentsRequest& request) const; /** * <p>Retrieves a paginated list of deployments.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListDeployments">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListDeploymentsOutcomeCallable ListDeploymentsCallable(const Model::ListDeploymentsRequest& request) const; /** * <p>Retrieves a paginated list of deployments.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListDeployments">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListDeploymentsAsync(const Model::ListDeploymentsRequest& request, const ListDeploymentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves a paginated list of deployment jobs that IoT Greengrass sends to * Greengrass core devices.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListEffectiveDeployments">AWS * API Reference</a></p> */ virtual Model::ListEffectiveDeploymentsOutcome ListEffectiveDeployments(const Model::ListEffectiveDeploymentsRequest& request) const; /** * <p>Retrieves a paginated list of deployment jobs that IoT Greengrass sends to * Greengrass core devices.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListEffectiveDeployments">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListEffectiveDeploymentsOutcomeCallable ListEffectiveDeploymentsCallable(const Model::ListEffectiveDeploymentsRequest& request) const; /** * <p>Retrieves a paginated list of deployment jobs that IoT Greengrass sends to * Greengrass core devices.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListEffectiveDeployments">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListEffectiveDeploymentsAsync(const Model::ListEffectiveDeploymentsRequest& request, const ListEffectiveDeploymentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves a paginated list of the components that a Greengrass core device * runs.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListInstalledComponents">AWS * API Reference</a></p> */ virtual Model::ListInstalledComponentsOutcome ListInstalledComponents(const Model::ListInstalledComponentsRequest& request) const; /** * <p>Retrieves a paginated list of the components that a Greengrass core device * runs.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListInstalledComponents">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListInstalledComponentsOutcomeCallable ListInstalledComponentsCallable(const Model::ListInstalledComponentsRequest& request) const; /** * <p>Retrieves a paginated list of the components that a Greengrass core device * runs.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListInstalledComponents">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListInstalledComponentsAsync(const Model::ListInstalledComponentsRequest& request, const ListInstalledComponentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves the list of tags for an IoT Greengrass resource.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListTagsForResource">AWS * API Reference</a></p> */ virtual Model::ListTagsForResourceOutcome ListTagsForResource(const Model::ListTagsForResourceRequest& request) const; /** * <p>Retrieves the list of tags for an IoT Greengrass resource.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListTagsForResource">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ListTagsForResourceOutcomeCallable ListTagsForResourceCallable(const Model::ListTagsForResourceRequest& request) const; /** * <p>Retrieves the list of tags for an IoT Greengrass resource.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListTagsForResource">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ListTagsForResourceAsync(const Model::ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Retrieves a list of components that meet the component, version, and platform * requirements of a deployment. Greengrass core devices call this operation when * they receive a deployment to identify the components to install.</p> <p>This * operation identifies components that meet all dependency requirements for a * deployment. If the requirements conflict, then this operation returns an error * and the deployment fails. For example, this occurs if component <code>A</code> * requires version <code>&gt;2.0.0</code> and component <code>B</code> requires * version <code>&lt;2.0.0</code> of a component dependency.</p> <p>When you * specify the component candidates to resolve, IoT Greengrass compares each * component's digest from the core device with the component's digest in the * Amazon Web Services Cloud. If the digests don't match, then IoT Greengrass * specifies to use the version from the Amazon Web Services Cloud.</p> * <p>To use this operation, you must use the data plane API endpoint and * authenticate with an IoT device certificate. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/greengrass.html">IoT * Greengrass endpoints and quotas</a>.</p> <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ResolveComponentCandidates">AWS * API Reference</a></p> */ virtual Model::ResolveComponentCandidatesOutcome ResolveComponentCandidates(const Model::ResolveComponentCandidatesRequest& request) const; /** * <p>Retrieves a list of components that meet the component, version, and platform * requirements of a deployment. Greengrass core devices call this operation when * they receive a deployment to identify the components to install.</p> <p>This * operation identifies components that meet all dependency requirements for a * deployment. If the requirements conflict, then this operation returns an error * and the deployment fails. For example, this occurs if component <code>A</code> * requires version <code>&gt;2.0.0</code> and component <code>B</code> requires * version <code>&lt;2.0.0</code> of a component dependency.</p> <p>When you * specify the component candidates to resolve, IoT Greengrass compares each * component's digest from the core device with the component's digest in the * Amazon Web Services Cloud. If the digests don't match, then IoT Greengrass * specifies to use the version from the Amazon Web Services Cloud.</p> * <p>To use this operation, you must use the data plane API endpoint and * authenticate with an IoT device certificate. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/greengrass.html">IoT * Greengrass endpoints and quotas</a>.</p> <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ResolveComponentCandidates">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ResolveComponentCandidatesOutcomeCallable ResolveComponentCandidatesCallable(const Model::ResolveComponentCandidatesRequest& request) const; /** * <p>Retrieves a list of components that meet the component, version, and platform * requirements of a deployment. Greengrass core devices call this operation when * they receive a deployment to identify the components to install.</p> <p>This * operation identifies components that meet all dependency requirements for a * deployment. If the requirements conflict, then this operation returns an error * and the deployment fails. For example, this occurs if component <code>A</code> * requires version <code>&gt;2.0.0</code> and component <code>B</code> requires * version <code>&lt;2.0.0</code> of a component dependency.</p> <p>When you * specify the component candidates to resolve, IoT Greengrass compares each * component's digest from the core device with the component's digest in the * Amazon Web Services Cloud. If the digests don't match, then IoT Greengrass * specifies to use the version from the Amazon Web Services Cloud.</p> * <p>To use this operation, you must use the data plane API endpoint and * authenticate with an IoT device certificate. For more information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/greengrass.html">IoT * Greengrass endpoints and quotas</a>.</p> <p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ResolveComponentCandidates">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ResolveComponentCandidatesAsync(const Model::ResolveComponentCandidatesRequest& request, const ResolveComponentCandidatesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Adds tags to an IoT Greengrass resource. If a tag already exists for the * resource, this operation updates the tag's value.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/TagResource">AWS * API Reference</a></p> */ virtual Model::TagResourceOutcome TagResource(const Model::TagResourceRequest& request) const; /** * <p>Adds tags to an IoT Greengrass resource. If a tag already exists for the * resource, this operation updates the tag's value.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/TagResource">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::TagResourceOutcomeCallable TagResourceCallable(const Model::TagResourceRequest& request) const; /** * <p>Adds tags to an IoT Greengrass resource. If a tag already exists for the * resource, this operation updates the tag's value.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/TagResource">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void TagResourceAsync(const Model::TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; /** * <p>Removes a tag from an IoT Greengrass resource.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/UntagResource">AWS * API Reference</a></p> */ virtual Model::UntagResourceOutcome UntagResource(const Model::UntagResourceRequest& request) const; /** * <p>Removes a tag from an IoT Greengrass resource.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/UntagResource">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::UntagResourceOutcomeCallable UntagResourceCallable(const Model::UntagResourceRequest& request) const; /** * <p>Removes a tag from an IoT Greengrass resource.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/UntagResource">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void UntagResourceAsync(const Model::UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; void OverrideEndpoint(const Aws::String& endpoint); private: void init(const Aws::Client::ClientConfiguration& clientConfiguration); void BatchAssociateClientDeviceWithCoreDeviceAsyncHelper(const Model::BatchAssociateClientDeviceWithCoreDeviceRequest& request, const BatchAssociateClientDeviceWithCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void BatchDisassociateClientDeviceFromCoreDeviceAsyncHelper(const Model::BatchDisassociateClientDeviceFromCoreDeviceRequest& request, const BatchDisassociateClientDeviceFromCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void CancelDeploymentAsyncHelper(const Model::CancelDeploymentRequest& request, const CancelDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void CreateComponentVersionAsyncHelper(const Model::CreateComponentVersionRequest& request, const CreateComponentVersionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void CreateDeploymentAsyncHelper(const Model::CreateDeploymentRequest& request, const CreateDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void DeleteComponentAsyncHelper(const Model::DeleteComponentRequest& request, const DeleteComponentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void DeleteCoreDeviceAsyncHelper(const Model::DeleteCoreDeviceRequest& request, const DeleteCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void DescribeComponentAsyncHelper(const Model::DescribeComponentRequest& request, const DescribeComponentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void GetComponentAsyncHelper(const Model::GetComponentRequest& request, const GetComponentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void GetComponentVersionArtifactAsyncHelper(const Model::GetComponentVersionArtifactRequest& request, const GetComponentVersionArtifactResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void GetCoreDeviceAsyncHelper(const Model::GetCoreDeviceRequest& request, const GetCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void GetDeploymentAsyncHelper(const Model::GetDeploymentRequest& request, const GetDeploymentResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListClientDevicesAssociatedWithCoreDeviceAsyncHelper(const Model::ListClientDevicesAssociatedWithCoreDeviceRequest& request, const ListClientDevicesAssociatedWithCoreDeviceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListComponentVersionsAsyncHelper(const Model::ListComponentVersionsRequest& request, const ListComponentVersionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListComponentsAsyncHelper(const Model::ListComponentsRequest& request, const ListComponentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListCoreDevicesAsyncHelper(const Model::ListCoreDevicesRequest& request, const ListCoreDevicesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListDeploymentsAsyncHelper(const Model::ListDeploymentsRequest& request, const ListDeploymentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListEffectiveDeploymentsAsyncHelper(const Model::ListEffectiveDeploymentsRequest& request, const ListEffectiveDeploymentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListInstalledComponentsAsyncHelper(const Model::ListInstalledComponentsRequest& request, const ListInstalledComponentsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ListTagsForResourceAsyncHelper(const Model::ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void ResolveComponentCandidatesAsyncHelper(const Model::ResolveComponentCandidatesRequest& request, const ResolveComponentCandidatesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void TagResourceAsyncHelper(const Model::TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; void UntagResourceAsyncHelper(const Model::UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; Aws::String m_uri; Aws::String m_configScheme; std::shared_ptr<Aws::Utils::Threading::Executor> m_executor; }; } // namespace GreengrassV2 } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
67bc3a3fb315a9fce0089f0e5fadae6016e590ec
7d29954c47203863c457c04794725a5e320b8c9d
/elements/ether/ARPResponder.cc
040caa7b232f51dff0a77c9ebd63ace6e8b795d4
[ "MIT" ]
permissive
gitter-badger/NBA
879340c00c5d83e0187b0162ab2bc1f9dc3d6add
f85ce709eb0a54d0340cc74ffe2532ae9ece8541
refs/heads/master
2020-12-24T19:45:53.787219
2015-08-07T04:36:57
2015-08-07T04:36:57
40,404,246
0
0
null
2015-08-08T13:48:52
2015-08-08T13:48:52
null
UTF-8
C++
false
false
3,904
cc
#include "ARPResponder.hh" #include "../../lib/types.hh" #include "sstream" using namespace std; using namespace nba; int ARPResponder::initialize() { return 0; } // per-system configuration int ARPResponder::initialize_global() { // Put IP addr - Mac addr mapping into hashmap. std::vector<std::string>::iterator it; string ip_addr_str, eth_addr_str; uint32_t ip_addr_num; EtherAddress eth_addr_obj; for (it = _args.begin(); it != _args.end(); ++it) { std::string str = *it; stringstream stream(str); stream >> ip_addr_str; stream >> eth_addr_str; //printf("ip_addr:%s, eth_addr:%s\n", ip_addr.c_str(), eth_addr.c_str()); // TODO: It could be IP addr/mask, but for now, only IP addr is handled. (mask not yet). ip_addr_num = inet_addr(ip_addr_str.c_str()); eth_addr_obj = EtherAddress(eth_addr_str); std::pair<uint32_t, EtherAddress> _pair (ip_addr_num, eth_addr_obj); _addr_hashmap.insert(_pair); } return 0; }; // per-node configuration int ARPResponder::initialize_per_node() { return 0; }; int ARPResponder::configure(comp_thread_context *ctx, std::vector<std::string> &args) { _args = args; return 0; } int ARPResponder::process(int input_port, Packet *pkt) { struct ether_hdr *ethh = (struct ether_hdr *) pkt->data(); struct ether_arp *arp_pkt = (struct ether_arp *)(ethh + 1); // ARP header & src/dst addrs struct arphdr *arph = &arp_pkt->ea_hdr; // ARP request packet comes in.. if ( (ntohs(ethh->ether_type) != ETHER_TYPE_ARP) && (ntohs(arph->ar_op) != ARPOP_REQUEST) && (ntohs(arph->ar_hrd) != ARPHRD_ETHER) && (ntohs(arph->ar_pro) != ETHER_TYPE_IPv4) ) { return DROP; } uint32_t sender_ip_addr; EtherAddress sender_eth_addr; uint32_t dest_ip_addr; //sender_ip_addr = ntohl(*(uint32_t*)arp_pkt->arp_spa); memcpy(&sender_ip_addr, arp_pkt->arp_spa, sizeof(uint32_t)); sender_eth_addr.set(arp_pkt->arp_sha); //dest_ip_addr = *(uint32_t*)arp_pkt->arp_tpa; memcpy(&dest_ip_addr, arp_pkt->arp_tpa, sizeof(uint32_t)); unordered_map<uint32_t, EtherAddress>::iterator iter; iter = _addr_hashmap.find(dest_ip_addr); if (iter != _addr_hashmap.end()) { // Coresponding MAC address found on this system. assert(0); EtherAddress found_eth_addr = iter->second; // Create ARP reply packet. char *arp_rep_pkt = 0; struct ether_hdr *arp_rep_ethh = (struct ether_hdr *)arp_rep_pkt; found_eth_addr.put_to(&arp_rep_ethh->s_addr); // reply eth src addr: addr found from hash_map sender_eth_addr.put_to(&arp_rep_ethh->d_addr); // reply eth dest addt: addr from request pkt arp_rep_ethh->ether_type = ETHER_TYPE_ARP; struct ether_arp *arp_rep_payload = (struct ether_arp*) (arp_rep_pkt + sizeof(ether_hdr)); memcpy(&arp_rep_payload->ea_hdr, arph, sizeof(arphdr)); arp_rep_payload->ea_hdr.ar_op = ARPOP_REPLY; memcpy(arp_rep_payload->arp_sha, found_eth_addr._data, sizeof(uint8_t)*6); // reply src mac addr: addr found from hashmap convert_ip_addr(dest_ip_addr, arp_rep_payload->arp_spa); // reply src ip addr: dest addr from request pkt memcpy(arp_rep_payload->arp_tha, sender_eth_addr._data, sizeof(uint8_t)*6); // reply dest mac addr: sender addr from request pkt convert_ip_addr(sender_ip_addr, arp_rep_payload->arp_tpa); // reply dest ip addr: sender addr from request pkt // Create prepacket struct // Make reply packet go to the port that request packt came in. // Put prepacket to prepacket_queue of io_thread_context } else { // not found, do nothing & drop it. (This is router!) } return DROP; } // vim: ts=8 sts=4 sw=4 et
[ "joongi@an.kaist.ac.kr" ]
joongi@an.kaist.ac.kr
37f7e28250a684b650d7547d0cad33c7fafc1475
aecf4944523b50424831f8af3debef67e3163b97
/net.ssa/xr_3da/xrGame/AI/Monsters/Boar/boar_script.cpp
9b2de26903f369d9424a600940b335080d2d70f6
[]
no_license
xrLil-Batya/gitxray
bc8c905444e40c4da5d77f69d03b41d5b9cec378
58aaa5185f7a682b8cf5f5f376a2e5b6ca16fed4
refs/heads/main
2023-03-31T07:43:57.500002
2020-12-12T21:12:25
2020-12-12T21:12:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
#include "stdafx.h" #include "boar.h" #include "../../../script_space.h" using namespace luabind; #pragma optimize("s",on) void CAI_Boar::script_register(lua_State *L) { module(L) [ class_<CAI_Boar,CGameObject>("CAI_Boar") .def(constructor<>()) ]; }
[ "admin@localhost" ]
admin@localhost
a858336669bfaea8be22320882e9069adcaf09d0
412a08f5d43fcd9dc5e06d2f587efa578ea40e8a
/BOJ/Implementation/boj10992_별_찍기_-_17.cpp
753e4162daa24c3b2744c4cc09a58d2f11cf4804
[]
no_license
onww1/Problem-Solving
19b920f5f4caec50a3aded971e1f1e630e8b6c46
86cc8854ef0457f8f7741cbae401af5038f8ae05
refs/heads/master
2022-06-07T15:47:45.685775
2022-05-25T12:59:59
2022-05-25T12:59:59
130,528,244
6
0
null
null
null
null
UTF-8
C++
false
false
368
cpp
#include <iostream> using namespace std; int main() { int N; cin >> N; for (int i=1; i<=N; i++) { for (int j=N-i; j>0; j--) cout << ' '; cout << '*'; if (i == 1) cout << '\n'; else if (i == N) { for (int j=0; j<2*(N-1); j++) cout << '*'; cout << '\n'; } else { for (int j=0; j<(2*i-3); j++) cout << ' '; cout << "*\n"; } } return 0; }
[ "sewon.dev@gmail.com" ]
sewon.dev@gmail.com
c74dd7f3f55cf7c885e9d3cacb335889ae8a4cce
92d400e084b0af053f03a0a2aaaaf5267a8bef6f
/game.cpp
9999c517e9a51d0938bd45d299db46871a2fd25c
[]
no_license
cckwes/consoleMastermind
9799f5efe2a6e4c0957206fa8bb4004c7fa0d689
4b01ba93a8cbf7ff00923bd8d458f73054d70c22
refs/heads/master
2016-08-11T18:13:13.482055
2016-02-01T14:02:14
2016-02-01T14:02:14
50,503,408
0
0
null
null
null
null
UTF-8
C++
false
false
4,067
cpp
#include <iostream> #include <string> #include <algorithm> #include "board.h" #include "game.h" Game::Game() { b = new Board(); } Game::~Game() { delete b; } void Game::welcome() { std::cout << "Welcome to console Mastermind\n" << "Enter 'R' to start game\n" << "Enter 'S' for game settings\n" << "Enter 'Q' to quit the game\n"; } void Game::start() { std::string inputString; while (1) { welcome(); std::getline(std::cin, inputString); std::transform(inputString.begin(), inputString.end(), inputString.begin(), tolower); if (inputString == "r") { int ret = startGame(); if (ret == 1) break; else continue; } else if (inputString == "s") settings(); else if (inputString == "q") break; else std::cout << "Invalid input\n\n"; } } int checkQuitRestart(std::string &input) { if (input.size() != 1) return 0; else if (input == "Q" || input == "q") return 1; else if (input == "R" || input == "r") return 2; else return 0; } int Game::startGame() { b->printColorList(); b->printHintList(); std::cout << "Command: \n" << "'Q' to quit, 'R' to start a new game\n"; b->restartGame(); while (b->getRemaining() != 0) { std::string inputString; std::cout << "[" << b->getRemaining() << "] Code:\t"; std::getline(std::cin, inputString); int ret = checkQuitRestart(inputString); if (ret) return ret; while (!b->isCodeValid(inputString)) { std::cout << "Invalid code, please try again.\n"; std::cout << "[" << b->getRemaining() << "] Code:\t"; std::getline(std::cin, inputString); ret = checkQuitRestart(inputString); if (ret) return ret; } std::string hint; if (b->getResult(inputString, hint)) { std::cout << "You won!\n"; return 0; } else { //display hint here std::cout << "Hint:\t" << hint << "\n"; } } std::cout << "Run out of moves!"; std::cout << "Correct code:\t" << b->getCode() << "\n"; return 0; } void Game::settings() { std::string settingsString; //prompt for code duplication settings while (1) { std::cout << "Allow duplicate code "; if (b->getDuplicate()) std::cout << "(Y/n):\t"; else std::cout << "(y/N):\t"; std::getline(std::cin, settingsString); //empty, use default if (settingsString.empty()) break; else if (settingsString.length() != 1) { std::cout << "Invalid input\n"; continue; } else { std::transform(settingsString.begin(), settingsString.end(), settingsString.begin(), tolower); if (settingsString == "y") { b->setDuplicate(true); break; } else if (settingsString == "n") { b->setDuplicate(false); break; } else { std::cout << "Invalid input\n"; continue; } } } //prompt for code length settings while (1) { std::cout << "Code length (" << b->getCodeLength() << "):\t"; std::getline(std::cin, settingsString); if (settingsString.empty()) break; int length = std::stoi(settingsString); if (length >= 4 && length <= 8) { b->setCodeLength(length); break; } else { std::cout << "Invalid input, code length must be between 4 and 8\n"; continue; } } }
[ "cckwes@gmail.com" ]
cckwes@gmail.com
576563bdd339b3a262096ad7e72bfff5d9d38c0b
79df47b9f7ee08bed0b1f7402c71a9d89a11bd5b
/src/shutdown.cpp
93caae571d793dbbd54322f8bf37af453b98fcb8
[]
no_license
hzxGoForward/bitcoin_visiualization
21796c56e041bc8c812b059fba777a1ec8066319
201ee7cfcdf73f810e0df0603adfaab845060e3a
refs/heads/main
2023-01-22T08:23:08.232274
2020-12-07T07:55:45
2020-12-07T07:55:45
319,240,840
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
#include "shutdown.h" #include <atomic> static std::atomic<bool> fRequestShutdown(false); void StartShutdown() { fRequestShutdown = true; } void AbortShutdown() { fRequestShutdown = false; } bool ShutdownRequested() { return fRequestShutdown; }
[ "123069135@qq.com" ]
123069135@qq.com
e1e4d99a7ff4424d892084f11204b78f4fbd5ab8
972ac18a7db247b16d2f3b2b218fbffcff1678cb
/ContextTreeWidget.cpp
db92f940f8a5fee391ef31f43e191e1bbad65729
[]
no_license
LubosD/radiodevil
60b73359303b5c804a91c0d3bf2da6c5b72b5d54
d028ef4c270a35f19c4acf3585610f94d5189f46
refs/heads/master
2021-01-09T20:45:55.041542
2008-08-20T16:22:20
2008-08-20T16:22:20
64,771,257
0
0
null
null
null
null
UTF-8
C++
false
false
918
cpp
#include "ContextTreeWidget.h" #include <QContextMenuEvent> ContextTreeWidget::ContextTreeWidget(QWidget* parent) : QTreeWidget(parent) { QAction* action; action = m_menu.addAction(tr("Add")); connect(action, SIGNAL(triggered()), this, SLOT(addItem())); action = m_menu.addAction(tr("Delete")); connect(action, SIGNAL(triggered()), this, SLOT(deleteItem())); } void ContextTreeWidget::contextMenuEvent(QContextMenuEvent* event) { m_menu.exec(mapToGlobal(event->pos())); } void ContextTreeWidget::addItem() { QTreeWidgetItem* item = new QTreeWidgetItem(this); item->setIcon(0, QIcon(":/menu/miscellaneous.png")); addTopLevelItem(item); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDragEnabled); editItem(item, 0); } void ContextTreeWidget::deleteItem() { QTreeWidgetItem* i = currentItem(); if(i != 0) delete takeTopLevelItem(indexOfTopLevelItem(i)); }
[ "lubos@dolezel.info" ]
lubos@dolezel.info
3d39e1f7f0831b438149520abf979e4a4401e16d
3f969cfe40b8b57f0042b00e140dacab04ff70fe
/C++/toets/ISGPCPW Practical Exam 2012-2013 P1/Exercise3/Skeleton.cpp
c4ad16477226f7e56af8c51249cb17f8cbfd0594
[]
no_license
sidneydegeus/Minor
b8570132efbd72c577beb65c93417b4892dcc354
dd24a5519c041e76ceb850e96de9aa6a2a041774
refs/heads/master
2021-01-23T08:00:07.122208
2017-06-06T14:00:17
2017-06-06T14:00:17
80,525,989
1
0
null
null
null
null
UTF-8
C++
false
false
446
cpp
#include "Skeleton.h" ///////////////////////////////////// // Constructors / Destructors // ///////////////////////////////////// CSkeleton::CSkeleton() { } CSkeleton::~CSkeleton() { } ///////////////////////////////////// // Member functions // ///////////////////////////////////// LRESULT CSkeleton::MsgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return CWin::MsgProc(hWnd, uMsg, wParam, lParam); }
[ "sidneydegeus@hotmail.com" ]
sidneydegeus@hotmail.com
81d9eb742a4665a0e52068a98a9688f9f47d9309
24c0f97a499b6ed2823ee2d9b5805c7589f65bcc
/libs/_.cplus/TESTBED/src_b3/btgui/OpenGLTrueTypeFont/opengl_fontstashcallbacks.cpp
e1554bf088ce9f01aa4563679df9ad8b13b01aad
[ "MIT" ]
permissive
hermantobin/modular
0d693f28be6947adacae3e5f80ffd77e3f6a7b89
e8db6b422f8d05b80837e23007799259ec389b66
refs/heads/master
2021-01-16T21:59:45.903350
2014-07-18T16:03:10
2014-07-18T16:03:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,475
cpp
#include "opengl_fontstashcallbacks.h" #include "../OpenGLWindow/GLPrimitiveRenderer.h" #include "../OpenGLWindow/GLPrimInternalData.h" #include "fontstash.h" #include "../OpenGLWindow/OpenGLInclude.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" static unsigned int s_indexData[INDEX_COUNT]; GLuint s_indexArrayObject, s_indexBuffer; GLuint s_vertexArrayObject,s_vertexBuffer; OpenGL2RenderCallbacks::OpenGL2RenderCallbacks(GLPrimitiveRenderer* primRender) :m_primRender2(primRender) { } OpenGL2RenderCallbacks::~OpenGL2RenderCallbacks() { } PrimInternalData* OpenGL2RenderCallbacks::getData() { return m_primRender2->getData(); } InternalOpenGL2RenderCallbacks::~InternalOpenGL2RenderCallbacks() { } void InternalOpenGL2RenderCallbacks::display2() { GLint err = glGetError(); assert(err==GL_NO_ERROR); // glViewport(0,0,10,10); //const float timeScale = 0.008f; PrimInternalData* data = getData(); glUseProgram(data->m_shaderProg); glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer); glBindVertexArray(s_vertexArrayObject); err = glGetError(); assert(err==GL_NO_ERROR); // glBindTexture(GL_TEXTURE_2D,m_texturehandle); err = glGetError(); assert(err==GL_NO_ERROR); vec2 p( 0.f,0.f);//?b?0.5f * sinf(timeValue), 0.5f * cosf(timeValue) ); glUniform2fv(data->m_positionUniform, 1, (const GLfloat *)&p); err = glGetError(); assert(err==GL_NO_ERROR); err = glGetError(); assert(err==GL_NO_ERROR); glEnableVertexAttribArray(data->m_positionAttribute); err = glGetError(); assert(err==GL_NO_ERROR); glEnableVertexAttribArray(data->m_colourAttribute); err = glGetError(); assert(err==GL_NO_ERROR); glEnableVertexAttribArray(data->m_textureAttribute); glVertexAttribPointer(data->m_positionAttribute, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)0); glVertexAttribPointer(data->m_colourAttribute , 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)sizeof(vec4)); glVertexAttribPointer(data->m_textureAttribute , 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *)(sizeof(vec4)+sizeof(vec4))); err = glGetError(); assert(err==GL_NO_ERROR); /* glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer); //glDrawArrays(GL_TRIANGLE_FAN, 0, 4); int indexCount = 6; err = glGetError(); assert(err==GL_NO_ERROR); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0); err = glGetError(); assert(err==GL_NO_ERROR); */ // glutSwapBuffers(); } void InternalOpenGL2RenderCallbacks::updateTexture(sth_texture* texture, sth_glyph* glyph, int textureWidth, int textureHeight) { GLint err; err = glGetError(); assert(err==GL_NO_ERROR); if (glyph) { // Update texture (entire texture, could use glyph to update partial texture using glTexSubImage2D) GLuint* gltexture = (GLuint*) texture->m_userData; glBindTexture(GL_TEXTURE_2D, *gltexture); glPixelStorei(GL_UNPACK_ALIGNMENT,1); err = glGetError(); assert(err==GL_NO_ERROR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, texture->m_texels); GLenum err = glGetError(); assert(err==GL_NO_ERROR); } else { if (textureWidth && textureHeight) { GLuint* texId = new GLuint; texture->m_userData = texId; //create new texture glGenTextures(1, texId); GLenum err = glGetError(); assert(err==GL_NO_ERROR); glBindTexture(GL_TEXTURE_2D, *texId); texture->m_texels = (unsigned char*)malloc(textureWidth*textureHeight); memset(texture->m_texels,0,textureWidth*textureHeight); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, texture->m_texels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); err = glGetError(); assert(err==GL_NO_ERROR); //////////////////////////// //create the other data { glGenVertexArrays(1, &s_vertexArrayObject); glBindVertexArray(s_vertexArrayObject); glGenBuffers(1, &s_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer); glBufferData(GL_ARRAY_BUFFER, VERT_COUNT * sizeof(Vertex), texture->newverts, GL_DYNAMIC_DRAW); GLuint err = glGetError(); assert(err==GL_NO_ERROR); for (int i=0;i<INDEX_COUNT;i++) { s_indexData[i] = i; } glGenBuffers(1, &s_indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER,INDEX_COUNT*sizeof(int), s_indexData,GL_STATIC_DRAW); err = glGetError(); assert(err==GL_NO_ERROR); } } else { //delete texture if (texture->m_userData) { GLuint* id = (GLuint*)texture->m_userData; glDeleteTextures(1, id); //delete id; delete texture->m_userData; texture->m_userData = 0; } } } } void InternalOpenGL2RenderCallbacks::render(sth_texture* texture) { display2(); GLuint* texId = (GLuint*) texture->m_userData; GLint err; err = glGetError(); assert(err==GL_NO_ERROR); glActiveTexture(GL_TEXTURE0); err = glGetError(); assert(err==GL_NO_ERROR); glBindTexture(GL_TEXTURE_2D, *texId); bool useFiltering = false; if (useFiltering) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } err = glGetError(); assert(err==GL_NO_ERROR); glBindBuffer(GL_ARRAY_BUFFER, s_vertexBuffer); glBindVertexArray(s_vertexArrayObject); glBufferData(GL_ARRAY_BUFFER, texture->nverts * sizeof(Vertex), &texture->newverts[0].position.p[0], GL_DYNAMIC_DRAW); err = glGetError(); assert(err==GL_NO_ERROR); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s_indexBuffer); //glDrawArrays(GL_TRIANGLE_FAN, 0, 4); int indexCount = texture->nverts; err = glGetError(); assert(err==GL_NO_ERROR); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0); err = glGetError(); assert(err==GL_NO_ERROR); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // glDisableVertexAttribArray(m_textureAttribute); glUseProgram(0); } void dumpTextureToPng(int textureWidth, int textureHeight, const char* fileName) { glPixelStorei(GL_PACK_ALIGNMENT,1); unsigned char* pixels = (unsigned char*)malloc(textureWidth*textureHeight); glReadPixels(0,0,textureWidth, textureHeight, GL_RED, GL_UNSIGNED_BYTE, pixels); //swap the pixels unsigned char* tmp = (unsigned char*)malloc(textureWidth); for (int j=0;j<textureHeight;j++) { pixels[j*textureWidth+j]=255; } if (0) { for (int j=0;j<textureHeight/2;j++) { for (int i=0;i<textureWidth;i++) { tmp[i] = pixels[j*textureWidth+i]; pixels[j*textureWidth+i]=pixels[(textureHeight-j-1)*textureWidth+i]; pixels[(textureHeight-j-1)*textureWidth+i] = tmp[i]; } } } int comp=1;//1=Y stbi_write_png(fileName, textureWidth,textureHeight, comp, pixels, textureWidth); free(pixels); }
[ "cogle@vt.edu" ]
cogle@vt.edu
6a597f78db37382f64ecc43f7a7964a1332c7faa
215ebd490eb4dafe2b3b9e3cb868d1eadb5dca11
/src/guigfx/cEditGfx.h
da05b7ae2e143cfe532656621fef9122d1a86905
[ "MIT" ]
permissive
aaaasmile/tressettecpp
1fc3a33cf87886d3f3d13566dd3eb5a7a401ce93
0f06a3d5eee6b5aa7e9a099652da548213d07f21
refs/heads/master
2020-04-28T01:56:23.075494
2019-07-31T23:39:26
2019-07-31T23:39:26
174,879,011
1
0
null
null
null
null
UTF-8
C++
false
false
3,122
h
// cEditGfx.h: interface for the cEditGfx class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_cEditGfx_H__2F3F455A_3EA3_49D6_84D9_A7D4188985C3__INCLUDED_) #define AFX_cEditGfx_H__2F3F455A_3EA3_49D6_84D9_A7D4188985C3__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "win_type_global.h" #include <SDL.h> #include <SDL_ttf.h> #include "FastDelegate.h" using namespace fastdelegate; //! class cEditGfx class cEditGfx { // use fastdelegate to implement the observer pattern and avoid using the callback interface on observer typedef FastDelegate1<int> CLICKEVENT; enum { XOFFSET = 5 }; public: //! enum eSate enum eSate { VISIBLE, INVISIBLE, SELECTED }; cEditGfx(); virtual ~cEditGfx(); //! init the control void Init(SDL_Rect* pRect, SDL_Surface* pScreen, TTF_Font* pFont, int iButID, SDL_Renderer* psdlRenderer); //! set window text void SetWindowText(LPCSTR strCaption){m_strButText = strCaption;} //! get window text LPCSTR GetWindowText(){return m_strButText.c_str();} //! mouse move event void MouseMove(SDL_Event &event, SDL_Surface* pScreen, SDL_Surface* pScene_background); //! mouse up void MouseUp(SDL_Event &event); //! draw the button void DrawControl(SDL_Surface* pScreen); //! enable the button void EnableWindow(BOOL bVal){m_bIsEnabled = bVal;} //! set button state void SetState(eSate eVal); //! provides the current state eSate GetState(){return m_eState;} //! redraw the button void RedrawButton(SDL_Surface* pScreen, SDL_Texture* pScene_background, SDL_Texture* pScreenTexture); //! control lost the focus void LostFocus(); //! control becomes focus void GetFocus(); //! key down event void KeyDown(SDL_Event &event); void TextInput(SDL_Event &event); //! set the numeric only flag void SetNumericOnly(BOOL bVal){m_bOnlyNum = bVal;} private: size_t FindCaretPosInBuffer(); size_t FindLastLogicalPos(); public: //! button state eSate m_eState; //! rectangle of the button SDL_Rect m_rctButt; //! text on the button STRING m_strButText; //! enabled flag BOOL m_bIsEnabled; //! click the event CLICKEVENT m_fncbClickEvent; private: //! surface where to draw the button SDL_Surface* m_pSurf_Bar; SDL_Renderer* m_psdlRenderer; //! button font TTF_Font* m_pFontText; //! current text color SDL_Color m_colCurrent; //! current text color SDL_Color m_colBorder; //! button id int m_iButID; //! caret start time Uint32 m_uiStartTime; //! show caret flag BOOL m_bShowCaret; //! caret logical position size_t m_iCarLogPos; //! numeric input mask flag BOOL m_bOnlyNum; UINT m_iMaxLen; }; #endif // !defined(AFX_CBUTTONGFX_H__2F3F455A_3EA3_49D6_84D9_A7D4188985C3__INCLUDED_)
[ "testhaus@gmx.at" ]
testhaus@gmx.at
2cc00dccdf6a94f01ba2651a61801b2a31603e3c
74cb80089d4d74250189d58b962a648bf2782f06
/get_data3/get_data3.ino
1d05052955f7c5cea87dff84dfd0903831a427f9
[]
no_license
moisesStevend/codigos_varios_arduino
8a8b5adabe20036fe6c1553d46d03fa33f88c1a1
46b4b3c96087dd21ef70f1e71c9f1193a745f484
refs/heads/master
2022-04-02T17:08:32.186094
2020-01-27T23:52:38
2020-01-27T23:52:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,986
ino
//libraries #include <SparkFunMPU9250-DMP.h> #include <MPU9250_asukiaaa.h>//don't have an use #include <WiFi.h> #include <PubSubClient.h> #define _ESP32_HAL_I2C_H_ //define to enable the i2c pines #define wifi_casa //enabling the set ups of wifi //#define wifi_lab //#define HR_node1 //wrist #define HR_node2 //upper arm /**********PRe-processor variables*****************/ //variables for wifi #ifdef wifi_casa const char* ssid = "jicamarca"; const char* password = "radioobservatory"; const char* mqtt_server = "test.mosquitto.org"; //const char* mqtt_server = "192.168.0.7"; #endif #ifdef wifi_lab const char* ssid = "LAB.ING.BIOMEDICA"; const char* password = "MicroRobotica19"; const char* mqtt_server = "test.mosquitto.org"; #endif //variables for i2c-mpu9250 #ifdef _ESP32_HAL_I2C_H_ #define SDA_PIN 21 #define SCL_PIN 22 #endif #ifdef HR_node1 #define topic_hr "HR_node1" #endif #ifdef HR_node2 #define topic_hr "HR_node2" #endif /*************Generals variables****************/ int battPin=34; int led_indicator=12; int size_gpio_leds=6; int gpio_leds[6]={16,4,19,18,2,17}; int button=23; uint8_t sensorId; MPU9250_DMP imu; //variables for external interruption bool fpress=true; //variables for mpu9250 struct HRaccel{ float x; float y; float z; }; HRaccel m_accel; struct HRgyros{ float x; float y; float z; }; HRgyros m_gyros; /****definition of functions***********/ void confGPIO(int *pines, int size_i, boolean test=false); float readBattery(int pin); void clear_led(int *pin); void plot_led(int *pin, byte val); void led_plot_Battery(); void readAccel(); void readGyros(); void readMag(); void ypr(long dt); void printIMUData(void); void formatMessage(float ax, float ay, float az, float gx, float gy, float gz); /**************************************/ /******Config especific variables for wifi*********/ WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; char msg_sms[200]=""; /******Config especific variables for mpu9250*********/ MPU9250_asukiaaa mySensor; //but it doens't use float aX, aY, aZ, aSqrt, gX, gY, gZ, mDirection, mX, mY, mZ; int precBtn1 = HIGH; double roll , pitch, yaw; long pre_ts = 0; float phi = 0; float theta = 0; float psi = 0; float phi_n_1, theta_n_1, psi_n_1; float phi_dot, theta_dot, psi_dot, phi_quat; long gyro_x_cal, gyro_y_cal, gyro_z_cal; float Q[4] = {1, 0, 0, 0} ; float Q_dot [4] ; float Q_pre [4] = {1, 0, 0, 0} ; long filtered_roll, filtered_pitch, filtered_yaw; /***********External interruption***********/ void IRAM_ATTR isr(){ //yield(); //delay(100); if(fpress){ led_plot_Battery(gpio_leds); }else{ clear_led(gpio_leds); } fpress = not(fpress); } /***********************************************/ void setup() { //config serial Serial.begin(230400); while(!Serial); //config button-indictor leds pinMode(button, INPUT_PULLUP);//config for the button pinMode(led_indicator,OUTPUT); digitalWrite(led_indicator, 1); attachInterrupt(button, isr, CHANGE); //config gpio-indictor leds confGPIO(gpio_leds, size_gpio_leds);//the config of the leds //led_plot_Battery(gpio_leds); Serial.println("started"); //enabling wifi setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); //enabling mpu9250 module if (imu.begin() != INV_SUCCESS) { while (1) { Serial.println("Unable to communicate with MPU-9250"); Serial.println("Check connections, and try again."); Serial.println(); delay(5000); } } imu.dmpBegin(DMP_FEATURE_6X_LP_QUAT | // Enable 6-axis quat DMP_FEATURE_GYRO_CAL, // Use gyro calibration 10); /* imu.dmpBegin(DMP_FEATURE_SEND_RAW_ACCEL | // Send accelerometer data DMP_FEATURE_GYRO_CAL | // Calibrate the gyro data DMP_FEATURE_SEND_CAL_GYRO | // Send calibrated gyro data DMP_FEATURE_6X_LP_QUAT , // Calculate quat's with accel/gyro 10); */ // setLPF() can be used to set the digital low-pass filter // of the accelerometer and gyroscope. // Can be any of the following: 188, 98, 42, 20, 10, 5 // (values are in Hz). imu.setLPF(5); // Set LPF corner frequency to 5Hz // The sample rate of the accel/gyro can be set using // setSampleRate. Acceptable values range from 4Hz to 1kHz imu.setSampleRate(10); // Set sample rate to 10Hz // Likewise, the compass (magnetometer) sample rate can be // set using the setCompassSampleRate() function. // This value can range between: 1-100Hz //imu.setCompassSampleRate(10); // Set mag rate to 10Hz // You can set your own offset for mag values // mySensor.magXOffset = -50; // mySensor.magYOffset = -55; // mySensor.magZOffset = -10; pre_ts = millis(); } void loop() { if (!client.connected()) { reconnect(); Serial.print("START"); Serial.print("ID sensor detected as?: "); //Serial.println(mySensor.readId(&sensorId) == 0); digitalWrite(led_indicator,0); } client.loop(); long now = millis(); if (now - lastMsg > 50) { lastMsg = now; if ( imu.fifoAvailable() ) { // Use dmpUpdateFifo to update the ax, gx, mx, etc. values if ( imu.dmpUpdateFifo() == INV_SUCCESS) { // computeEulerAngles can be used -- after updating the // quaternion values -- to estimate roll, pitch, and yaw imu.computeEulerAngles(); /***************************************/ /* float gyroX = imu.calcGyro(imu.gx); // gyroX is x-axis rotation in dps float gyroY = imu.calcGyro(imu.gy); // gyroY is y-axis rotation in dps float gyroZ = imu.calcGyro(imu.gz); // gyroZ is z-axis rotation in dps float magX = imu.calcMag(imu.mx); // magX is x-axis magnetic field in uT float magY = imu.calcMag(imu.my); // magY is y-axis magnetic field in uT float magZ = imu.calcMag(imu.mz); // magZ is z-axis magnetic field in uT float nmag = sqrt(magX * magX + magY * magY + magZ * magZ); long dt = millis() -pre_ts; pitch = atan2 (imu.ay , ( sqrt ((imu.ax * imu.ax) + (imu.az * imu.az)))); pitch = (0.98 * (pitch + imu.gy * dt / 1000.0f) + 0.02 * (imu.ay)) * 57.3; pre_ts = millis(); mX = magX / nmag; mY = magY / nmag; mZ = magZ / nmag; yaw = ((imu.yaw + gyroZ * dt / 1000.0f) + 0.02 * (mZ)) * 57.3; // pre_ts = millis(); //roll = (0.98 * (imu.roll + gX * dt / 1000.0f) + 0.02 * (aX)) * 57.3; //pitch = (0.98 * (imu.pitch + gY * dt / 1000.0f) + 0.02 * (aY)) * 57.3; //yaw = ((imu.ya + gZ * dt / 1000.0f) + 0.02 * (mZ)) * 57.3; */ /***************************************/ //Serial.println("360, "+String(imu.roll) + ',' + String(pitch) + ',' + String(imu.yaw)+", 0"); Serial.println("360, "+String(imu.roll) + ',' + String(imu.pitch) + ',' + String(imu.yaw)+", 0"); snprintf(msg_sms,200,"{'angles': [%f, %f,%f ]}", imu.roll, imu.pitch, imu.yaw); client.publish(topic_hr, msg_sms); //printIMUData(); } } /* if(!mySensor.readId(&sensorId)){// && mySensor.accelUpdate() == 0 && mySensor.gyroUpdate() == 0){ readAccel(); readGyros(); readMag(); ypr(millis() -pre_ts); pre_ts = millis(); //formatMessage(m_gyros.x, m_gyros.y, m_gyros.z, m_accel.x,m_accel.y,m_accel.z);//set the values in msg_sms //snprintf(msg_sms,200,"{'giros': [%f, %f,%f ], 'accel':[%f, %f, %f ]}", m_gyros.x, m_gyros.y, m_gyros.z, m_accel.x,m_accel.y,m_accel.z); snprintf(msg_sms,200,"{'angles': [%d, %d,%d ]}", filtered_roll, filtered_pitch, filtered_yaw); client.publish(topic_hr, msg_sms); //client.publish("MPU1", msg_sms); } */ } }//fin de loop /**************************************************/ /***************functions area********************/ /**************************************************/ /******************wifi functions**************/ void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } randomSeed(micros()); Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); // Switch on the LED if an 1 was received as first character if ((char)payload[0] == '1') { // digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level // but actually the LED is on; this is because // it is active low on the ESP-01) } else { //digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH } } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Create a random client ID String clientId = "ESP8266Client-"; clientId += String(random(0xffff), HEX); // Attempt to connect if (client.connect(clientId.c_str())) { Serial.println("connected"); // Once connected, publish an announcement... //client.publish("outTopic", "hello world"); // ... and resubscribe //client.subscribe("inTopic"); } else { digitalWrite(led_indicator,1); Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } /**************function button*************************/ //currently, it doesn't have an use void startBatch() { Serial.println("STARTING BATCH"); } // Sends the closed batch signal void closeBatch() { Serial.println("CLOSING BATCH"); } void confGPIO(int *pines, int size_i, boolean test){ for(int i=0;i<size_i;i++){ pinMode(pines[i],OUTPUT); } if(test){ boolean change=true; int rep=4; //first for for(int j=0;j<rep; j++){ for (int i=0;i<size_i;i++){ digitalWrite(pines[i],change); } delay(500); change=not(change); for (int i=0;i<size_i;i++){ digitalWrite(pines[i],change); } delay(500); change=not(change); } //second for for(int j=0;j<rep; j++){ for (int i=0;i<size_i;i++){ digitalWrite(pines[i],1); delay(500); digitalWrite(pines[i],0); } } } } /*************led-button functions*********/ float readBattery(int pin){ float bat=0; bat = analogRead(pin)*3.3/4096.0;//0-4096 return bat; } void clear_led(int *pin){ //val = 0b001110; for(int i=0;i<size_gpio_leds;i++){ digitalWrite(pin[i],0); } } void plot_led(int *pin, byte val){ //val = 0b001110; clear_led(pin); for(int i=0;i<size_gpio_leds;i++){ digitalWrite(pin[i],(val&(0b000001<<i))>>i); } } void led_plot_Battery(int *pin){ float lectbat = readBattery(battPin); if(lectbat > 3.2){ //111111 plot_led(pin, 0b111111); //plot_led(pin, 0b001111); //plot_led(pin, 0b000111); }else if(3.1<lectbat && lectbat<=3.2) { //001111 plot_led(pin, 0b001111); }else if(2.6<lectbat && lectbat<=3.1){ //000111 plot_led(pin, 0b000111); }else{ //000001 plot_led(pin, 0b000001); } } /*********functions to read the values of mpu***/ void readAccel(){ if (mySensor.accelUpdate() == 0) { //mySensor.accelUpdate(); aX = mySensor.accelX(); aY = mySensor.accelY(); aZ = mySensor.accelZ(); aSqrt = mySensor.accelSqrt(); aX = aX/aSqrt; aY = aY/aSqrt; aZ = aZ/aSqrt; /* Serial.print(" "); Serial.print(aX); Serial.print(" "); Serial.print(aY); Serial.print(" "); Serial.print(aZ); */ m_accel.x=aX; m_accel.y=aY; m_accel.z=aZ; } } void readGyros(){ if (mySensor.gyroUpdate() == 0) { // mySensor.gyroUpdate(); gX = mySensor.gyroX()/57.3; gY = mySensor.gyroY()/57.3; gZ = mySensor.gyroZ()/57.3; /* gX = mySensor.gyroX(); gY = mySensor.gyroY(); gZ = mySensor.gyroZ(); */ //float nmag = sqrt(magX * magX + magY * magY + magZ * magZ); /* Serial.print(" "); Serial.print(gX); Serial.print(" "); Serial.print(gY); Serial.print(" "); Serial.print(gZ); Serial.println(" END"); */ m_gyros.x=gX; m_gyros.y=gY; m_gyros.z=gZ; } } void readMag(){ if (mySensor.magUpdate() == 0) { mX = mySensor.magX(); mY = mySensor.magY(); mZ = mySensor.magZ(); mDirection = mySensor.magHorizDirection(); float nmag = sqrt(mX * mX + mY * mY + mZ * mZ); mX = mX / nmag; mY = mY / nmag; mZ = mZ / nmag; //Serial.println("magX: " + String(mX)); //Serial.println("maxY: " + String(mY)); //Serial.println("magZ: " + String(mZ)); //Serial.println("horizontal direction: " + String(mDirection)); } } void ypr(long dt){ //Euler angle from accel pitch = atan2 (aY , ( sqrt ((aX * aX) + (aZ * aZ)))); roll = atan2(-aX , ( sqrt((aY * aY) + (aZ * aZ)))); // yaw from mag float Yh = (mY * cos(roll)) + (mZ * sin(roll)); float Xh = (mX * cos(pitch)) + (mY * sin(roll) * sin(pitch)) + (mZ * cos(roll) * sin(pitch)); yaw = atan2(Yh, Xh); roll = (0.98 * (roll + gX * dt / 1000.0f) + 0.02 * (aX)) * 57.3; pitch = (0.98 * (pitch + gY * dt / 1000.0f) + 0.02 * (aY)) * 57.3; yaw = ((yaw + gZ * dt / 1000.0f) + 0.02 * (mZ)) * 57.3; /* Serial.print("90, "); Serial.print(roll); Serial.print(","); Serial.print(pitch); Serial.print(","); Serial.print(yaw); Serial.println(", -90"); */ /* phi_quat = (0.98 * (phi_quat + gX * dt / 1000.0f) + 0.02 * (aX)) * 57.3; theta_quat = (0.98 * (theta_quat + gY * dt / 1000.0f) + 0.02 * (aY)) * 57.3; psi_quat = (0.98 * (psi_quat + gZ * dt / 1000.0f) + 0.02 * (mZ)) * 57.3; */ // quaternions Q_dot[0] = -0.5 * ( (gX * Q_pre[1]) + (gY * Q_pre[2]) + (Q_pre[3] * gZ)); Q_dot[1] = 0.5 * ( (gX * Q_pre[0]) + (gZ * Q_pre[2]) - (Q_pre[3] * gY)); Q_dot[2] = 0.5 * ( (gY * Q_pre[0]) - (gZ * Q_pre[1]) + (Q_pre[3] * gX)); Q_dot[3] = 0.5 * ( (gZ * Q_pre[0]) + (gY * Q_pre[1]) - (Q_pre[2] * gX)); Q[0] = Q_pre[0] + (Q_dot[0] * dt / 1000.0); Q_pre[0] = Q[0]; Q[1] = Q_pre[1] + (Q_dot[1] * dt / 1000.0); Q_pre[1] = Q[1]; Q[2] = Q_pre[2] + (Q_dot[2] * dt / 1000.0); Q_pre[2] = Q[2]; Q[3] = Q_pre[3] + (Q_dot[3] * dt / 1000.0); Q_pre[3] = Q[3]; double n = (sqrt((Q[0] * Q[0]) + (Q[1] * Q[1]) + (Q[2] * Q[2]) + (Q[3] * Q[3]))); float Q0 = Q[0] / n; float Q1 = Q[1] / n; float Q2 = Q[2] / n; float Q3 = Q[3] / n; phi_quat = atan2 (2 * ((Q0 * Q1) + (Q2 * Q3)), ((0.5f - Q1 * Q1 - Q2 * Q2))); float theta_quat = asin( 2 * ((Q0 * Q2) - (Q1 * Q3))); float psi_quat = atan2(2 * ((Q0 * Q3) + (Q1 * Q2)), ((0.5f - Q2 * Q2 + Q3 * Q3))); phi_quat = (0.98 * (phi_quat + gX * dt / 1000.0f) + 0.02 * (aX)) * 57.3; theta_quat = (0.98 * (theta_quat + gY * dt / 1000.0f) + 0.02 * (aY)) * 57.3; psi_quat = (0.98 *(psi_quat + gZ * dt / 1000.0f) + 0.02 * (mZ)) * 57.3; //Serial.println("90, "+String(phi_quat) + ',' + String(theta_quat) + ',' + String(psi_quat)+", -90"); filtered_roll = 0.99 * (roll + roll * dt / 1000.0f) + 0.01 * (phi_quat); filtered_pitch = 0.99 * (pitch + pitch * dt / 1000.0f) + 0.01 * (theta_quat); filtered_yaw = 0.5 * (yaw + yaw * dt / 1000.0f) + 0.5 * (psi_quat); Serial.println("90, "+String(filtered_roll) + ',' + String(filtered_pitch) + ',' + String(filtered_yaw)+", -90"); //Serial.println("90, "+String(filtered_pitch)); } void formatMessage(float ax, float ay, float az, float gx, float gy, float gz){ snprintf(msg_sms,100,"{'giros': [%f, %f,%f ], 'accel':[%f, %f, %f ]}", gx,gy,gz,ax,ay,az); } void printIMUData(void) { // After calling dmpUpdateFifo() the ax, gx, mx, etc. values // are all updated. // Quaternion values are, by default, stored in Q30 long // format. calcQuat turns them into a float between -1 and 1 float q0 = imu.calcQuat(imu.qw); float q1 = imu.calcQuat(imu.qx); float q2 = imu.calcQuat(imu.qy); float q3 = imu.calcQuat(imu.qz); /* SerialPort.println("Q: " + String(q0, 4) + ", " + String(q1, 4) + ", " + String(q2, 4) + ", " + String(q3, 4));*/ /* SerialPort.println("R/P/Y: " + String(imu.roll) + ", " + String(imu.pitch) + ", " + String(imu.yaw)); */ Serial.println("360, "+String(imu.roll) + ',' + String(imu.pitch) + ',' + String(imu.yaw)+", 0"); //SerialPort.println("Time: " + String(imu.time) + " ms"); //SerialPort.println(); }
[ "noreply@github.com" ]
noreply@github.com
4a1b3cbe866eb547a26d918b5970a90f69b9dde5
bba21a9bbd9a136ef7f38cad3233bf7a8e80f153
/Main/Users/Reza/VRES/LibOVR/Src/CAPI/D3D1X/CAPI_D3D9_Util.cpp
ad8854c6280a6062164f4c6c38afa756a8384352
[]
no_license
rezanour/randomoldstuff
da95141b3eb7698a55c27b788b2bf3315462545c
f78ccc05e5b86909325f7f2140b18d6134de5904
refs/heads/master
2021-01-19T18:02:40.190735
2014-12-15T05:27:17
2014-12-15T05:28:41
27,686,761
3
0
null
null
null
null
UTF-8
C++
false
false
16,302
cpp
/************************************************************************************ Filename : CAPI_D3D1X_Util.cpp Content : D3D9 utility functions for rendering Created : March 7 , 2014 Authors : Tom Heath Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.1 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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 "CAPI_D3D9_DistortionRenderer.h" #define OVR_D3D_VERSION 9 #include "../../OVR_CAPI_D3D.h" namespace OVR { namespace CAPI { namespace D3D9 { #define PRECOMPILE_FLAG 0 #if !PRECOMPILE_FLAG //To make these, you need to run it with PRECOMPILE_FLAG, which also uses them, so good for debugging. //Then cut and paste these from the output window. //Then turn off the flag. DWORD precompiledVertexShaderSrc[95] = {4294836736,3014654,1111577667,28,127,4294836736,2,28,33024,120,68,131074,655361,88,0,104,2,131073,88,0,1415936325,1668436847,1716475477,1952805734,2880154368,196609,131073,1,0,1415936325,1668436847,1666405973,6646881,845116278,1291858015,1869767529,1952870259,693250080,1397508128,1750278220,1919247457,1836008224,1701603696,775495794,959330610,858665525,3223857,83886161,2685337601,1065353216,0,1056964608,0,33554463,2147483648,2416902144,33554463,2147614720,2416902145,33554463,2147483653,2416902146,33554463,2147549189,2416902147,33554463,2147614725,2416902148,33554433,2147680256,2699296768,67108868,3758292992,2162425856,2430861314,2699296770,67108868,3758292993,2162425856,2430861315,2699296770,67108868,3758292994,2162425856,2430861316,2699296770,67108868,3222208512,2416181248,2689597441,2686779393,33554433,3758161923,2415919105,65535,}; DWORD precompiledVertexShaderTimewarpSrc[293] = {4294836736,4456446,1111577667,28,215,4294836736,4,28,33024,208,108,1310722,5373956,124,0,140,262146,1179652,124,0,157,131074,655361,176,0,192,2,131073,176,0,1382381893,1952543855,1164865385,2868929646,196611,262148,1,0,1382381893,1952543855,1399746409,1953653108,1702446336,1918070612,1331058019,1702061670,2880110708,196609,131073,1,0,1415936325,1668436847,1666405973,6646881,845116278,1291858015,1869767529,1952870259,693250080,1397508128,1750278220,1919247457,1836008224,1701603696,775495794,959330610,858665525,3223857,83886161,2685337601,1065353216,0,1056964608,0,33554463,2147483648,2416902144,33554463,2147549184,2416902145,33554463,2147614720,2416902146,33554463,2147483653,2416902147,33554463,2147549189,2416902148,33554463,2147614725,2416902149,33554433,2147549184,2695495684,50331650,2147549185,2164260864,2695495700,33554433,2147614720,2695495685,50331650,2147614721,2169831424,2695495701,33554433,2147745792,2695495686,50331650,2147745793,2175401984,2695495702,33554433,2148007936,2695495687,50331650,2148007937,2180972544,2695495703,67108868,2148466688,2415919105,2162425857,2162425856,67108868,2148466689,2416181251,2689597441,2684682241,50331657,2147549186,2162425856,2162425857,33554438,2147549186,2147483650,33554433,2147680259,2699296772,50331650,2147876866,2177892355,2697986068,67108868,2147549187,2415919105,2158624770,2689925124,67108868,2147549188,2415919105,2153054210,2684354564,33554433,2147680261,2699296773,50331650,2147876866,2177105925,2697199637,67108868,2147614723,2415919105,2153054210,2689925125,67108868,2147614724,2415919105,2158624770,2684354565,33554433,2147680261,2699296774,50331650,2147811333,2177171461,2697265174,67108868,2147745795,2415919105,2147483653,2689925126,67108868,2147745796,2415919105,2158624773,2684354566,33554433,2147680261,2699296775,50331650,2148073477,2166685701,2686779415,67108868,2148007939,2415919105,2147483653,2689925127,67108868,2148007940,2415919105,2164195333,2684354567,50331657,2147549189,2162425860,2162425857,50331657,2147614725,2162425859,2162425857,50331653,2147680257,2147483650,2162425861,33554433,2147680258,2699296768,67108868,3758292992,2162425858,2162425857,2699296770,67108868,2148466689,2416181252,2689597441,2684682241,50331657,2147549189,2162425860,2162425857,50331657,2147614725,2162425859,2162425857,50331657,2147549185,2162425856,2162425857,33554438,2147549185,2147483649,50331653,2147680257,2147483649,2162425861,67108868,3758292993,2162425858,2162425857,2699296770,67108868,2148466689,2416181253,2689597441,2684682241,50331657,2147549188,2162425860,2162425857,50331657,2147614724,2162425859,2162425857,50331657,2147549184,2162425856,2162425857,33554438,2147549184,2147483648,50331653,2147680256,2147483648,2162425860,67108868,3758292994,2162425858,2162425856,2699296770,67108868,3222208512,2416181248,2689597441,2686779393,33554433,3758161923,2415919106,65535,}; DWORD precompiledPixelShaderSrc[84] = {4294902528,2228222,1111577667,28,79,4294902528,1,28,33024,72,48,3,131073,56,0,1954047316,6648437,786436,65537,1,0,861893488,1291858015,1869767529,1952870259,693250080,1397508128,1750278220,1919247457,1836008224,1701603696,775495794,959330610,858665525,3223857,83886161,2685337600,1065353216,0,0,0,33554463,2147483653,2416115712,33554463,2147549189,2416115713,33554463,2147614725,2416115714,33554463,2147680261,2415984643,33554463,2415919104,2685339648,50331714,2148466688,2430861312,2699298816,67108868,2148073472,2147483648,2690908160,2686779392,50331714,2148466689,2430861313,2699298816,33554433,2147614720,2153054209,50331714,2148466689,2430861314,2699298816,33554433,2147745792,2158624769,50331653,2148468736,2162425856,2415919107,65535,}; #else #include "d3dcompiler.h" /***************************************************************************/ const char* VertexShaderSrc = "float2 EyeToSourceUVScale : register(c0); \n" "float2 EyeToSourceUVOffset : register(c2); \n" "void main(in float2 Position : POSITION, in float TimeWarp : POSITION1, \n" " in float Vignette : POSITION2, in float2 TexCoord0 : TEXCOORD0, \n" " in float2 TexCoord1 : TEXCOORD1, in float2 TexCoord2 : TEXCOORD2, \n" " out float4 oPosition : SV_Position, out float2 oTexCoord0 : TEXCOORD0, \n" " out float2 oTexCoord1 : TEXCOORD1, out float2 oTexCoord2 : TEXCOORD2, \n" " out float oVignette : TEXCOORD3) \n" "{ \n" " oTexCoord0 = EyeToSourceUVScale * TexCoord0 + EyeToSourceUVOffset; \n" " oTexCoord1 = EyeToSourceUVScale * TexCoord1 + EyeToSourceUVOffset; \n" " oTexCoord2 = EyeToSourceUVScale * TexCoord2 + EyeToSourceUVOffset; \n" " oVignette = Vignette; \n" " oPosition = float4(Position.xy, 0.5, 1.0); \n" "}"; /***************************************************************************/ const char* VertexShaderTimewarpSrc = "float2 EyeToSourceUVScale : register(c0); \n" "float2 EyeToSourceUVOffset : register(c2); \n" "float4x4 EyeRotationStart : register(c4); \n" "float4x4 EyeRotationEnd : register(c20); \n" "float2 TimewarpTexCoord(float2 TexCoord, float4x4 rotMat) \n" "{ \n" " float3 transformed = float3( mul ( rotMat, float4(TexCoord.xy, 1, 1) ).xyz); \n" " float2 flattened = (transformed.xy / transformed.z); \n" " return(EyeToSourceUVScale * flattened + EyeToSourceUVOffset); \n" "} \n" "void main(in float2 Position : POSITION, in float TimeWarp : POSITION1, \n" " in float Vignette : POSITION2, in float2 TexCoord0 : TEXCOORD0, \n" " in float2 TexCoord1 : TEXCOORD1, in float2 TexCoord2 : TEXCOORD2, \n" " out float4 oPosition : SV_Position, out float2 oTexCoord0 : TEXCOORD0, \n" " out float2 oTexCoord1 : TEXCOORD1, out float2 oTexCoord2 : TEXCOORD2, \n" " out float oVignette : TEXCOORD3) \n" "{ \n" " float4x4 lerpedEyeRot = lerp(EyeRotationStart, EyeRotationEnd, TimeWarp); \n" " oTexCoord0 = TimewarpTexCoord(TexCoord0,lerpedEyeRot); \n" " oTexCoord1 = TimewarpTexCoord(TexCoord1,lerpedEyeRot); \n" " oTexCoord2 = TimewarpTexCoord(TexCoord2,lerpedEyeRot); \n" " oVignette = Vignette; \n" " oPosition = float4(Position.xy, 0.5, 1.0); \n" "}"; /***************************************************************************/ const char* PixelShaderSrc = " sampler2D Texture : register(s0); \n" "float4 main(in float4 oPosition : SV_Position, in float2 oTexCoord0 : TEXCOORD0, \n" " in float2 oTexCoord1 : TEXCOORD1, in float2 oTexCoord2 : TEXCOORD2, \n" " in float oVignette : TEXCOORD3) \n" " : SV_Target \n" "{ \n" " float R = tex2D(Texture,oTexCoord0).r; \n" " float G = tex2D(Texture,oTexCoord1).g; \n" " float B = tex2D(Texture,oTexCoord2).b; \n" " return (oVignette*float4(R,G,B,1)); \n" "}"; /*************************************************************/ ID3DBlob* ShaderCompile(char * shaderName, const char * shaderSrcString, const char * profile) { ID3DBlob* pShaderCode = NULL; ID3DBlob* pErrorMsg = NULL; if (FAILED(D3DCompile(shaderSrcString, strlen(shaderSrcString),NULL,NULL,NULL, "main",profile,D3DCOMPILE_OPTIMIZATION_LEVEL3,0, &pShaderCode,&pErrorMsg))) MessageBoxA(NULL,(char *) pErrorMsg->GetBufferPointer(),"", MB_OK); if (pErrorMsg) pErrorMsg->Release(); //Now write out blob char tempString[1000]; int numDWORDs = ((int)pShaderCode->GetBufferSize())/4; DWORD * ptr = (DWORD *)pShaderCode->GetBufferPointer(); sprintf_s(tempString,"DWORD %s[%d] = {",shaderName,numDWORDs); OutputDebugStringA(tempString); for (int i = 0;i < numDWORDs; i++) { sprintf_s(tempString,"%lu,",ptr[i]); OutputDebugStringA(tempString); } OutputDebugStringA("};\n"); return(pShaderCode); } #endif /***********************************************************/ void DistortionRenderer::CreateDistortionShaders(void) { #if PRECOMPILE_FLAG ID3DBlob * pShaderCode; pShaderCode = ShaderCompile("precompiledVertexShaderSrc",VertexShaderSrc,"vs_2_0"); device->CreateVertexShader( ( DWORD* )pShaderCode->GetBufferPointer(), &vertexShader ); pShaderCode->Release(); pShaderCode = ShaderCompile("precompiledVertexShaderTimewarpSrc",VertexShaderTimewarpSrc,"vs_2_0"); device->CreateVertexShader( ( DWORD* )pShaderCode->GetBufferPointer(), &vertexShaderTimewarp ); pShaderCode->Release(); pShaderCode = ShaderCompile("precompiledPixelShaderSrc",PixelShaderSrc,"ps_3_0"); device->CreatePixelShader( ( DWORD* )pShaderCode->GetBufferPointer(), &pixelShader ); pShaderCode->Release(); #else device->CreateVertexShader( precompiledVertexShaderSrc, &vertexShader ); device->CreateVertexShader( precompiledVertexShaderTimewarpSrc, &vertexShaderTimewarp ); device->CreatePixelShader( precompiledPixelShaderSrc, &pixelShader ); #endif } /***************************************************/ void DistortionRenderer::CreateVertexDeclaration(void) { static const D3DVERTEXELEMENT9 VertexElements[7] = { { 0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 8, D3DDECLTYPE_FLOAT1, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 1 }, { 0, 12, D3DDECLTYPE_FLOAT1, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 2 }, { 0, 16, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 }, { 0, 32, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 }, D3DDECL_END() }; device->CreateVertexDeclaration( VertexElements, &vertexDecl ); } /******************************************************/ void DistortionRenderer::Create_Distortion_Models(void) { //Make the distortion models for (int eye=0;eye<2;eye++) { FOR_EACH_EYE * e = &eachEye[eye]; ovrDistortionMesh meshData; ovrHmd_CreateDistortionMesh(HMD, RState.EyeRenderDesc[eye].Eye, RState.EyeRenderDesc[eye].Fov, distortionCaps, &meshData); e->numVerts = meshData.VertexCount; e->numIndices = meshData.IndexCount; device->CreateVertexBuffer( (e->numVerts)*sizeof(ovrDistortionVertex),0, 0, D3DPOOL_MANAGED, &e->dxVerts, NULL ); ovrDistortionVertex * dxv; e->dxVerts->Lock( 0, 0, (void**)&dxv, 0 ); for (int v=0;v<e->numVerts;v++) dxv[v] = meshData.pVertexData[v]; device->CreateIndexBuffer( (e->numIndices)*sizeof(unsigned long),0, D3DFMT_INDEX32, D3DPOOL_MANAGED, &e->dxIndices, NULL ); unsigned long* dxi; e->dxIndices->Lock( 0, 0, (void**)&dxi, 0 ); for (int i=0;i<e->numIndices;i++) dxi[i] = meshData.pIndexData[i]; ovrHmd_DestroyDistortionMesh( &meshData ); } } /**********************************************************/ void DistortionRenderer::RenderBothDistortionMeshes(void) { for (int eye=0; eye<2; eye++) { FOR_EACH_EYE * e = &eachEye[eye]; D3DVIEWPORT9 vp; vp.X=0; vp.Y=0; vp.Width=screenSize.w; vp.Height=screenSize.h; vp.MinZ=0; vp.MaxZ = 1; device->SetViewport(&vp); device->SetStreamSource( 0, e->dxVerts,0, sizeof(ovrDistortionVertex) ); device->SetVertexDeclaration( vertexDecl ); device->SetIndices( e->dxIndices ); device->SetPixelShader( pixelShader ); device->SetTexture( 0, e->texture); //Choose which vertex shader, with associated additional inputs if (distortionCaps & ovrDistortionCap_TimeWarp) { device->SetVertexShader( vertexShaderTimewarp ); ovrMatrix4f timeWarpMatrices[2]; ovrHmd_GetEyeTimewarpMatrices(HMD, (ovrEyeType)eye, RState.EyeRenderPoses[eye], timeWarpMatrices); //Need to transpose the matrices timeWarpMatrices[0] = Matrix4f(timeWarpMatrices[0]).Transposed(); timeWarpMatrices[1] = Matrix4f(timeWarpMatrices[1]).Transposed(); // Feed identity like matrices in until we get proper timewarp calculation going on device->SetVertexShaderConstantF(4, (float *) &timeWarpMatrices[0],4); device->SetVertexShaderConstantF(20,(float *) &timeWarpMatrices[1],4); } else { device->SetVertexShader( vertexShader ); } //Set up vertex shader constants device->SetVertexShaderConstantF( 0, ( FLOAT* )&(e->UVScaleOffset[0]), 1 ); device->SetVertexShaderConstantF( 2, ( FLOAT* )&(e->UVScaleOffset[1]), 1 ); device->DrawIndexedPrimitive( D3DPT_TRIANGLELIST,0,0,e->numVerts,0,e->numIndices/3); } } }}}
[ "rezanour@hotmail.com" ]
rezanour@hotmail.com
e0428d2ac14a3b57ec5bf0cfc462b02b4e06d9b0
e15db6c9f378e1d8877d801fb07540aa7ff7cd0a
/koda/utils.hpp
6bc64b0d269da625ea8e303a5f3748757a3292b7
[]
no_license
inesmersak/zero-forcing
a689ae698ec1cb3fcef154ffe3eee9c45dfe49b2
5334e53408cda94b0d7af23b5920552f0dd95012
refs/heads/master
2023-02-18T21:36:18.335826
2020-01-11T16:42:38
2020-01-11T16:42:38
327,687,551
0
1
null
null
null
null
UTF-8
C++
false
false
1,455
hpp
#ifndef UTILS_H #define UTILS_H #include <iostream> #include <time.h> #include <unordered_set> #include <vector> #include "Graph.hpp" #define prn(r, t) { std::cout << "res = " << r.first << ", iter = " << r.second << ", t (ms): " << t << "\n"; } // some constants describing vertex colour / state #define BLACK 0 #define WHITE 1 #define IN_ZFS -1 #define NOT_FORCED -2 vector<int> find_white_neighbours(const Graph& graph, int u, const vector<int>& colouring); bool all_vertices_black(const vector<int>& colouring); vector<int> generate_random_zfs(int N); void assert_vertex_label_correctness(const Graph& graph, int u); template <typename T> ostream& operator<<(ostream& out, const vector<T>& vec) { out << "{"; for (T u : vec) { out << u << ","; } out << "}\n"; return out; } template <typename T1, typename T2> ostream& operator<<(ostream& out, const pair<T1, T2>& pair) { out << "p{" << pair.first << ", " << pair.second << "}"; return out; } template <typename T> T pop(unordered_set<T>& set) { T i = *set.begin(); set.erase(set.begin()); return i; } template<typename Function, typename... Args> auto timeit(Function func, Args... args) -> decltype(func(args...)) { auto t = clock(); auto r = func(args...); t = clock() - t; float t_ms = (float) t / CLOCKS_PER_SEC * 1000; // prn(r, t_ms); cout << "res = " << r << ", t (ms): " << t_ms << "\n"; return r; } #endif
[ "inesmersak@gmail.com" ]
inesmersak@gmail.com
560c9d60ac0ac6268e9a2d6736c26f36526e4b4f
ad4fd3709bfb7211553bb5adec1ee80db30e7c99
/Lab4_4/Lab 4.2.cpp
b9c81a98455bacf989dedf06abe7208cc12e3aae
[]
no_license
F1LlEsK-Labs/Pavel-Chernomorets-Labs
4e0caef9294c5d4a20acdff2a6487a81813198d4
06afee16c84a4e54b4fe16aaf0ff1a046d652d0b
refs/heads/master
2022-09-29T14:42:44.357552
2020-06-02T20:08:56
2020-06-02T20:08:56
260,878,178
0
0
null
null
null
null
UTF-8
C++
false
false
273
cpp
#include <iostream> int zero_small(int& a, int& b) { if (a < b) a = 0; else if (a > b) b = 0; return 0; } int main() { int a, b; std::cout << "Enter 2 nums: " << std::endl; std::cin >> a >> b; zero_small(a, b); std::cout << a << std::endl << b; return 0; }
[ "63155166+F1LlEsK@users.noreply.github.com" ]
63155166+F1LlEsK@users.noreply.github.com
636380adce98da175cfd98e07ea8088782ca4911
8eff13f94c54d26cccbbae500fd7f6b6c2bcbba9
/week 2/hackerrank-string/alt_char_hckr.cpp
1902e0bc069df24d7e5abc0ff7a152e74bf0ea78
[]
no_license
sneharaoganta/IPMP1921
9deaa95f9c32a9844e27eb34778e4187d8f147b5
07e38004e29e819fc4c2d0d467d9f24324f1f4a1
refs/heads/master
2023-06-02T16:00:13.375195
2021-06-18T12:38:17
2021-06-18T12:38:17
354,610,570
1
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
// Complete the alternatingCharacters function below. //9.https://www.hackerrank.com/challenges/alternating-characters/problem //Status:All test cases accepted int alternatingCharacters(string s) { int i; int count=0; label: for(i=0;i<s.size()+1;i++){ if(s[i]=='A'&&s[i+1]=='A'||s[i]=='B'&&s[i+1]=='B'){ s.erase(s.begin()+i); i=i-1; count++; } } cout<<s<<"\n"; return count; }
[ "64457551+sneharaoganta@users.noreply.github.com" ]
64457551+sneharaoganta@users.noreply.github.com
5e1d4eb77ef0febbd7920a2a2bf42cada4c1425e
24a4a659f5bc332d3c08abb437aefc4d8d7127e0
/cpp/oneapi/dal/algo/kmeans/backend/cpu/infer_kernel.hpp
771e129525b32b6d30a9b5c5f6290cac5a3fdbf6
[ "Intel", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT", "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
vepifanov/daal
6eb3f4227dd22c612b52f1c51c47ec6dc75eb61d
7ea5fcfd0a929e8a3a50edaf7bb7794de2bc3aa3
refs/heads/master
2021-07-09T20:03:50.030745
2020-10-12T12:09:04
2020-10-12T12:09:04
211,113,456
0
0
Apache-2.0
2019-09-26T14:47:31
2019-09-26T14:47:30
null
UTF-8
C++
false
false
1,244
hpp
/******************************************************************************* * Copyright 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #pragma once #include "oneapi/dal/algo/kmeans/infer_types.hpp" #include "oneapi/dal/backend/dispatcher.hpp" namespace oneapi::dal::kmeans::backend { template <typename Float, typename Method, typename Task> struct infer_kernel_cpu { infer_result<Task> operator()(const dal::backend::context_cpu& ctx, const descriptor_base<Task>& params, const infer_input<Task>& input) const; }; } // namespace oneapi::dal::kmeans::backend
[ "noreply@github.com" ]
noreply@github.com
99f0c72ba70ee27bda11b3755bfe3f55362d4e80
a23e010ddb9967884de10aa52b5893194529462c
/playground/Schedule4.cpp
62796e12fafb89be41ceebca08a90cc94f9a47ec
[]
no_license
zwang610/code-practice
cdfa1cbb0e61327a0cc5ef425a0786bb23dc1a27
c7ff3a7a94e669f51c598727acb55813424dd28d
refs/heads/master
2020-05-12T22:27:25.004147
2019-04-15T20:04:35
2019-04-15T20:04:35
181,557,663
0
0
null
null
null
null
UTF-8
C++
false
false
2,942
cpp
#include <iostream> #include <fstream> #include <string> #include "DynamicArray.h" using namespace std; #include <cstring> #include <algorithm> struct CourseInfor{ string section; string term; string course; }; struct CheckInfor { string section; string term; }; int main(){ cout << "Programmer: Zheyi Wang\n"; cout << "File: " << __FILE__ << endl; Array <CourseInfor>courseList; int i = 0; char* token = 0; char buff[1000] = " "; const char* const tab = "\t"; ifstream input; //prase the text into an array of class CourseInfor input.open("schedule.txt"); if(!input.good()) cout << "File open error."; string line; getline(input, line); //ignore the first line while (input.good()) { getline(input, line); strcpy(buff, line.c_str()); courseList[i].term = (token = strtok(buff, tab)) ? token : ""; courseList[i].section = (token = strtok(0, tab)) ? token : ""; courseList[i].course = (token = strtok(0, "-")) ? token : ""; i++; } input.close(); for (int j = 0; j < i - 1; j++) //bubble sort, change the array into alphabet order { for (int k = 0; k < i - j - 1; k++) { if (courseList[k].course > courseList[k + 1].course) swap(courseList[k], courseList[k + 1]); } } cout << courseList[0].course << ", "; int n = 1; // n is the counter for while loop int sectionCounter = 1; while (n < i) //use a loop to output the sections, i is the capacity of the courselist array { if (courseList[n].course != courseList[n - 1].course) { cout << sectionCounter << " sections\n"; sectionCounter = 1; cout << courseList[n].course << ", "; } else sectionCounter++; n++; } cout << sectionCounter << " sections\n"; Array <CheckInfor>checkList(i); //create a new a array to store the course list after cleaning up the duplicate entrys int checkListCapacity = 0; //capacity here is not the capacity of the array, just how many data store in the new array int duplicateCount = 0; //count the entry bool duplicate = false; for (int j = 0; j < i; j++) { for (int k = 0; k < checkListCapacity; k++) { if (courseList[j].term == checkList[k].term && courseList[j].section == checkList[k].section) // if term and section are same { duplicateCount++; //duplicate entry count ++ and dont save it in the new array duplicate = true; break; } } if (!duplicate) { checkList[checkListCapacity].section = courseList[j].section; // store section checkList[checkListCapacity].term = courseList[j].term; // store term checkListCapacity++; } duplicate = false; } cout << "\nThere are " << duplicateCount << " duplicate entrys in the text." << endl; system("pause"); return 0; }
[ "joeyw0128@gmail.com" ]
joeyw0128@gmail.com
045438b2e55678b8b1240bc42f100f5b7c09fefb
5faabc8bf7fa0df1e33c73e593e04e5bf5c0e079
/School-projects/Cpp-Allegro5-Planner2D/a_Main.cpp
2ec8885678ee1281e31a42ba5ee1d9202e60a207
[]
no_license
gmarczyk/Old-stuff
6fc4cd2df3528d13db007894e0f68b121c77e6ca
6293c52eb595f450d7ec940381d665809eb3d1cf
refs/heads/master
2020-03-17T01:09:52.240840
2018-05-12T13:36:16
2018-05-12T13:36:16
133,142,364
0
0
null
null
null
null
UTF-8
C++
false
false
7,536
cpp
#include "Display/Display_MainWindow.h" #include "Components\Component_Flasher.h" #include "List\List_Element.h" #include "List/List_ElementAddon.h" #include "List/List_List.h" #include <iostream> #include <allegro5/allegro.h> #include <allegro5/allegro_font.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_native_dialog.h> #include <allegro5/allegro_primitives.h> void main() { // Allegro initialization al_init(); al_init_native_dialog_addon(); al_init_primitives_addon(); al_init_font_addon(); al_init_image_addon(); // Setting up display and window Display_MainWindow MainDisplay; MainDisplay.DrawMenuComponents(); MainDisplay.DrawToolbarThings(); Display_MainWindow::RefreshDisplay(); // Mouse, Keyboard, Event initialization al_install_mouse(); al_install_keyboard(); // Event queue initialization ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_mouse_event_source()); al_register_event_source(event_queue, al_get_display_event_source(Display_MainWindow::GetDisplay())); // Main loop miscelannous float mouseXpos = 0.0; float mouseYpos = 0.0; bool movingDisplay = false; POINT pAfter; bool wasLighted = false; bool isRunning = true; while (isRunning) { // Wait for event to happen // ALLEGRO_EVENT events; al_wait_for_event(event_queue, &events); if (events.type == ALLEGRO_EVENT_KEY_DOWN) { switch (events.keyboard.keycode) { case ALLEGRO_KEY_N: Display_MainWindow::hitboxes->ActualCollisionDrawing = !(Display_MainWindow::hitboxes->ActualCollisionDrawing); MainDisplay.DrawAreaThings(); MainDisplay.DrawMenuComponents(); MainDisplay.DrawToolbarThings(); Display_MainWindow::RefreshDisplay(); break; case ALLEGRO_KEY_ENTER: if (MainDisplay.ptrActualFocus != NULL && MainDisplay.ptrActualFocus->CollisionChecking() == false) { wasLighted = true; MainDisplay.ptrActualFocus->SetLightColor(al_map_rgb(122, 80, 200)); al_set_target_bitmap(Display_MainWindow::GetDrawingAreaBmp()); MainDisplay.ptrActualFocus->LightElement(); al_set_target_backbuffer(Display_MainWindow::GetDisplay()); Display_MainWindow::RefreshDisplay(); } MainDisplay.SettleElement(); MainDisplay.DrawMenuComponents(); Display_MainWindow::RefreshDisplay(); break; case ALLEGRO_KEY_ESCAPE: MainDisplay.ClearActualFocus(); break; default: break; } } else if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { if (events.mouse.button & 1) { // Moving the display if (movingDisplay == false && MainDisplay.CheckIfToolbarClicked(events.mouse.x, events.mouse.y)) { movingDisplay = true; mouseXpos = events.mouse.x; mouseYpos = events.mouse.y; } // Exit if (MainDisplay.CheckIfExitClicked(events.mouse.x, events.mouse.y)) { isRunning = false; break; } // Components MainDisplay.MouseEventMenuComponents(events.mouse.x,events.mouse.y); MainDisplay.DrawMenuComponents(); // Area if (events.mouse.x > Display_MainWindow::drawingArea_Xpos && events.mouse.y > Display_MainWindow::drawingArea_Ypos) { if (MainDisplay.ptrActualFocus == NULL) { float areaX = MainDisplay.hitboxes->ToAreaIndex_DspPos_X(events.mouse.x); float areaY = MainDisplay.hitboxes->ToAreaIndex_DspPos_Y(events.mouse.y); if ((areaX >= 0) && (areaY >= 0)) { if ((MainDisplay.hitboxes->GetElemPointer(areaX, areaY)) != NULL) { MainDisplay.UnsettleElement((MainDisplay.hitboxes->GetElemPointer(areaX, areaY))); } } MainDisplay.DrawMenuComponents(); MainDisplay.DrawAreaThings(); } else if (MainDisplay.ptrActualFocus != NULL && MainDisplay.ptrActualFocus->CollisionChecking() == false) { wasLighted = true; MainDisplay.ptrActualFocus->SetLightColor(al_map_rgb(122, 80, 200)); MainDisplay.DrawAreaThings(); al_set_target_bitmap(Display_MainWindow::GetDrawingAreaBmp()); MainDisplay.ptrActualFocus->LightElement(); al_set_target_backbuffer(Display_MainWindow::GetDisplay()); float xa, xb,m1,m2; MainDisplay.ptrActualFocus->SetPosition(Display_MainWindow::hitboxes->ToAreaPos_DspPos_X(events.mouse.x), Display_MainWindow::hitboxes->ToAreaPos_DspPos_Y(events.mouse.y)); cout << "x : " << Display_MainWindow::hitboxes->ToAreaIndex_DspPos_X(events.mouse.x) << " y: " << Display_MainWindow::hitboxes->ToAreaIndex_DspPos_Y(events.mouse.y) << endl; cout << "x : " << Display_MainWindow::hitboxes->ToAreaIndex_AreaPos_X(MainDisplay.ptrActualFocus->GetPositionX()) << " y: " << Display_MainWindow::hitboxes->ToAreaIndex_AreaPos_Y(MainDisplay.ptrActualFocus->GetPositionY()) << endl; MainDisplay.SettleElement(); } } Display_MainWindow::RefreshDisplay(); } } else if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) { movingDisplay = false; mouseXpos = 0.0; mouseYpos = 0.0; pAfter.x = 0; pAfter.y = 0; } else if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { isRunning = false; break; } else if (events.type == ALLEGRO_EVENT_MOUSE_AXES) { if (movingDisplay == true) { GetCursorPos(&pAfter); double xx, yy; xx = pAfter.x - mouseXpos; yy = pAfter.y - mouseYpos; al_set_window_position(MainDisplay.GetDisplay(), xx, yy); } // Handle on actual item if (MainDisplay.ptrActualFocus != NULL) { if ((events.mouse.x >= Display_MainWindow::drawingArea_Xpos) && (events.mouse.x <= Display_MainWindow::drawingArea_XposEnd) && (events.mouse.y >= Display_MainWindow::drawingArea_Ypos) && (events.mouse.y <= Display_MainWindow::drawingArea_YposEnd)) { MainDisplay.ptrActualFocus->SetPosition(Display_MainWindow::hitboxes->ToAreaPos_DspPos_X(events.mouse.x), Display_MainWindow::hitboxes->ToAreaPos_DspPos_Y(events.mouse.y)); MainDisplay.ptrActualFocus->CollisionChecking(); MainDisplay.DrawAreaThings(); Display_MainWindow::RefreshDisplay(); } } //Light if mouse on item else if (MainDisplay.ptrActualFocus == NULL) { float areaX = MainDisplay.hitboxes->ToAreaIndex_DspPos_X(events.mouse.x); float areaY = MainDisplay.hitboxes->ToAreaIndex_DspPos_Y(events.mouse.y); if ((areaX >= 0) && (areaY >= 0)) { if ((MainDisplay.hitboxes->GetElemPointer(areaX, areaY)) != NULL) { wasLighted = true; (MainDisplay.hitboxes->GetElemPointer(areaX, areaY))->SetLightColor(al_map_rgb(122, 80, 200)); al_set_target_bitmap(Display_MainWindow::GetDrawingAreaBmp()); (MainDisplay.hitboxes->GetElemPointer(areaX, areaY))->LightElement(); al_set_target_backbuffer(Display_MainWindow::GetDisplay()); Display_MainWindow::RefreshDisplay(); } else { if (wasLighted == true) { MainDisplay.DrawAreaThings(); MainDisplay.DrawMenuComponents(); Display_MainWindow::RefreshDisplay(); } } } } } // else if (events.type == ALLEGRO_EVENT_MOUSE_AXES) } al_destroy_event_queue(event_queue); }
[ "noreply@github.com" ]
noreply@github.com
fd8c2f80cfd096c27ea41ed6055c4d438fdce0f3
d3f6b5bebefb126535562fe7444497b014fb73b0
/Fitz/HttpServer.cpp
4f2d40d3302491ce925fabaa4fbdb88f08207357
[]
no_license
Fitzpy/Py-Web
54350da40f037b4ab648e3790441bbacaaca6a99
d372778b98e56be91889c4c46636fed6f6860be7
refs/heads/master
2022-09-04T02:50:47.439965
2020-05-27T12:27:00
2020-05-27T12:27:00
262,303,779
0
0
null
null
null
null
UTF-8
C++
false
false
2,009
cpp
// // Created by py on 2020/5/4. // #include "HttpServer.h" #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> #include "Util.h" #include "Logging.h" HttpServer::HttpServer(EventLoop *loop, int threadNum, int port) : loop_(loop), threadNum_(threadNum), eventLoopThreadPool_(new EventLoopThreadPool(loop_, threadNum)), started_(false), acceptChannel_(new Channel(loop_)), port_(port), listenFd_(socket_bind_listen(port_)) { acceptChannel_->setFd(listenFd_); handle_for_sigpipe(); if (setSocketNonBlocking(listenFd_) < 0) { perror("set socket non block failed"); abort(); } } void HttpServer::start() { eventLoopThreadPool_->start(); acceptChannel_->setEvents(EPOLLIN | EPOLLET); acceptChannel_->setReadHandler([this] { handNewConn(); }); acceptChannel_->setWriteHandler([this] { handThisConn(); }); loop_->addToPoller(acceptChannel_, 0); started_ = true; } void HttpServer::handNewConn() { struct sockaddr_in client_addr; memset(&client_addr, 0, sizeof(struct sockaddr_in)); socklen_t client_addr_len = sizeof(client_addr); int accept_fd = 0; while ((accept_fd = accept(listenFd_, (struct sockaddr *) &client_addr, &client_addr_len)) > 0) { EventLoop *loop = eventLoopThreadPool_->getNextLoop(); LOG << "New connection from " << inet_ntoa(client_addr.sin_addr) << ":" << ntohs(client_addr.sin_port); if (accept_fd >= MaxFds) { close(accept_fd); continue; } if (setSocketNonBlocking(accept_fd) < 0) { LOG << "Set non block failed!"; return; } setSocketNodelay(accept_fd); std::shared_ptr<HttpMessage> req_info(new HttpMessage(loop, accept_fd)); req_info->getChannel()->setHolder(req_info); loop->queueInLoop([req_info] { req_info->newEvent(); }); } acceptChannel_->setEvents(EPOLLIN | EPOLLET); }
[ "noreply@github.com" ]
noreply@github.com
56d1b65f76e4b14bf6bb62680f3e0cb1d2a3a9c6
6241115567f05824729bf0e621e33cf810ed22a8
/maindice.cpp
51c213de6078bcf57950b079a6768a7926dd746e
[]
no_license
Risca/Dice-roller
37a2c2edec89bd0728f639c551be7d911be6cdb7
5575ca46655368ae391e27efd6cb9e6cae38e510
refs/heads/master
2016-09-06T01:56:41.210974
2011-09-29T10:45:33
2011-09-29T10:45:33
2,481,341
0
0
null
null
null
null
UTF-8
C++
false
false
1,174
cpp
#include "maindice.h" #include "ui_maindice.h" #include <QTime> MainDice::MainDice(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainDice) { ui->setupUi(this); qsrand(QTime::currentTime().msec()); dices=10; music=Phonon::createPlayer(Phonon::MusicCategory, Phonon::MediaSource("dice_sound.mp3")); } MainDice::~MainDice() { delete ui; } void MainDice::on_spinBox_valueChanged(int i) { dices=i; } void MainDice::on_pushButton_clicked() { music->play(); int successes=0,ones=0,dice_result; for(int i=0;i<dices;i++){ /* Random */ dice_result=qrand()%6+1; if (dice_result >= 5) { successes++; } else if (dice_result == 1) { ones++; } } ui->lineEditSuccess->setText(QString::number(successes)); ui->lineEditOnes->setText(QString::number(ones)); if (ones >= int(double(dices)/2+0.5)) { if (successes==0) { ui->criticalGlitch->setText("Critical glitch!"); } else { ui->criticalGlitch->setText("Glitch!"); } } else { ui->criticalGlitch->setText(""); } }
[ "patda293@student.liu.se" ]
patda293@student.liu.se
10f9f6575ac0908f5e35151018b570e2cbf39165
3e842b74212d0702689e9d27eb406e6ee3e85a8b
/Inc/Model.h
10ab3f1d06b5ad3a35d6e79962cbbfbf362e93bf
[ "MIT" ]
permissive
kleopatra999/DirectXTK12
57e3ecaa953ec5d80dcfff31241b9f42075138d6
91d5d7836af1125fdd4cc3e4a000ca37f282b885
refs/heads/master
2021-01-18T04:57:38.545669
2016-07-07T00:51:42
2016-07-07T00:51:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,097
h
//-------------------------------------------------------------------------------------- // File: Model.h // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkID=615561 //-------------------------------------------------------------------------------------- #pragma once #if defined(_XBOX_ONE) && defined(_TITLE) #include <d3d12_x.h> #else #include <d3d12.h> #endif #include <DirectXMath.h> #include <DirectXCollision.h> #include <functional> #include <iterator> #include <memory> #include <string> #include <type_traits> #include <vector> #include <assert.h> #include <stdint.h> #include "GraphicsMemory.h" #include "Effects.h" namespace DirectX { class IEffect; class IEffectFactory; class CommonStates; class ModelMesh; //---------------------------------------------------------------------------------- // Each mesh part is a submesh with a single effect class ModelMeshPart { public: ModelMeshPart(); virtual ~ModelMeshPart(); uint32_t materialIndex; uint32_t indexCount; uint32_t startIndex; uint32_t vertexOffset; uint32_t vertexStride; D3D_PRIMITIVE_TOPOLOGY primitiveType; DXGI_FORMAT indexFormat; GraphicsResource indexBuffer; GraphicsResource vertexBuffer; std::shared_ptr<std::vector<D3D12_INPUT_ELEMENT_DESC>> vbDecl; using Collection = std::vector<std::unique_ptr<ModelMeshPart>>; using DrawCallback = std::function<void (_In_ ID3D12GraphicsCommandList* commandList, _In_ const ModelMeshPart& part)>; // Draw mesh part void __cdecl Draw(_In_ ID3D12GraphicsCommandList* commandList) const; // // Utilities for drawing multiple mesh parts // // Draw the mesh static void __cdecl DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, _In_ const ModelMeshPart::Collection& meshParts); // Draw the mesh with an effect static void __cdecl DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, _In_ const ModelMeshPart::Collection& meshParts, _In_ IEffect* effect); // Draw the mesh with a callback for each mesh part static void __cdecl DrawMeshParts(_In_ ID3D12GraphicsCommandList* commandList, _In_ const ModelMeshPart::Collection& meshParts, DrawCallback callback); // Draw the mesh with a range of effects that mesh parts will index into. // Effects can be any IEffect pointer type (including smart pointer). Value or reference types will not compile. // The iterator passed to this method should have random access capabilities for best performance. template<typename TEffectIterator, typename TEffectIteratorCategory = TEffectIterator::iterator_category> static void DrawMeshParts( _In_ ID3D12GraphicsCommandList* commandList, _In_ const ModelMeshPart::Collection& meshParts, TEffectIterator effects) { // This assert is here to prevent accidental use of containers that would cause undesirable performance penalties. static_assert( std::is_base_of<std::random_access_iterator_tag, TEffectIteratorCategory>::value, "Providing an iterator without random access capabilities -- such as from std::list -- is not supported."); for ( auto it = std::begin(meshParts); it != std::end(meshParts); ++it ) { auto part = it->get(); assert(part != nullptr); // Get the effect at the location specified by the part's material TEffectIterator effect_iterator = effects; std::advance(effect_iterator, part->materialIndex); // Apply the effect and draw (*effect_iterator)->Apply(commandList); part->Draw(commandList); } } }; //---------------------------------------------------------------------------------- // A mesh consists of one or more model mesh parts class ModelMesh { public: ModelMesh(); virtual ~ModelMesh(); BoundingSphere boundingSphere; BoundingBox boundingBox; ModelMeshPart::Collection opaqueMeshParts; ModelMeshPart::Collection alphaMeshParts; std::wstring name; using Collection = std::vector<std::shared_ptr<ModelMesh>>; // Draw the mesh void __cdecl DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList) const; void __cdecl DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList) const; // Draw the mesh with an effect void __cdecl DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, _In_ IEffect* effect) const; void __cdecl DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, _In_ IEffect* effect) const; // Draw the mesh with a callback for each mesh part void __cdecl DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, ModelMeshPart::DrawCallback callback) const; void __cdecl DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, ModelMeshPart::DrawCallback callback) const; // Draw the mesh with a range of effects that mesh parts will index into. // TEffectPtr can be any IEffect pointer type (including smart pointer). Value or reference types will not compile. template<typename TEffectIterator, typename TEffectIteratorCategory = TEffectIterator::iterator_category> void DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, TEffectIterator effects) const { ModelMeshPart::DrawMeshParts<TEffectIterator, TEffectIteratorCategory>(commandList, opaqueMeshParts, effects); } template<typename TEffectIterator, typename TEffectIteratorCategory = TEffectIterator::iterator_category> void DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, TEffectIterator effects) const { ModelMeshPart::DrawMeshParts<TEffectIterator, TEffectIteratorCategory>(commandList, alphaMeshParts, effects); } }; //---------------------------------------------------------------------------------- // A model consists of one or more meshes class Model { public: Model(); virtual ~Model(); using ModelMaterialInfo = IEffectFactory::EffectInfo; using ModelMaterialInfoCollection = std::vector<ModelMaterialInfo>; using TextureCollection = std::vector<std::wstring>; // // NOTE // // The Model::Draw functions use variadic templates and perfect-forwarding in order to support future overloads to the ModelMesh::Draw // family of functions. This means that a new ModelMesh::Draw overload can be added, removed or altered, but the Model::Draw* routines // will still remain compatible. The correct ModelMesh::Draw overload will be selected by the compiler depending on the arguments you // provide to Model::Draw*. // // Draw all the opaque meshes in the model template<typename... TForwardArgs> void DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const { // Draw opaque parts for ( auto it = std::begin(meshes); it != std::end(meshes); ++it ) { auto mesh = it->get(); assert( mesh != nullptr ); mesh->DrawOpaque(commandList, std::forward<TForwardArgs>(args)...); } } // Draw all the alpha meshes in the model template<typename... TForwardArgs> void DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const { // Draw opaque parts for ( auto it = std::begin(meshes); it != std::end(meshes); ++it ) { auto mesh = it->get(); assert( mesh != nullptr ); mesh->DrawAlpha(commandList, std::forward<TForwardArgs>(args)...); } } // Draw all the meshes in the model template<typename... TForwardArgs> void Draw(_In_ ID3D12GraphicsCommandList* commandList, TForwardArgs&&... args) const { DrawOpaque(commandList, std::forward<TForwardArgs>(args)...); DrawAlpha(commandList, std::forward<TForwardArgs>(args)...); } // Load texture resources into an existing Effect Texture Factory void __cdecl LoadTextures(IEffectTextureFactory& texFactory, int destinationDescriptorOffset = 0); // Load texture resources into a new Effect Texture Factory std::unique_ptr<EffectTextureFactory> __cdecl LoadTextures( _In_ ID3D12Device* device, _Inout_ ResourceUploadBatch& resourceUploadBatch, _In_opt_z_ const wchar_t* texturesPath = nullptr, D3D12_DESCRIPTOR_HEAP_FLAGS flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); // Create effects using the default effect factory std::vector<std::shared_ptr<IEffect>> __cdecl CreateEffects( const EffectPipelineStateDescription& opaquePipelineState, const EffectPipelineStateDescription& alphaPipelineState, _In_ ID3D12DescriptorHeap* gpuVisibleTextureDescriptorHeap, int baseDescriptorOffset = 0); // Create effects using a custom effect factory std::vector<std::shared_ptr<IEffect>> __cdecl CreateEffects( IEffectFactory& fxFactory, const EffectPipelineStateDescription& opaquePipelineState, const EffectPipelineStateDescription& alphaPipelineState, int baseDescriptorOffset = 0); // Loads a model from a DirectX SDK .SDKMESH file static std::unique_ptr<Model> __cdecl CreateFromSDKMESH( _In_reads_bytes_(dataSize) const uint8_t* meshData, _In_ size_t dataSize ); static std::unique_ptr<Model> __cdecl CreateFromSDKMESH( _In_z_ const wchar_t* szFileName ); // Loads a model from a .VBO file static std::unique_ptr<Model> __cdecl CreateFromVBO( _In_reads_bytes_(dataSize) const uint8_t* meshData, _In_ size_t dataSize ); static std::unique_ptr<Model> __cdecl CreateFromVBO( _In_z_ const wchar_t* szFileName ); // Utility function for getting a GPU descriptor for a mesh part/material index. If there is no texture the // descriptor will be zero. D3D12_GPU_DESCRIPTOR_HANDLE GetGpuTextureHandleForMaterialIndex(uint32_t materialIndex, _In_ ID3D12DescriptorHeap* heap, _In_ size_t descriptorSize, _In_ size_t descriptorOffset) const { D3D12_GPU_DESCRIPTOR_HANDLE handle = {}; if (materialIndex >= materials.size()) return handle; int textureIndex = materials[materialIndex].textureIndex; if (textureIndex == -1) return handle; handle = heap->GetGPUDescriptorHandleForHeapStart(); handle.ptr += descriptorSize * ((size_t) textureIndex + descriptorOffset); return handle; } // Utility function for updating the matrices in a list of effects. This will SetWorld, SetView and SetProjection // on any effect in the list that derives from IEffectMatrices. static void XM_CALLCONV UpdateEffectMatrices( _In_ std::vector<std::shared_ptr<IEffect>>& effectList, DirectX::FXMMATRIX world, DirectX::CXMMATRIX view, DirectX::CXMMATRIX proj); ModelMesh::Collection meshes; ModelMaterialInfoCollection materials; TextureCollection textureNames; std::wstring name; private: std::shared_ptr<IEffect> __cdecl CreateEffectForMeshPart( IEffectFactory& fxFactory, const EffectPipelineStateDescription& opaquePipelineState, const EffectPipelineStateDescription& alphaPipelineState, int descriptorOffset, _In_ const ModelMeshPart* part) const; }; }
[ "chuckw@windows.microsoft.com" ]
chuckw@windows.microsoft.com
1f8e47624e24b0dbdea4075ef0e84cc2908ba425
a9dcca3cc82ef8571a609456156bda7e02ff989a
/source/MUI/MIG_Page.cpp
da9aef23e6db3416dc628a3a4da1f709354d241e
[ "MIT" ]
permissive
Borrk/Enzyme-labeled-instrument
ea420e174dd8a6b442be6ba19a116e3d899388c9
a7c8f4459511c774f7e0c4fee1fe05baf1ae2a5f
refs/heads/master
2020-06-28T17:39:08.672508
2019-09-09T03:14:40
2019-09-09T03:14:40
200,298,941
1
0
null
null
null
null
UTF-8
C++
false
false
9,228
cpp
#include "MIG_OS_Base.hpp" #include "MIG_Page.hpp" INT32U MigPage::mPageCnt = 0; MigPage* MigPage::mpCurPage = (MigPage*)0; MigPage* MigPage::mpFirstPage = (MigPage*)0; MigPage::MigPage( MigObj *pParent ) :MigObj( pParent ) { Init(); } MigPage::MigPage( const tagCS& cs ) :MigObj( cs ) { Init(); }; MigPage::~MigPage() { DeleteAllCtrls(); } void MigPage::Init(void) { if ( 0 == mPageCnt ) { mpCurPage = this; mpFirstPage = this; } mPageCnt++; mpReturnPage = NULL; mpCurCtrl = NULL; mpChildCtrlList = NULL; } void MigPage::Draw(void) { if ( mStyle & ENM_OBJ_HIDEN ) return; DrawFrame( ); if ( mStyle & ENM_OBJ_TITLE ) { DrawTitle( ); } // draw control DrawControls(); } void MigPage::DrawTitle(void) { MCHAR *ap; if ( mTitleID == MIG_STR_ID_INVALID ) ap = mszTitle; else ap = MLoadStr(mTitleID); PutStr( mX + ((mWidth - strlen(ap)*8)/2), mY, ap, 0 ); } void MigPage::DrawFrame(void) { // add later if ( mStyle & ENM_OBJ_FRAME ) { PutRect( mX, mY, mWidth, mHeight ); } else { PutRect( mX, mY, mWidth, mHeight ); // PutBox( mX, mY, mWidth, mHeight ); } } /// Control relative routines void MigPage::AddControl( MigControl* pCtrl ) { assert( pCtrl != NULL ); MigObj *apCtrl = mpChildCtrlList; if ( NULL == mpChildCtrlList ) { //mpCurCtrl = pCtrl; mpChildCtrlList = pCtrl; mpChildCtrlList->SetNext( NULL ); } else { while ( apCtrl->Next() ) { apCtrl = apCtrl->Next(); } apCtrl->SetNext( pCtrl ); } // set control's parent pCtrl->SetParent( this ); if ( mpCurCtrl == NULL ) ControlFocusSw( pCtrl ); } MigControl* MigPage::AddControl( const tagCS& cs ) { MigControl *apCtrl = new MigControl( cs ); AddControl( apCtrl ); return apCtrl; } void MigPage::DeleteAllCtrls(void) { MigControl* apCtrl = mpChildCtrlList; MigControl* apNextCtrl; while ( apCtrl ) { apNextCtrl = (MigControl*)apCtrl->Next(); delete apCtrl; apCtrl = apNextCtrl; } } void MigPage::DrawControls(void) { // add later MigControl* apCtrl = mpChildCtrlList; while ( apCtrl ) { apCtrl->Update(); apCtrl = (MigControl*)apCtrl->Next(); } } void MigPage::FocusControl( INT32U id ) { MigObj* apCtrl = mpChildCtrlList; while ( apCtrl ) { if ( id == apCtrl->GetID() ) break; apCtrl = apCtrl->Next(); } if ( apCtrl ) { mpCurCtrl->FocusOff(); apCtrl->FocusOn(); mpCurCtrl = (MigControl*)apCtrl; } } MigControl* MigPage::FindActiveCtrl(MigControl *pStartCtrl, BOOLEAN bDown ) { INT8U aFound = 0; MigControl *apCtrl= pStartCtrl ? pStartCtrl : mpChildCtrlList; MigControl *apLastCtrl= apCtrl; while ( apCtrl ) { if ( apCtrl->IsActive() ) { aFound = 1; break; } apCtrl = (MigControl*) (bDown ? apCtrl->Next() : apCtrl->Previous()); } if ( aFound == 0 ) { /// ring switch control #if 1 if ( /*pStartCtrl == mpChildCtrlList && */!bDown ) { apCtrl = GetLastControl(); // bDown = TRUE; } else { apCtrl = mpChildCtrlList; } #else apCtrl = mpChildCtrlList; #endif while ( apCtrl && pStartCtrl != apCtrl ) //apCtrl < apLastCtrl ) { if ( apCtrl && apCtrl->IsActive() ) { aFound = 1; break; } apCtrl = (MigControl*)(bDown ? apCtrl->Next() : apCtrl->Previous()); } } return (aFound == 1) ? apCtrl : NULL; } void MigPage::ControlFocusSw( MigControl *pCtrl, BOOLEAN bDown ) { /// when current focused control in edit mode, cannot switch focus if ( mpCurCtrl && mpCurCtrl->IsInEdit() ) { // Hyq, delete whenever control's focus switch return; } #if 1 MigControl *apCtrl, *apLastCtrl = mpCurCtrl; if ( mpCurCtrl == NULL ) { apCtrl= mpChildCtrlList; } else if ( pCtrl == NULL ) { #if 1 /// ring switch control if ( bDown ) { apCtrl= (MigControl*)mpCurCtrl->Next(); apCtrl = (MigControl*)(bDown ? mpCurCtrl->Next() : mpCurCtrl->Previous()); } else { apCtrl = GetLastControl(); } #else apCtrl= (MigControl*)mpCurCtrl->Next(); apCtrl = (MigControl*)(bDown ? mpCurCtrl->Next() : mpCurCtrl->Previous()); #endif } else { apCtrl = pCtrl; } apCtrl = FindActiveCtrl( apCtrl, bDown ); if ( apCtrl ) { // if ( apLastCtrl != apCtrl ) { if ( apLastCtrl ) apLastCtrl->FocusOff(); if ( apCtrl ) ///< found { apCtrl->FocusOn(); } mpCurCtrl = apCtrl; } // else // { // mpCurCtrl->SetStyle( mpCurCtrl->GetStyle() | ENM_CTRL_FOCUSED ); // } } #else if ( mpCurCtrl == NULL ) { mpCurCtrl = mpChildCtrlList; if ( mpCurCtrl ) { mpCurCtrl->FocusOn(); } return; } MigControl *apCtrl= mpCurCtrl; if ( pCtrl == NULL ) { if ( mpCurCtrl->Next() ) { apCtrl = (MigControl*)mpCurCtrl->Next(); } else { apCtrl = mpChildCtrlList; } } else if ( mpCurCtrl != pCtrl ) { apCtrl = pCtrl; } mpCurCtrl->FocusOff(); apCtrl->FocusOn(); mpCurCtrl = apCtrl; #endif // temp code Update(); } MigControl* MigPage::GetControl( INT32U id ) { MigObj* apCtrl = mpChildCtrlList; while ( apCtrl ) { if ( id == apCtrl->GetID() ) break; apCtrl = apCtrl->Next(); } return (MigControl*)apCtrl; } MigControl* MigPage::GetLastControl( ) { MigObj* apCtrl = mpChildCtrlList; while ( apCtrl ) { if ( apCtrl->Next() == NULL ) break; apCtrl = apCtrl->Next(); } return (MigControl*)apCtrl; } MigControl* MigPage::GetControlByIndex( INT16U idx ) { INT16U i = 1; MigObj* apCtrl = mpChildCtrlList; while ( apCtrl && i++ < idx ) { apCtrl = apCtrl->Next(); } return (MigControl*)apCtrl; } /// Focus switch MigPage* MigPage::GetCurFocusPage(void) { return mpCurPage; } void MigPage::SetCurFocusPage(MigPage* pPage ) { if ( pPage == NULL ) return; if ( pPage != mpCurPage ) { mpCurPage->FocusOff(); //EnmDelay(2000); ///< for draw twice bug pPage->FocusOn(); mpCurPage = pPage; } } MigPage* MigPage::Switch2Page( INT32U id, MigPage *pReturnPage ) { MigPage* p = mpFirstPage; p = FindPageByID( p, id ); if ( p ) { if ( pReturnPage != p ) p->SetReturnPage( pReturnPage ); SetCurFocusPage( p ); } return p; } MigPage* MigPage::FindPageByID( MigPage* p, INT32U id ) { static MigPage *aPage = NULL; static INT16U aNestCnt = 0; MigPage *ap = aPage; aNestCnt++; if ( p->GetID() == id ) { aPage = p; if ( --aNestCnt == 0 ) { aPage = NULL; } return p; } if ( p->Child() ) { FindPageByID( (MigPage*)p->Child(), id ); } /// find in brother page if ( aPage == NULL ) { if ( p->Next() ) { FindPageByID( (MigPage*)p->Next(), id ); } } ap = aPage; if ( --aNestCnt == 0 ) { aPage = NULL; } return ap; } /// Message proc void MigPage::OnMessage( const tagMigMSG& stMsg ) { INT32U aMsg = stMsg.msg; if ( mpCurCtrl ) mpCurCtrl->OnMessage( stMsg); switch ( aMsg ) { case ENM_MSG_KEY: OnKey( (INT16U)stMsg.param1 ); break; //case ENM_MSG_TIMER: // break; case ENM_MSG_PAINT: Update(); break; case ENM_MSG_CFG_CHG: SetParam(); break; default: OnUserMsg( stMsg ); break; } } void MigPage::OnUserMsg( const tagMigMSG& stMsg ) { /// do nothing } void MigPage::BroadcastMsg( tagMigMSG msg ) { MigPage *p = this; if ( p->Child() == 0 ) { p->OnMessage( msg ); if ( p->Next() ) { p = (MigPage*)p->Next(); p->BroadcastMsg( msg ); } else { // p->OnMessage( msg ); } } else { p = (MigPage*)p->Child(); p->BroadcastMsg( msg ); if ( p->Next() ) { p = (MigPage*)p->Next(); p->BroadcastMsg( msg ); } } } void MigPage::FocusOn(void) { ControlFocusSw( mpCurCtrl); // temp code Draw(); } void MigPage::FocusOff(void) { // if (mpCurCtrl) // mpCurCtrl->FocusOff(); } INT16U MigPage::NumKey2Index( INT16U key ) { INT16U aKeyMap[10][2] = { { KEY_0_N, 0 }, { KEY_1_A, 1 }, { KEY_2_B, 2 }, { KEY_3_C, 3 }, { KEY_4_D, 4 }, { KEY_5_E, 5 }, { KEY_6_F, 6 }, { KEY_7_G, 7 }, { KEY_8_H, 8 }, { KEY_9_P, 9 } }; INT16U aKey = (INT16U)-1; for ( INT16U i = 0; i < 10; i++ ) { if ( key == aKeyMap[i][0] ) { aKey = aKeyMap[i][1]; break; } } return aKey; } void MigPage::OnNumKey( INT16U key ) { key = GetKeyValue(key); INT16U aKey = NumKey2Index( GetKeyValue(key) ); if ( aKey == (INT16U)-1 ) return; switch( GetKeyValue(key) ) { case KEY_0_N: case KEY_1_A: case KEY_2_B: case KEY_3_C: case KEY_4_D: case KEY_5_E: case KEY_6_F: case KEY_7_G: case KEY_8_H: case KEY_9_P: if ( mpCurCtrl && mpCurCtrl->GetType() == ENM_CTRL_LABEL ) ControlFocusSw( GetControlByIndex( (INT16U)aKey ) ); SetCurFocusPage( (MigPage*)Child( aKey ) ); break; default: break; } } void MigPage::OnKeyUp( void ) { if ( mpCurCtrl ) //&& mpCurCtrl->Previous() ) { ControlFocusSw( (MigControl*)mpCurCtrl->Previous(), FALSE ); } } void MigPage::OnKeyDown( void ) { if ( mpCurCtrl ) //&& mpCurCtrl->Next() ) { ControlFocusSw( (MigControl*)mpCurCtrl->Next() ); } } void MigPage::OnKeyESC( void ) { if ( mpReturnPage ) SetCurFocusPage( mpReturnPage ); else SetCurFocusPage( (MigPage*)mpParent ); mpReturnPage = NULL; } void MigPage::InvalidateRect( tagRect& rc, BOOLEAN bRepaint ) { if ( bRepaint ) ClearScreen( WHITE ); else { PutBox( rc.left, rc.top, (rc.right - rc.left), (rc.bottom - rc.top) ); } }
[ "yiyasail@hotmail.com" ]
yiyasail@hotmail.com
7a66c18c045bb02f585ade26aafde0a067f1feee
8c225cf2eccf75a95f8b6d8805e7d0f692bd3cd7
/FIR/Center.cpp
280490fbd75f10fc1e3ea046271afa9187393d5d
[]
no_license
WoodyloveLuger/FIR
0c2e41f1abdae48a0b4bb7b26332a878dcf06224
f574115ee936b68d764d0ad08b1578df6d18d276
refs/heads/master
2021-01-20T15:19:04.197059
2017-02-27T12:01:49
2017-02-27T12:01:49
82,804,956
2
0
null
null
null
null
GB18030
C++
false
false
971
cpp
// Center.cpp : 实现文件 // #include "stdafx.h" #include "FIR.h" #include "Center.h" #include "afxdialogex.h" #include <string> #include "FIRView.h" using namespace std; // Center 对话框 IMPLEMENT_DYNAMIC(Center, CDialogEx) player gamelayer[100]; Center::Center(CWnd* pParent /*=NULL*/) : CDialogEx(Center::IDD, pParent) , editor1(_T("")) , editor2(_T("")) { } Center::~Center() { } void Center::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, editor1); DDX_Text(pDX, IDC_EDIT2, editor2); } BEGIN_MESSAGE_MAP(Center, CDialogEx) ON_BN_CLICKED(IDOK, &Center::OnBnClickedOk) END_MESSAGE_MAP() // Center 消息处理程序 void Center::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 CString cst1; CString cst2; GetDlgItem(IDC_EDIT1)->GetWindowText(cst1); GetDlgItem(IDC_EDIT2)->GetWindowText(cst2); gamelayer[0].name=cst1; gamelayer[1].name = cst2; CDialogEx::OnOK(); }
[ "756500638@qq.com" ]
756500638@qq.com
937198833d521022683bc7ab92b1b586329deeb0
9f81d77e028503dcbb6d7d4c0c302391b8fdd50c
/google/cloud/compute/region_autoscalers/v1/region_autoscalers_connection_idempotency_policy.cc
96b4bdcdf325567d1c4a6c8a868b22968fbf227d
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
googleapis/google-cloud-cpp
b96a6ee50c972371daa8b8067ddd803de95f54ba
178d6581b499242c52f9150817d91e6c95b773a5
refs/heads/main
2023-08-31T09:30:11.624568
2023-08-31T03:29:11
2023-08-31T03:29:11
111,860,063
450
351
Apache-2.0
2023-09-14T21:52:02
2017-11-24T00:19:31
C++
UTF-8
C++
false
false
3,060
cc
// Copyright 2023 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/compute/region_autoscalers/v1/region_autoscalers.proto #include "google/cloud/compute/region_autoscalers/v1/region_autoscalers_connection_idempotency_policy.h" #include <memory> namespace google { namespace cloud { namespace compute_region_autoscalers_v1 { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN using ::google::cloud::Idempotency; RegionAutoscalersConnectionIdempotencyPolicy:: ~RegionAutoscalersConnectionIdempotencyPolicy() = default; std::unique_ptr<RegionAutoscalersConnectionIdempotencyPolicy> RegionAutoscalersConnectionIdempotencyPolicy::clone() const { return std::make_unique<RegionAutoscalersConnectionIdempotencyPolicy>(*this); } Idempotency RegionAutoscalersConnectionIdempotencyPolicy::DeleteRegionAutoscalers( google::cloud::cpp::compute::region_autoscalers::v1:: DeleteRegionAutoscalersRequest const&) { return Idempotency::kNonIdempotent; } Idempotency RegionAutoscalersConnectionIdempotencyPolicy::GetRegionAutoscalers( google::cloud::cpp::compute::region_autoscalers::v1:: GetRegionAutoscalersRequest const&) { return Idempotency::kIdempotent; } Idempotency RegionAutoscalersConnectionIdempotencyPolicy::InsertRegionAutoscalers( google::cloud::cpp::compute::region_autoscalers::v1:: InsertRegionAutoscalersRequest const&) { return Idempotency::kNonIdempotent; } Idempotency RegionAutoscalersConnectionIdempotencyPolicy::ListRegionAutoscalers( google::cloud::cpp::compute::region_autoscalers::v1:: ListRegionAutoscalersRequest) { // NOLINT return Idempotency::kIdempotent; } Idempotency RegionAutoscalersConnectionIdempotencyPolicy::PatchRegionAutoscalers( google::cloud::cpp::compute::region_autoscalers::v1:: PatchRegionAutoscalersRequest const&) { return Idempotency::kNonIdempotent; } Idempotency RegionAutoscalersConnectionIdempotencyPolicy::UpdateRegionAutoscalers( google::cloud::cpp::compute::region_autoscalers::v1:: UpdateRegionAutoscalersRequest const&) { return Idempotency::kIdempotent; } std::unique_ptr<RegionAutoscalersConnectionIdempotencyPolicy> MakeDefaultRegionAutoscalersConnectionIdempotencyPolicy() { return std::make_unique<RegionAutoscalersConnectionIdempotencyPolicy>(); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace compute_region_autoscalers_v1 } // namespace cloud } // namespace google
[ "noreply@github.com" ]
noreply@github.com
5919d0abe49dec9553f7b494acf98d4611042c4a
680440f5e59eb2157c1ecb41fd891880ac47c459
/LUOGU/P2941/surroundTheIslands.cpp
9fab6c1254700ddba196d7ff9b5e9af98f0108f5
[]
no_license
Skywt2003/codes
a705dc3a4f5f79d47450179fc597bd92639f3d93
0e09198dc84e3f6907a11b117a068f5e0f55ca68
refs/heads/master
2020-03-29T09:29:54.014364
2019-11-15T12:39:47
2019-11-15T12:39:47
149,760,952
6
0
null
null
null
null
UTF-8
C++
false
false
1,641
cpp
#include<bits/stdc++.h> #define int long long using namespace std; inline int read(){ int ret=0,f=1;char ch=getchar(); while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();} while (ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar(); return ret*f; } const int INF=0x3f3f3f3f3f3f3f3f; const int maxn=506,maxe=1005; int n; int tot=0,lnk[maxn],nxt[maxe],to[maxe]; int cost[maxn][maxn]; void add_edge(int x,int y){ tot++; to[tot]=y; nxt[tot]=lnk[x]; lnk[x]=tot; } int dfn[maxn],low[maxn]; bool vis[maxn]; stack<int> stk; int cnt=0; vector<int> inc[maxn]; int blt[maxn]; void tarjan(int x){ dfn[x]=low[x]=++dfn[0]; vis[x]=true; stk.push(x); for (int i=lnk[x];i;i=nxt[i]) if (!dfn[to[i]]){ tarjan(to[i]); low[x]=min(low[x],low[to[i]]); } else if (vis[to[i]]) low[x]=min(low[x],dfn[to[i]]); if (low[x] == dfn[x]){ cnt++; for (;;){ int now=stk.top(); stk.pop(); blt[now]=cnt; inc[cnt].push_back(now); vis[now]=false; if (now==x) break; } } } int dist[maxn][maxn]; int ans=INF; signed main(){ n=read(); for (int i=1;i<=n;i++){ int x=read(),y=read(); add_edge(x,y);add_edge(y,x); } for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) cost[i][j]=read(); for (int i=1;i<=n;i++) if (!dfn[i]) tarjan(i); for (int i=1;i<=cnt;i++) for (int j=i+1;j<=cnt;j++){ int now=INF; for (int k=0;k<inc[i].size();k++) for (int t=0;t<inc[j].size();t++) now=min(now,cost[inc[i][k]][inc[j][t]]); dist[i][j]=dist[j][i]=now; } for (int i=1;i<=cnt;i++){ int now=0; for (int j=1;j<=cnt;j++) if (i!=j) now+=dist[i][j]; ans=min(ans,now); } printf("%lld\n",ans*2); return 0; }
[ "skywt2003@gmail.com" ]
skywt2003@gmail.com
f93ba42b11b36dbdfe4c2257dc19036896e3912f
3ae80dbc18ed3e89bedf846d098b2a98d8e4b776
/src/Exporter/WAVExporter.cpp
5fd2d73a0c26760a6bc94c7321f4dbb7a7bd1c9b
[]
no_license
sswroom/SClass
deee467349ca249a7401f5d3c177cdf763a253ca
9a403ec67c6c4dfd2402f19d44c6573e25d4b347
refs/heads/main
2023-09-01T07:24:58.907606
2023-08-31T11:24:34
2023-08-31T11:24:34
329,970,172
10
7
null
null
null
null
UTF-8
C++
false
false
4,183
cpp
#include "Stdafx.h" #include "MyMemory.h" #include "Data/ByteTool.h" #include "Media/IAudioSource.h" #include "Media/MediaFile.h" #include "Exporter/WAVExporter.h" Exporter::WAVExporter::WAVExporter() { this->codePage = 65001; } Exporter::WAVExporter::~WAVExporter() { } Int32 Exporter::WAVExporter::GetName() { return *(Int32*)"WAVE"; } IO::FileExporter::SupportType Exporter::WAVExporter::IsObjectSupported(IO::ParsedObject *pobj) { if (pobj->GetParserType() != IO::ParserType::MediaFile) { return IO::FileExporter::SupportType::NotSupported; } Media::MediaFile *file = (Media::MediaFile *)pobj; if (file->GetStream(1, 0) != 0) return IO::FileExporter::SupportType::NotSupported; Media::IMediaSource *stm = file->GetStream(0, 0); if (stm == 0) return IO::FileExporter::SupportType::NotSupported; if (stm->GetMediaType() != Media::MEDIA_TYPE_AUDIO) return IO::FileExporter::SupportType::NotSupported; return IO::FileExporter::SupportType::NormalStream; } Bool Exporter::WAVExporter::GetOutputName(UOSInt index, UTF8Char *nameBuff, UTF8Char *fileNameBuff) { if (index == 0) { Text::StrConcatC(nameBuff, UTF8STRC("WAV File")); Text::StrConcatC(fileNameBuff, UTF8STRC("*.wav")); return true; } return false; } void Exporter::WAVExporter::SetCodePage(UInt32 codePage) { this->codePage = codePage; } Bool Exporter::WAVExporter::ExportFile(NotNullPtr<IO::SeekableStream> stm, Text::CString fileName, IO::ParsedObject *pobj, void *param) { if (pobj->GetParserType() != IO::ParserType::MediaFile) { return false; } UInt8 *buff; Media::MediaFile *file = (Media::MediaFile *)pobj; if (file->GetStream(1, 0) != 0) return false; Media::IMediaSource *src = file->GetStream(0, 0); if (src == 0) return false; if (src->GetMediaType() != Media::MEDIA_TYPE_AUDIO) return false; Media::IAudioSource *audio = (Media::IAudioSource*)src; Media::AudioFormat format; audio->GetFormat(&format); UInt64 fileSize = 0; UInt64 headerSize = 0; UInt64 initPos = stm->GetPosition(); buff = MemAlloc(UInt8, 1048576); WriteNInt32(&buff[0], *(Int32*)"RIFF"); WriteUInt32(&buff[4], 0); WriteNInt32(&buff[8], *(Int32*)"WAVE"); WriteNInt32(&buff[12], *(Int32*)"JUNK"); WriteUInt32(&buff[16], 28); MemClear(&buff[20], 28); WriteNInt32(&buff[48], *(Int32*)"fmt "); WriteUInt32(&buff[52], 18 + format.extraSize); WriteUInt16(&buff[56], (UInt16)format.formatId); WriteUInt16(&buff[58], format.nChannels); WriteUInt32(&buff[60], format.frequency); WriteUInt32(&buff[64], format.bitRate >> 3); WriteUInt16(&buff[68], format.align); WriteUInt16(&buff[70], format.bitpersample); WriteUInt16(&buff[72], format.extraSize); if (format.extraSize > 0) { headerSize = 82 + format.extraSize; MemCopyNO(&buff[74], format.extra, format.extraSize); WriteNInt32(&buff[(UOSInt)(headerSize - 8)], *(Int32*)"data"); WriteInt32(&buff[(UOSInt)(headerSize - 4)], 0); } else { headerSize = 82; WriteNInt32(&buff[74], *(Int32*)"data"); WriteUInt32(&buff[78], 0); } stm->Write(buff, (UOSInt)headerSize); fileSize = headerSize; UOSInt blockSize; Sync::Event *evt; NEW_CLASS(evt, Sync::Event(true)); if (audio->Start(evt, (UOSInt)(1048576 - headerSize))) { while ((blockSize = audio->ReadBlock(Data::ByteArray(&buff[(UOSInt)headerSize], (UOSInt)(1048576 - headerSize)))) > 0) { stm->Write(&buff[(UOSInt)headerSize], blockSize); fileSize += blockSize; } audio->Stop(); } DEL_CLASS(evt); if (fileSize >= 0x100000000LL) { WriteNInt32(&buff[12], *(Int32*)"ds64"); WriteUInt64(&buff[20], fileSize - 8); WriteUInt64(&buff[28], fileSize - headerSize); WriteUInt64(&buff[36], 0); WriteUInt32(&buff[44], 0); WriteInt32(&buff[4], -1); WriteInt32(&buff[(UOSInt)(headerSize - 4)], -1); WriteNInt32(&buff[0], *(Int32*)"RF64"); } else { WriteUInt32(&buff[4], (UInt32)(fileSize - 8)); WriteUInt32(&buff[(UOSInt)(headerSize - 4)], (UInt32)(fileSize - headerSize)); } stm->SeekFromBeginning(initPos); stm->Write(buff, (UOSInt)headerSize); MemFree(buff); return true; }
[ "sswroom@yahoo.com" ]
sswroom@yahoo.com
2d042e6891b0956df9918b7a885bce996aed5411
f0b7bcc41298354b471a72a7eeafe349aa8655bf
/codebase/apps/mdv_utils/src/Mdv3Dto2D/Mdv3Dto2D.cc
b8d76fb22a2d86affc8e9379e45928392bbda7e9
[ "BSD-3-Clause" ]
permissive
NCAR/lrose-core
23abeb4e4f1b287725dc659fb566a293aba70069
be0d059240ca442883ae2993b6aa112011755688
refs/heads/master
2023-09-01T04:01:36.030960
2023-08-25T00:41:16
2023-08-25T00:41:16
51,408,988
90
53
NOASSERTION
2023-08-18T21:59:40
2016-02-09T23:36:25
C++
UTF-8
C++
false
false
14,498
cc
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* // ** Copyright UCAR (c) 1990 - 2016 // ** University Corporation for Atmospheric Research (UCAR) // ** National Center for Atmospheric Research (NCAR) // ** Boulder, Colorado, USA // ** BSD licence applies - redistribution and use in source and binary // ** forms, with or without modification, are permitted provided that // ** the following conditions are met: // ** 1) If the software is modified to produce derivative works, // ** such modified software should be clearly marked, so as not // ** to confuse it with the version available from UCAR. // ** 2) Redistributions of source code must retain the above copyright // ** notice, this list of conditions and the following disclaimer. // ** 3) 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. // ** 4) Neither the name of UCAR nor the names of its contributors, // ** if any, may be used to endorse or promote products derived from // ** this software without specific prior written permission. // ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS // ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED // ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ // RCS info // $Author: dixon $ // $Locker: $ // $Date: 2016/03/04 02:22:10 $ // $Id: Mdv3Dto2D.cc,v 1.6 2016/03/04 02:22:10 dixon Exp $ // $Revision: 1.6 $ // $State: Exp $ // /**-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**/ /********************************************************************* * Mdv3Dto2D: Mdv3Dto2D program object. * * RAP, NCAR, Boulder CO * * March 2008 * * Nancy Rehak * *********************************************************************/ #include <assert.h> #include <iostream> #include <signal.h> #include <string> #include <toolsa/os_config.h> #include <dsdata/DsLdataTrigger.hh> #include <dsdata/DsTimeListTrigger.hh> #include <toolsa/pmu.h> #include <toolsa/procmap.h> #include <toolsa/str.h> #include <toolsa/umisc.h> #include "Mdv3Dto2D.hh" #include "Params.hh" #include "FirstComputer.hh" #include "MaxComputer.hh" #include "MeanComputer.hh" #include "MinComputer.hh" #include "SumComputer.hh" using namespace std; // Global variables Mdv3Dto2D *Mdv3Dto2D::_instance = (Mdv3Dto2D *)NULL; /********************************************************************* * Constructor */ Mdv3Dto2D::Mdv3Dto2D(int argc, char **argv) : _dataTrigger(0), _computer(0) { static const string method_name = "Mdv3Dto2D::Mdv3Dto2D()"; // Make sure the singleton wasn't already created. assert(_instance == (Mdv3Dto2D *)NULL); // Initialize the okay flag. okay = true; // Set the singleton instance pointer _instance = this; // Set the program name. path_parts_t progname_parts; uparse_path(argv[0], &progname_parts); _progName = STRdup(progname_parts.base); // display ucopyright message. ucopyright(_progName); // Get the command line arguments. _args = new Args(argc, argv, _progName); // Get TDRP parameters. _params = new Params(); char *params_path = new char[sizeof("unknown")+1]; strcpy(params_path, "unknown"); if (_params->loadFromArgs(argc, argv, _args->override.list, &params_path)) { cerr << "ERROR: " << method_name << endl; cerr << "Problem with TDRP parameters in file: " << params_path << endl; okay = false; return; } } /********************************************************************* * Destructor */ Mdv3Dto2D::~Mdv3Dto2D() { // Unregister process PMU_auto_unregister(); // Free contained objects delete _params; delete _args; delete _dataTrigger; delete _computer; // Free included strings STRfree(_progName); } /********************************************************************* * Inst() - Retrieve the singleton instance of this class. */ Mdv3Dto2D *Mdv3Dto2D::Inst(int argc, char **argv) { if (_instance == (Mdv3Dto2D *)NULL) new Mdv3Dto2D(argc, argv); return(_instance); } Mdv3Dto2D *Mdv3Dto2D::Inst() { assert(_instance != (Mdv3Dto2D *)NULL); return(_instance); } /********************************************************************* * init() - Initialize the local data. * * Returns true if the initialization was successful, false otherwise. */ bool Mdv3Dto2D::init() { static const string method_name = "Mdv3Dto2D::init()"; // Initialize the data trigger if (!_initTrigger()) return false; // Initialize the value computer if (!_initComputer()) return false; // Initialize process registration PMU_auto_init(_progName, _params->instance, PROCMAP_REGISTER_INTERVAL); return true; } /********************************************************************* * run() - run the program. */ void Mdv3Dto2D::run() { static const string method_name = "Mdv3Dto2D::run()"; // Process each of the input files, printing out the coverage values // for each as they are processed. DateTime trigger_time; while (!_dataTrigger->endOfData()) { if (_dataTrigger->nextIssueTime(trigger_time) != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error getting next trigger time" << endl; continue; } if (!_processData(trigger_time)) { cerr << "ERROR: " << method_name << endl; cerr << "Error processing data for time: " << trigger_time << endl; continue; } } /* endwhile - !_dataTrigger->endOfData() */ } /********************************************************************** * Private Member Functions * **********************************************************************/ /********************************************************************* * _initComputer() - Initialize the value computer. * * Returns true on success, false on failure. */ bool Mdv3Dto2D::_initComputer(void) { static const string method_name = "Mdv3Dto2D::_initComputer()"; switch (_params->computation) { case Params::COMPUTE_SUM : _computer = new SumComputer(); break; case Params::COMPUTE_MEAN : _computer = new MeanComputer(); break; case Params::COMPUTE_MAX : _computer = new MaxComputer(); break; case Params::COMPUTE_MIN : _computer = new MinComputer(); break; case Params::COMPUTE_FIRST : _computer = new FirstComputer(); break; } return true; } /********************************************************************* * _initTrigger() - Initialize the data trigger. * * Returns true on success, false on failure. */ bool Mdv3Dto2D::_initTrigger(void) { static const string method_name = "Mdv3Dto2D::_initTrigger()"; switch (_params->trigger_mode) { case Params::TIME_LIST : { time_t start_time = DateTime::parseDateTime(_params->time_list_trigger.start_time); time_t end_time = DateTime::parseDateTime(_params->time_list_trigger.end_time); if (start_time == DateTime::NEVER) { cerr << "ERROR: " << method_name << endl; cerr << "Error parsing start_time string for TIME_LIST trigger: " << _params->time_list_trigger.start_time << endl; return false; } if (end_time == DateTime::NEVER) { cerr << "ERROR: " << method_name << endl; cerr << "Error parsing end_time string for TIME_LIST trigger: " << _params->time_list_trigger.end_time << endl; return false; } if (_params->debug) { cerr << "Initializing TIME_LIST trigger: " << endl; cerr << " url: " << _params->input_field.url << endl; cerr << " start time: " << DateTime::str(start_time) << endl; cerr << " end time: " << DateTime::str(end_time) << endl; } DsTimeListTrigger *trigger = new DsTimeListTrigger(); if (trigger->init(_params->input_field.url, start_time, end_time) != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error initializing TIME_LIST trigger for url: " << _params->input_field.url << endl; cerr << " Start time: " << _params->time_list_trigger.start_time << endl; cerr << " End time: " << _params->time_list_trigger.end_time << endl; cerr << trigger->getErrStr() << endl; return false; } _dataTrigger = trigger; break; } case Params::LATEST_DATA : { DsLdataTrigger *trigger = new DsLdataTrigger(); if (trigger->init(_params->input_field.url, _params->max_valid_age, PMU_auto_register) != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error initializing LATEST_DATA trigger for url: " << _params->input_field.url << endl; cerr << trigger->getErrStr() << endl; return false; } _dataTrigger = trigger; break; } } /* endswitch - _params->trigger_mode */ return true; } /********************************************************************* * _performRead() - Perform the read. This method just consolidates * the parts of the reading of the input fields that * is common between fields. * * Returns true on success, false on failure. */ bool Mdv3Dto2D::_performRead(DsMdvx &input_file, const string &url, const DateTime &trigger_time, const int max_input_secs) const { static const string method_name = "Mdv3Dto2D::_performRead()"; // Finish setting up the read request input_file.setReadTime(Mdvx::READ_FIRST_BEFORE, url, max_input_secs, trigger_time.utime()); input_file.setReadEncodingType(Mdvx::ENCODING_FLOAT32); input_file.setReadCompressionType(Mdvx::COMPRESSION_NONE); input_file.setReadScalingType(Mdvx::SCALING_NONE); // Read the data if (input_file.readVolume() != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error reading input volume from: " << url << endl; cerr << input_file.getErrStr() << endl; return false; } return true; } /********************************************************************* * _processData() - Process data for the given trigger time. * * Returns true on success, false on failure. */ bool Mdv3Dto2D::_processData(const DateTime &trigger_time) { static const string method_name = "Mdv3Dto2D::_processData()"; if (_params->debug) cerr << endl << "*** Processing data for time: " << trigger_time << endl; // Read in the input field DsMdvx input_file; bool read_successful; if (_params->input_field.use_field_name) read_successful = _readInputFile(input_file, _params->input_field.url, _params->input_field.field_name, trigger_time, _params->input_field.max_input_secs); else read_successful = _readInputFile(input_file, _params->input_field.url, _params->input_field.field_num, trigger_time, _params->input_field.max_input_secs); if (!read_successful) return false; MdvxField *field_3d = input_file.getField(0); if (field_3d == 0) return false; // Compute the 2D field MdvxField *field_2d; if ((field_2d = _computer->computeField(*field_3d)) == 0) return false; // Create and write the output file. Note that in this method the // field_2d pointer is added to the output file, which reclaims the // memory before exiting. So don't reclaim this memory here. if (!_writeOutputFile(input_file.getMasterHeader(), field_2d)) return false; return true; } /********************************************************************* * _readInputFile() - Read the indicated input field. * * Returns true on success, false on failure. */ bool Mdv3Dto2D::_readInputFile(DsMdvx &input_file, const string &url, const string &field_name, const DateTime &trigger_time, const int max_input_secs) const { // Set up the read request input_file.addReadField(field_name); if (!_performRead(input_file, url, trigger_time, max_input_secs)) return false; return true; } bool Mdv3Dto2D::_readInputFile(DsMdvx &input_file, const string &url, const int field_num, const DateTime &trigger_time, const int max_input_secs) const { // Set up the read request input_file.addReadField(field_num); if (!_performRead(input_file, url, trigger_time, max_input_secs)) return false; return true; } /********************************************************************* * _writeOutputFile() - Create and write the output file. * * Returns true on success, false on failure. */ bool Mdv3Dto2D::_writeOutputFile(const Mdvx::master_header_t input_master_hdr, MdvxField *field_2d) const { static const string method_name = "Mdv3Dto2D::_writeOutputFile()"; // Create the output master header Mdvx::master_header_t output_master_hdr = input_master_hdr; output_master_hdr.data_dimension = 2; output_master_hdr.vlevel_type = Mdvx::VERT_TYPE_SURFACE; output_master_hdr.n_fields = 0; output_master_hdr.max_nx = 0; output_master_hdr.max_ny = 0; output_master_hdr.max_nz = 0; output_master_hdr.n_chunks = 0; // Create the output file DsMdvx output_file; output_file.setMasterHeader(output_master_hdr); field_2d->convertType(Mdvx::ENCODING_INT8, Mdvx::COMPRESSION_BZIP, Mdvx::SCALING_DYNAMIC); output_file.addField(field_2d); // Write the output file output_file.setWriteLdataInfo(); if (output_file.writeToDir(_params->output_url) != 0) { cerr << "ERROR: " << method_name << endl; cerr << "Error writing output file to URL: " << _params->output_url << endl; cerr << output_file.getErrStr() << endl; return false; } return true; }
[ "dixon@ucar.edu" ]
dixon@ucar.edu
31f6602702ab3f70bee9277a896c95cea3ea7e65
06959c9cdbf807837cac4bdd2eec305b68dcd905
/goddess_daq/goddess/source/siDet.cxx
17345dfebf8864854c811667f01e1781b15e022e
[]
no_license
mhall12/Analysis
e62a39f8a6826f337cce6ba9ff642df3da32e8ca
caa8b95c65ad82feb12afa39fd26bea1729dbd0e
refs/heads/master
2020-05-22T04:15:05.236887
2017-12-04T20:53:12
2017-12-04T20:53:12
61,132,132
0
0
null
null
null
null
UTF-8
C++
false
false
4,905
cxx
#include "siDet.h" #include <cmath> #include <iostream> #include <limits.h> siDet::siDet(): numPtype(0), numNtype(0) { Clear(); } siDet::~siDet() { } void siDet::Clear() { enRawP.clear(); enRawN.clear(); enCalP.clear(); enCalN.clear(); timeP.clear(); timeN.clear(); } void siDet::SetNumContacts(int pType, int nType/*=0*/) { numPtype = pType; numNtype = nType; parEnCalP.resize(pType); parEnCalN.resize(nType); } /** * \param[in] contact The contact number to validate. * \param[in] nType Whether the contact is nType. * \return True is contact has been declared. */ bool siDet::ValidContact(unsigned int contact, bool nType/*=false*/) { size_t size = numPtype; if (nType) size = numNtype; if (contact >= size) { fprintf(stderr, "ERROR: Contact specified, %u, is invalid!\n",contact); return false; } return true; } /**The raw value is stored and the calibrated value is computed based on the loaded * calibration parameters. * * \param[in] channel The channel to be adjusted. * \param[in] rawValue The raw contact value in channels. */ void siDet::SetRawValue(unsigned int channel, unsigned int rawValue) { if (channel < numPtype) SetRawValue(channel,siDet::pType,rawValue); else if (channel < numPtype + numNtype) SetRawValue(channel,siDet::nType,rawValue); else std::cerr << "ERROR: Cannot set raw value for invalid channel: " << channel << "!\n"; } /**The raw value is stored and the calibrated value is computed based on the loaded * calibration parameters. * * \param[in] contact The contact to be adjusted. * \param[in] rawValue The raw contact value in channels. * \param[in] nType Whether the contact selected is n type. */ void siDet::SetRawValue(unsigned int contact, bool nType, unsigned int rawValue) { if (!ValidContact(contact, nType)) return; //Get pointer to the raw an calibrated storage location. float *enCal = 0; unsigned int threshold = 0; std::vector<float> *parEnCal; if (nType) { enRawN[contact] = rawValue; if (contact < threshN.size()) threshold = threshN.at(contact); if (rawValue > threshold) enCal = &(enCalN[contact]); parEnCal = &(parEnCalN[contact]); } else { enRawP[contact] = rawValue; if (contact < threshP.size()) threshold = threshP.at(contact); if (rawValue > threshold) enCal = &(enCalP[contact]); parEnCal = &(parEnCalP[contact]); } //Assign raw value and compute calibrated value. if (enCal) { //*enCal = 0; //for (size_t power = 0; power < parEnCal->size(); power++) //*enCal += parEnCal->at(power) * pow(rawValue,power); *enCal = (rawValue - parEnCal->at(0)) * parEnCal->at(1); } } void siDet::SetTimeStamp(unsigned int contact, bool contactType, unsigned long long timestamp /*=0*/) { if (!ValidContact(contact, contactType)) return; if (contactType == siDet::nType) { timeN[contact] = timestamp; } else { timeP[contact] = timestamp; } } float siDet::GetCalEnergy(int contact, bool nType/*=false*/) { if (!ValidContact(contact, nType)) return 0; ValueMap *enCal; if (nType) enCal = &enCalN; else enCal = & enCalP; auto itr = enCal->find(contact); if (itr != enCal->end()) return itr->second; return 0; } int siDet::GetContactMult() { return enCalP.size() + enCalN.size(); } int siDet::GetContactMult(bool contactType) { if (contactType == siDet::nType) return enCalN.size(); return enCalP.size(); } /* * \return True if successful. */ bool siDet::SetEnergyCalib(std::vector<float> par, int contact, bool nType/*=false*/) { if (!ValidContact(contact,nType)) return false; if (nType) parEnCalN.at(contact) = par; else parEnCalP.at(contact) = par; return true; } bool siDet::SetThresholds(std::vector<int> thresholds, bool contactType/*=siDet::pType*/) { if (thresholds.size() != (unsigned int)GetNumChannels(contactType)) { std::cerr << "ERROR: Vector specified for thresholds was not the equal to the number of contacts (" << thresholds.size() << ">" << GetNumChannels(contactType) << ")!\n"; return false; } if (contactType == siDet::nType) threshN = thresholds; else threshP = thresholds; return true; } int siDet::GetNumChannels(bool nType) { if (nType) return numNtype; return numPtype; } siDet::ValueMap siDet::GetRawEn(bool nType) { if (nType) return enRawN; return enRawP; } siDet::ValueMap siDet::GetCalEn(bool nType) { if (nType) return enCalN; return enCalP; } bool siDet::ContactHit(int contact, bool nType) { ValueMap *map = &enRawP; if (nType) map = &enRawN; if (map->find(contact) == map->end()) return false; return true; } unsigned long long siDet::GetTimeStamp() { unsigned long long timestamp = ULLONG_MAX; for (auto itr = timeP.begin(); itr != timeP.end(); ++itr) { if (timestamp > itr->second) timestamp = itr->second; } for (auto itr = timeN.begin(); itr != timeN.end(); ++itr) { if (timestamp > itr->second) timestamp = itr->second; } return timestamp; } ClassImp(siDet)
[ "mhall12@nd.edu" ]
mhall12@nd.edu
7f0d242fdf759e98a21255e2e61858a2e1da67f6
e4ae3f7a7844c93d01fad66ed7513ae33220aebe
/RunTime_DataSize/bubbleSort.cpp
b82181566d57565b5f988cc1207c1e92500bcd2c
[]
no_license
MFotouhi/Sorting-simulation-
8f1db8e818ccfaa1a8c9815659a04460e1471932
901b753523037495a848bd8aefe1f1b101ea1c29
refs/heads/master
2020-05-05T06:09:23.347430
2019-04-22T21:34:33
2019-04-22T21:34:33
179,777,579
0
0
null
null
null
null
UTF-8
C++
false
false
5,650
cpp
/*================================================================= * * YPRIME.C Sample .MEX file corresponding to YPRIME.M * Solves simple 3 body orbit problem * * The calling syntax is: * * [yp] = yprime(t, y) * * You may also want to look at the corresponding M-code, yprime.m. * * This is a MEX-file for MATLAB. * Copyright 1984-2011 The MathWorks, Inc. * *=================================================================*/ #include <math.h> #include "mex.h" #include <stdio.h> #include <string.h> #include <time.h> #include <unistd.h> #include <stdlib.h> #define yp plhs[0] clock_t start,end; double cpu_time_used; unsigned int input_arr[1020000]; unsigned int input_arr_1000[1000]; unsigned int input_arr_10000[10000]; unsigned int input_arr_20000[20000]; unsigned int input_arr_30000[30000]; unsigned int input_arr_50000[50000]; void swap(unsigned int xp[],unsigned int ypp[]) { unsigned int temp = *xp; *xp = *ypp; *ypp = temp; } void bubbleSort(unsigned int arr[], unsigned int arr_length) { int i, j; bool swapped; for (i = 0; i < arr_length-1; i++) { swapped = false; for (j = 0; j < arr_length-i-1; j++) { if (arr[j] > arr[j+1]) { swap(&arr[j], &arr[j+1]); swapped = true; } } // IF no two elements were swapped by inner loop, then break if (swapped == false) break; } } void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { unsigned int counter = 0; FILE *fp; char str[2000000]; char* filename = "C:\\Sorting Project\\Code\\RunTime_DataSize\\Dataset2_Rand.txt"; fp = fopen(filename, "r"); unsigned int array_length =0; while (fscanf(fp, "%s", str)!=EOF){ array_length = array_length+1; } printf("array_length = %d\r\n",array_length); fp = fopen(filename, "r"); for(unsigned int i=0;i<array_length;i++){ fscanf(fp, "%s", str); input_arr[counter] = atoi(str); counter=counter+1; } fclose(fp); unsigned int co = 0; unsigned int data_size ; double *DataSize_RunTime; yp = mxCreateDoubleMatrix( 2, 5, mxREAL); DataSize_RunTime = mxGetPr(yp); int Mont_Carlo_Num = 5; for(int Mcount =0;Mcount<Mont_Carlo_Num;Mcount++){ /////////////////////////////////////////// Data Size=1000 data_size = 1000; for(co=0;co<data_size;co++){ input_arr_1000[co] = input_arr[co]; } start = clock(); bubbleSort(input_arr_1000,data_size); end = clock(); // Calculation RunTime cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; DataSize_RunTime[0] =DataSize_RunTime[0]+ data_size; DataSize_RunTime[1] =DataSize_RunTime[1]+ cpu_time_used*1000; printf( "\n Data Size = %d\n", data_size ); printf( "\n RunTime = %f sec\n", cpu_time_used ); printf( "/////////////////////////\n"); /////////////////////////////////////////// Data Size=10000 data_size = 10000; for(co=0;co<data_size;co++){ input_arr_10000[co] = input_arr[co]; } start = clock(); bubbleSort(input_arr_10000,data_size); end = clock(); // Calculation RunTime cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; DataSize_RunTime[2] =DataSize_RunTime[2]+ data_size; DataSize_RunTime[3] =DataSize_RunTime[3]+ cpu_time_used*1000; printf( "\n Data Size = %d\n", data_size ); printf( "\n RunTime = %f sec\n", cpu_time_used ); printf( "/////////////////////////\n"); /////////////////////////////////////////// Data Size=20000 data_size = 20000; for(co=0;co<data_size;co++){ input_arr_20000[co] = input_arr[co]; } start = clock(); bubbleSort(input_arr_20000,data_size); end = clock(); // Calculation RunTime cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; DataSize_RunTime[4] =DataSize_RunTime[4]+ data_size; DataSize_RunTime[5] =DataSize_RunTime[5]+ cpu_time_used*1000; printf( "\n Data Size = %d\n", data_size ); printf( "\n RunTime = %f sec\n", cpu_time_used ); printf( "/////////////////////////\n"); /////////////////////////////////////////// Data Size=30000 data_size = 30000; for(co=0;co<data_size;co++){ input_arr_30000[co] = input_arr[co]; } start = clock(); bubbleSort(input_arr_30000,data_size); end = clock(); // Calculation RunTime cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; DataSize_RunTime[6] =DataSize_RunTime[6]+ data_size; DataSize_RunTime[7] =DataSize_RunTime[7]+ cpu_time_used*1000; printf( "\n Data Size = %d\n", data_size ); printf( "\n RunTime = %f sec\n", cpu_time_used ); printf( "/////////////////////////\n"); /////////////////////////////////////////// Data Size=50000 data_size = 50000; for(co=0;co<data_size;co++){ input_arr_50000[co] = input_arr[co]; } start = clock(); bubbleSort(input_arr_50000,data_size); end = clock(); // Calculation RunTime cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; DataSize_RunTime[8] =DataSize_RunTime[8]+ data_size; DataSize_RunTime[9] =DataSize_RunTime[9]+ cpu_time_used*1000; printf( "\n Data Size = %d\n", data_size ); printf( "\n RunTime = %f sec\n", cpu_time_used ); printf( "/////////////////////////\n"); } for(int j =0;j<10;j++){ DataSize_RunTime[j] = DataSize_RunTime[j]/Mont_Carlo_Num; } return; }
[ "mfotouhi@uw.edu" ]
mfotouhi@uw.edu
ee9c1eb1c7e673251bf59115f07041fdd95b7d9a
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/protocols/simple_moves/DumpSingleResidueRotamers.fwd.hh
0d35ede63a7c92aade23ae74aa8ccae7e7cfc76c
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
1,365
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file protocols/simple_moves/DumpSingleResidueRotamers.fwd.hh /// @brief Given a residue index, dump all of the rotamers to individual PDB files within 0-1 sd of the mean /// @author Rebecca Alford (rfalford12@gmail.com) #ifndef INCLUDED_protocols_simple_moves_DumpSingleResidueRotamers_fwd_hh #define INCLUDED_protocols_simple_moves_DumpSingleResidueRotamers_fwd_hh // Utility headers #include <utility/pointer/owning_ptr.hh> // Forward namespace protocols { namespace simple_moves { class DumpSingleResidueRotamers; typedef utility::pointer::shared_ptr< DumpSingleResidueRotamers > DumpSingleResidueRotamersOP; typedef utility::pointer::shared_ptr< DumpSingleResidueRotamers const > DumpSingleResidueRotamersCOP; } //protocols } //simple_moves #endif //INCLUDED_protocols_simple_moves_DumpSingleResidueRotamers_fwd_hh
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
056de7959b228cdfff921314475d5fe989d77a69
2f557f60fc609c03fbb42badf2c4f41ef2e60227
/EventFilter/L1TRawToDigi/plugins/implementations_stage2/CaloLayer1Unpacker.h
cb8ced39033df43adec323b2f9206cd74e7e20f3
[ "Apache-2.0" ]
permissive
CMS-TMTT/cmssw
91d70fc40a7110832a2ceb2dc08c15b5a299bd3b
80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7
refs/heads/TMTT_1060
2020-03-24T07:49:39.440996
2020-03-04T17:21:36
2020-03-04T17:21:36
142,576,342
3
5
Apache-2.0
2019-12-05T21:16:34
2018-07-27T12:48:13
C++
UTF-8
C++
false
false
879
h
#ifndef L1T_PACKER_STAGE2_LAYER1UNPACKER_H #define L1T_PACKER_STAGE2_LAYER1UNPACKER_H #include "EventFilter/L1TRawToDigi/interface/Unpacker.h" #include "CaloLayer1Collections.h" #include "UCTCTP7RawData.h" namespace l1t { namespace stage2 { class CaloLayer1Unpacker : public Unpacker { public: bool unpack(const Block& block, UnpackerCollections *coll) override; private: void makeECalTPGs(uint32_t lPhi, UCTCTP7RawData& ctp7Data, EcalTrigPrimDigiCollection* ecalTPGs); void makeHCalTPGs(uint32_t lPhi, UCTCTP7RawData& ctp7Data, HcalTrigPrimDigiCollection* hcalTPGs); void makeHFTPGs(uint32_t lPhi, UCTCTP7RawData& ctp7Data, HcalTrigPrimDigiCollection* hcalTPGs); void makeRegions(uint32_t lPhi, UCTCTP7RawData& ctp7Data, L1CaloRegionCollection* regions); }; } } #endif
[ "vladimir.rekovic@cern.ch" ]
vladimir.rekovic@cern.ch
b9e39718d9b22bdbdd002bf332350a7b1f6e0207
15c72ed40f59f43ba1ed7f499992033464039945
/Data-structures-codes/array/arr.cpp
d145c8ed131e865e02055f7983bada35e128ee5f
[]
no_license
ramanbaghla89/data_structures
fc40102d473595c51992b7c47c025d045c9b9956
b1a84a99f6c4e3144e3d1c8c3bdcd18e9e75336f
refs/heads/master
2020-04-02T23:28:26.670844
2018-10-26T17:23:24
2018-10-26T17:23:24
154,868,847
1
0
null
null
null
null
UTF-8
C++
false
false
1,823
cpp
using namespace std; #include<iostream> class array1 { int *arr,n; public: array1 (int size_) { n=size_; arr=new int[n]; } void input() { for (int i=0;i<n;i++) { cin>>arr[i]; } } void display() { for (int i=0;i<n;i++) { cout<<arr[i]<<endl; } } void lsearch() { int flag=0,value; cout<<"enter item to be searched"<<endl; cin>>value; for (int i=0;i<n;i++) { if (arr[i]==value) { flag=1; cout<<"FOUND"<<endl; break; } } if (flag==0) { cout<<"NOT FOUND"<<endl; } } void bsearch() { int value,mid,beg,end_,flag=0; cout<<"enter item to be searched"; cin>>value; beg=0; end_=n-1; mid= (beg+end_)/2; while (beg<=end_) { if (arr[mid]==value) { cout<<"item found"<<endl; flag=1; break; } else { if (arr[mid]>value) end_=mid-1; else beg=mid+1; } mid= (beg+end_)/2; } if (flag==0) cout<<"item not found"<<endl; } void bsort(); }; void array1::bsort() { int temp,flag; for (int p=1;p<n;p++) { flag=0; for (int c=0;c<n-p;c++) { if (arr[c]>arr[c+1]) { flag=1; temp=arr[c]; arr[c]=arr[c+1]; arr[c+1]=temp; } } if (flag==0) break; } } int main() { int size_,ch; cout<<"enter size of array"<<endl; cin>>size_; array1 ob(size_); cout<<"enter 1 for entering values,2 for display,3 for linear search,4 for binary search,5 for sorting and 0 to exit"<<endl; cin>>ch; while (ch!=0) { switch(ch) { case 1: cout<<"enter values"; ob.input(); break; case 2: ob.display(); break; case 3: ob.lsearch(); break; case 4: ob.bsearch(); break; case 5: ob.bsort(); cout<<"after sorting"<<endl; ob.display() ; } cout<<"enter choice"<<endl; cin>>ch; } }
[ "ramanbaghla89@gmail.com" ]
ramanbaghla89@gmail.com
73deddc17aa4f5ba734529a37681eb4bfaddc141
e4a51db989a3ac315a09b5aeb69950fbdd40289a
/sqlselect/libtoken/token_stream.cpp
113973483295cc26a1c09917f989f94e6d044991
[ "MIT" ]
permissive
DmytroGerasymchuk/sqlselect
3eb21ad6a4af0dbfd7b5fed7f94bed38d9dfac20
40a882a371ab8171d6e2ffd6f4bf5c77e82b05d6
refs/heads/master
2021-01-19T13:26:24.547881
2017-05-01T09:00:40
2017-05-01T09:00:40
88,090,149
0
0
null
null
null
null
UTF-8
C++
false
false
6,231
cpp
#include "token_stream.h" namespace libtoken { token_stream::token_stream(const token_stream_settings& ts_settings, istream& is) : line_buf{ is }, state{ true } { settings = ts_settings; } token_stream& token_stream::operator << (token& t) { token_buf.push_back(t); return *this; } token_stream& token_stream::operator >> (token& t) { if (!state) throw libtoken_exception("this token_stream is not readable any more", line_buf); if (token_buf.size() > 0) // if there are some previously buffered tokens { // then return the last one and make buffer one position shorter t = token_buf[token_buf.size() - 1]; token_buf.pop_back(); } else { t.clear(settings.multipart_token_separator); token_part tmp; QualState qual_state = QualState::None; while (char c = line_buf.getch()) { // EOL signal if (c == line_buf.eol_signal()) { if (something_read(t, tmp)) // if already something has been read { if (settings.newline_as_token) line_buf.ungetch(); // put EOL back to be read later break; } if (settings.newline_as_token) { tmp.type = token_part::Type::EOL; tmp.body.append(1, c); break; } else continue; } // if this is some kind of space AND NOT inside of qualification process if (iswspace(c) && (qual_state == QualState::None)) { if (something_read(t, tmp)) // if already something has been read break; continue; } if (qual_state == QualState::None) // if not inside of a qualified content { // is this a comment? if (comment_from_here(c)) { line_buf.skip_to_eol(); if (something_read(t, tmp)) // if already something has been read break; continue; } // is this a token part separator? if (c == settings.multipart_token_separator) { syntax_assert(tmp.body.length() == 0, "empty part of multipart token detected"); t.parts.push_back(tmp); tmp.clear(); continue; } // or maybe some special token starts from here? int sti = special_token_from_here_index(c); if (sti > -1) // yes! { // if special token follows something, which has already been read if (something_read(t, tmp)) { line_buf.ungetch(); // put first character of the special token back to be read later break; // and definitively end the current token } // otherwise, skip characters of the current special token // and return the special token as a result tmp.body = settings.special_tokens[sti]; line_buf.skip(tmp.body.size() - 1); // one character less, because 1st character has been already read! break; } } // text qualifier NOT inside another qualification? if (qualification(c, settings.text_qualifier, qual_state, QualState::Text)) { if (qual_state == QualState::None) // start of the qualified text { if (something_read(t, tmp)) { line_buf.ungetch(); // put first character back to be read later break; // and definitively end the current token } qual_state = QualState::Text; tmp.type = token_part::Type::Text; tmp.qualified_by = settings.text_qualifier; continue; } // end of the qualified text qual_state = QualState::None; // we don't check for positive length here, because text may be empty (like '')! break; // definitively end-of-token } // token qualifier NOT inside another qualification? if (qualification(c, settings.token_part_qualifier, qual_state, QualState::Token)) { if (qual_state == QualState::None) // start of the qualified token part { if (tmp.body.length() != 0) // if something is being read { line_buf.ungetch(); // put first character back to be read later break; // and definitively end the current token } qual_state = QualState::Token; tmp.qualified_by = settings.token_part_qualifier; continue; } // end of the qualified token part syntax_assert(tmp.body.length() == 0, "empty qualified token part detected"); qual_state = QualState::None; // what follows the end of qualified token part? c = line_buf.getch(); line_buf.ungetch(1); if (c == settings.multipart_token_separator) // next part of the multipart token continue; break; // definitively end-of-token } tmp.body.append(1, c); } syntax_assert(qual_state == QualState::Token, "non-closed token part qualification"); syntax_assert(qual_state == QualState::Text, "non-closed text qualification"); if ((tmp.body.length() == 0) && (tmp.type != token_part::Type::Text)) // nothing found until end of stream // and this is not a qualified text (because text may be empty, like '') { syntax_assert(t.parts.size() > 0, "improper multipart token detected"); state = false; // say that this stream does not contain anything } else t.parts.push_back(tmp); } return *this; } bool token_stream::comment_from_here(const char c) { return string_from_here(c, settings.single_line_comment_prefix); } int token_stream::special_token_from_here_index(const char c) { for (unsigned int i = 0; i < settings.special_tokens.size(); i++) if (string_from_here(c, settings.special_tokens[i])) return i; return -1; } bool token_stream::string_from_here(const char c, const string& etalon) { if (etalon.length() == 0) return false; char cur_c = c; int cur_pos = 0; bool diff_found = true; while (etalon[cur_pos] == cur_c) { if (cur_pos == (etalon.length() - 1)) // end of etalon reached { diff_found = false; break; } if (!(cur_c = line_buf.getch())) break; cur_pos++; } if (cur_pos != 0) // rewind buffer back if checked more than current character line_buf.ungetch(cur_pos); return (!diff_found); } }
[ "dmytro@gerasymchuk.net" ]
dmytro@gerasymchuk.net
cb906b1c025b710a642d30045bad8455d92b5608
855aec2f376b3ab6f80b1d2c1715cf264ec68c7b
/2/src/2Example.cpp
a3d7246f3b74eac92a07cfebbeeeae42d30f0a50
[]
no_license
UW-COSC-4010-5010-CYBER-FA-2017/foundational-concepts-in-cybersecurity-agermann
7931b1ff20dced4f43dd30c5e1030a3fcef04c03
573836aec3af6b1b9e5af8eb043965586c5e765a
refs/heads/master
2021-07-23T19:14:48.875399
2017-11-01T02:53:25
2017-11-01T02:53:25
106,346,939
0
0
null
null
null
null
UTF-8
C++
false
false
1,041
cpp
#include <iostream> #include <string> using namespace std; int address[30]; void msWord() { int addressStart = 0; int addressEnd = 9; for (int i = addressStart; i <= addressEnd; ++i) { address[i] = 42; cout << "msWord accessing unique address space: address " << i << endl; } } void msPaint() { int addressStart = 10; int addressEnd = 19; for (int i = addressStart; i <= addressEnd; ++i) { address[i] = 23; cout << "msPaint accessing unique address space: address " << i << endl; } } void pinball() { int addressStart = 20; int addressEnd = 29; for (int i = addressStart; i <= addressEnd; ++i) { address[i] = 777; cout << "Pinball accessing unique address space: address " << i << endl; } } int main() { string input; for (int i = 0; i < 10; i++) { msWord(); msPaint(); pinball(); } cin >> input; return 0; }
[ "noreply@github.com" ]
noreply@github.com
136c9d1fdfce96601d57d86a1dffac8d88f0afd7
1ad6afd3a08c5487701038af3ad4511420d7d410
/llvm/tools/clang/tools/extra/unittests/clangd/ClangdTests.cpp
b0e56ba78e724de6a0e043d19e017e094535d206
[ "NCSA" ]
permissive
geekwish/Bitype
a12a42337d74328f2559513c2b1f3bee4549a63d
4b9605b6ba4d09efcdc97982ccd8b36e48d253cd
refs/heads/master
2020-08-19T12:35:44.141934
2018-12-23T04:53:26
2018-12-23T04:53:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,438
cpp
//===-- ClangdTests.cpp - Clangd unit tests ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Annotations.h" #include "ClangdLSPServer.h" #include "ClangdServer.h" #include "Matchers.h" #include "SyncAPI.h" #include "TestFS.h" #include "URI.h" #include "clang/Config/config.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Path.h" #include "llvm/Support/Regex.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <algorithm> #include <chrono> #include <iostream> #include <random> #include <string> #include <thread> #include <vector> namespace clang { namespace clangd { using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Gt; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; namespace { bool diagsContainErrors(const std::vector<Diag> &Diagnostics) { for (auto D : Diagnostics) { if (D.Severity == DiagnosticsEngine::Error || D.Severity == DiagnosticsEngine::Fatal) return true; } return false; } class ErrorCheckingDiagConsumer : public DiagnosticsConsumer { public: void onDiagnosticsReady(PathRef File, std::vector<Diag> Diagnostics) override { bool HadError = diagsContainErrors(Diagnostics); std::lock_guard<std::mutex> Lock(Mutex); HadErrorInLastDiags = HadError; } bool hadErrorInLastDiags() { std::lock_guard<std::mutex> Lock(Mutex); return HadErrorInLastDiags; } private: std::mutex Mutex; bool HadErrorInLastDiags = false; }; /// For each file, record whether the last published diagnostics contained at /// least one error. class MultipleErrorCheckingDiagConsumer : public DiagnosticsConsumer { public: void onDiagnosticsReady(PathRef File, std::vector<Diag> Diagnostics) override { bool HadError = diagsContainErrors(Diagnostics); std::lock_guard<std::mutex> Lock(Mutex); LastDiagsHadError[File] = HadError; } /// Exposes all files consumed by onDiagnosticsReady in an unspecified order. /// For each file, a bool value indicates whether the last diagnostics /// contained an error. std::vector<std::pair<Path, bool>> filesWithDiags() const { std::vector<std::pair<Path, bool>> Result; std::lock_guard<std::mutex> Lock(Mutex); for (const auto &it : LastDiagsHadError) { Result.emplace_back(it.first(), it.second); } return Result; } void clear() { std::lock_guard<std::mutex> Lock(Mutex); LastDiagsHadError.clear(); } private: mutable std::mutex Mutex; llvm::StringMap<bool> LastDiagsHadError; }; /// Replaces all patterns of the form 0x123abc with spaces std::string replacePtrsInDump(std::string const &Dump) { llvm::Regex RE("0x[0-9a-fA-F]+"); llvm::SmallVector<StringRef, 1> Matches; llvm::StringRef Pending = Dump; std::string Result; while (RE.match(Pending, &Matches)) { assert(Matches.size() == 1 && "Exactly one match expected"); auto MatchPos = Matches[0].data() - Pending.data(); Result += Pending.take_front(MatchPos); Pending = Pending.drop_front(MatchPos + Matches[0].size()); } Result += Pending; return Result; } std::string dumpASTWithoutMemoryLocs(ClangdServer &Server, PathRef File) { auto DumpWithMemLocs = runDumpAST(Server, File); return replacePtrsInDump(DumpWithMemLocs); } class ClangdVFSTest : public ::testing::Test { protected: std::string parseSourceAndDumpAST( PathRef SourceFileRelPath, StringRef SourceContents, std::vector<std::pair<PathRef, StringRef>> ExtraFiles = {}, bool ExpectErrors = false) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); for (const auto &FileWithContents : ExtraFiles) FS.Files[testPath(FileWithContents.first)] = FileWithContents.second; auto SourceFilename = testPath(SourceFileRelPath); Server.addDocument(SourceFilename, SourceContents); auto Result = dumpASTWithoutMemoryLocs(Server, SourceFilename); EXPECT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics"; EXPECT_EQ(ExpectErrors, DiagConsumer.hadErrorInLastDiags()); return Result; } }; TEST_F(ClangdVFSTest, Parse) { // FIXME: figure out a stable format for AST dumps, so that we can check the // output of the dump itself is equal to the expected one, not just that it's // different. auto Empty = parseSourceAndDumpAST("foo.cpp", "", {}); auto OneDecl = parseSourceAndDumpAST("foo.cpp", "int a;", {}); auto SomeDecls = parseSourceAndDumpAST("foo.cpp", "int a; int b; int c;", {}); EXPECT_NE(Empty, OneDecl); EXPECT_NE(Empty, SomeDecls); EXPECT_NE(SomeDecls, OneDecl); auto Empty2 = parseSourceAndDumpAST("foo.cpp", ""); auto OneDecl2 = parseSourceAndDumpAST("foo.cpp", "int a;"); auto SomeDecls2 = parseSourceAndDumpAST("foo.cpp", "int a; int b; int c;"); EXPECT_EQ(Empty, Empty2); EXPECT_EQ(OneDecl, OneDecl2); EXPECT_EQ(SomeDecls, SomeDecls2); } TEST_F(ClangdVFSTest, ParseWithHeader) { parseSourceAndDumpAST("foo.cpp", "#include \"foo.h\"", {}, /*ExpectErrors=*/true); parseSourceAndDumpAST("foo.cpp", "#include \"foo.h\"", {{"foo.h", ""}}, /*ExpectErrors=*/false); const auto SourceContents = R"cpp( #include "foo.h" int b = a; )cpp"; parseSourceAndDumpAST("foo.cpp", SourceContents, {{"foo.h", ""}}, /*ExpectErrors=*/true); parseSourceAndDumpAST("foo.cpp", SourceContents, {{"foo.h", "int a;"}}, /*ExpectErrors=*/false); } TEST_F(ClangdVFSTest, Reparse) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); const auto SourceContents = R"cpp( #include "foo.h" int b = a; )cpp"; auto FooCpp = testPath("foo.cpp"); FS.Files[testPath("foo.h")] = "int a;"; FS.Files[FooCpp] = SourceContents; Server.addDocument(FooCpp, SourceContents); auto DumpParse1 = dumpASTWithoutMemoryLocs(Server, FooCpp); ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics"; EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); Server.addDocument(FooCpp, ""); auto DumpParseEmpty = dumpASTWithoutMemoryLocs(Server, FooCpp); ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics"; EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); Server.addDocument(FooCpp, SourceContents); auto DumpParse2 = dumpASTWithoutMemoryLocs(Server, FooCpp); ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics"; EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); EXPECT_EQ(DumpParse1, DumpParse2); EXPECT_NE(DumpParse1, DumpParseEmpty); } TEST_F(ClangdVFSTest, ReparseOnHeaderChange) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); const auto SourceContents = R"cpp( #include "foo.h" int b = a; )cpp"; auto FooCpp = testPath("foo.cpp"); auto FooH = testPath("foo.h"); FS.Files[FooH] = "int a;"; FS.Files[FooCpp] = SourceContents; Server.addDocument(FooCpp, SourceContents); auto DumpParse1 = dumpASTWithoutMemoryLocs(Server, FooCpp); ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics"; EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); FS.Files[FooH] = ""; Server.addDocument(FooCpp, SourceContents); auto DumpParseDifferent = dumpASTWithoutMemoryLocs(Server, FooCpp); ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics"; EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags()); FS.Files[FooH] = "int a;"; Server.addDocument(FooCpp, SourceContents); auto DumpParse2 = dumpASTWithoutMemoryLocs(Server, FooCpp); ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics"; EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); EXPECT_EQ(DumpParse1, DumpParse2); EXPECT_NE(DumpParse1, DumpParseDifferent); } TEST_F(ClangdVFSTest, PropagatesContexts) { static Key<int> Secret; struct FSProvider : public FileSystemProvider { IntrusiveRefCntPtr<vfs::FileSystem> getFileSystem() override { Got = Context::current().getExisting(Secret); return buildTestFS({}); } int Got; } FS; struct DiagConsumer : public DiagnosticsConsumer { void onDiagnosticsReady(PathRef File, std::vector<Diag> Diagnostics) override { Got = Context::current().getExisting(Secret); } int Got; } DiagConsumer; MockCompilationDatabase CDB; // Verify that the context is plumbed to the FS provider and diagnostics. ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); { WithContextValue Entrypoint(Secret, 42); Server.addDocument(testPath("foo.cpp"), "void main(){}"); } ASSERT_TRUE(Server.blockUntilIdleForTest()); EXPECT_EQ(FS.Got, 42); EXPECT_EQ(DiagConsumer.Got, 42); } // Only enable this test on Unix #ifdef LLVM_ON_UNIX TEST_F(ClangdVFSTest, SearchLibDir) { // Checks that searches for GCC installation is done through vfs. MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; CDB.ExtraClangFlags.insert(CDB.ExtraClangFlags.end(), {"-xc++", "-target", "x86_64-linux-unknown", "-m64", "--gcc-toolchain=/randomusr", "-stdlib=libstdc++"}); ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); // Just a random gcc version string SmallString<8> Version("4.9.3"); // A lib dir for gcc installation SmallString<64> LibDir("/randomusr/lib/gcc/x86_64-linux-gnu"); llvm::sys::path::append(LibDir, Version); // Put crtbegin.o into LibDir/64 to trick clang into thinking there's a gcc // installation there. SmallString<64> DummyLibFile; llvm::sys::path::append(DummyLibFile, LibDir, "64", "crtbegin.o"); FS.Files[DummyLibFile] = ""; SmallString<64> IncludeDir("/randomusr/include/c++"); llvm::sys::path::append(IncludeDir, Version); SmallString<64> StringPath; llvm::sys::path::append(StringPath, IncludeDir, "string"); FS.Files[StringPath] = "class mock_string {};"; auto FooCpp = testPath("foo.cpp"); const auto SourceContents = R"cpp( #include <string> mock_string x; )cpp"; FS.Files[FooCpp] = SourceContents; runAddDocument(Server, FooCpp, SourceContents); EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); const auto SourceContentsWithError = R"cpp( #include <string> std::string x; )cpp"; runAddDocument(Server, FooCpp, SourceContentsWithError); EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags()); } #endif // LLVM_ON_UNIX TEST_F(ClangdVFSTest, ForceReparseCompileCommand) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); auto FooCpp = testPath("foo.cpp"); const auto SourceContents1 = R"cpp( template <class T> struct foo { T x; }; )cpp"; const auto SourceContents2 = R"cpp( template <class T> struct bar { T x; }; )cpp"; FS.Files[FooCpp] = ""; // First parse files in C mode and check they produce errors. CDB.ExtraClangFlags = {"-xc"}; runAddDocument(Server, FooCpp, SourceContents1); EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags()); runAddDocument(Server, FooCpp, SourceContents2); EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags()); // Now switch to C++ mode. CDB.ExtraClangFlags = {"-xc++"}; // By default addDocument does not check if CompileCommand has changed, so we // expect to see the errors. runAddDocument(Server, FooCpp, SourceContents1); EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags()); runAddDocument(Server, FooCpp, SourceContents2); EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags()); // Passing SkipCache=true will force addDocument to reparse the file with // proper flags. runAddDocument(Server, FooCpp, SourceContents2, WantDiagnostics::Auto, /*SkipCache=*/true); EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); // Subsequent addDocument calls should finish without errors too. runAddDocument(Server, FooCpp, SourceContents1); EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); runAddDocument(Server, FooCpp, SourceContents2); EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); } TEST_F(ClangdVFSTest, ForceReparseCompileCommandDefines) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); auto FooCpp = testPath("foo.cpp"); const auto SourceContents = R"cpp( #ifdef WITH_ERROR this #endif int main() { return 0; } )cpp"; FS.Files[FooCpp] = ""; // Parse with define, we expect to see the errors. CDB.ExtraClangFlags = {"-DWITH_ERROR"}; runAddDocument(Server, FooCpp, SourceContents); EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags()); // Parse without the define, no errors should be produced. CDB.ExtraClangFlags = {}; // By default addDocument does not check if CompileCommand has changed, so we // expect to see the errors. runAddDocument(Server, FooCpp, SourceContents); EXPECT_TRUE(DiagConsumer.hadErrorInLastDiags()); // Passing SkipCache=true will force addDocument to reparse the file with // proper flags. runAddDocument(Server, FooCpp, SourceContents, WantDiagnostics::Auto, /*SkipCache=*/true); ASSERT_TRUE(Server.blockUntilIdleForTest()); EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); // Subsequent addDocument call should finish without errors too. runAddDocument(Server, FooCpp, SourceContents); EXPECT_FALSE(DiagConsumer.hadErrorInLastDiags()); } // Test ClangdServer.reparseOpenedFiles. TEST_F(ClangdVFSTest, ReparseOpenedFiles) { Annotations FooSource(R"cpp( #ifdef MACRO static void $one[[bob]]() {} #else static void $two[[bob]]() {} #endif int main () { bo^b (); return 0; } )cpp"); Annotations BarSource(R"cpp( #ifdef MACRO this is an error #endif )cpp"); Annotations BazSource(R"cpp( int hello; )cpp"); MockFSProvider FS; MockCompilationDatabase CDB; MultipleErrorCheckingDiagConsumer DiagConsumer; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); auto FooCpp = testPath("foo.cpp"); auto BarCpp = testPath("bar.cpp"); auto BazCpp = testPath("baz.cpp"); FS.Files[FooCpp] = ""; FS.Files[BarCpp] = ""; FS.Files[BazCpp] = ""; CDB.ExtraClangFlags = {"-DMACRO=1"}; Server.addDocument(FooCpp, FooSource.code()); Server.addDocument(BarCpp, BarSource.code()); Server.addDocument(BazCpp, BazSource.code()); ASSERT_TRUE(Server.blockUntilIdleForTest()); EXPECT_THAT(DiagConsumer.filesWithDiags(), UnorderedElementsAre(Pair(FooCpp, false), Pair(BarCpp, true), Pair(BazCpp, false))); auto Locations = runFindDefinitions(Server, FooCpp, FooSource.point()); EXPECT_TRUE(bool(Locations)); EXPECT_THAT(*Locations, ElementsAre(Location{URIForFile{FooCpp}, FooSource.range("one")})); // Undefine MACRO, close baz.cpp. CDB.ExtraClangFlags.clear(); DiagConsumer.clear(); Server.removeDocument(BazCpp); Server.addDocument(FooCpp, FooSource.code(), WantDiagnostics::Auto, /*SkipCache=*/true); Server.addDocument(BarCpp, BarSource.code(), WantDiagnostics::Auto, /*SkipCache=*/true); ASSERT_TRUE(Server.blockUntilIdleForTest()); EXPECT_THAT(DiagConsumer.filesWithDiags(), UnorderedElementsAre(Pair(FooCpp, false), Pair(BarCpp, false))); Locations = runFindDefinitions(Server, FooCpp, FooSource.point()); EXPECT_TRUE(bool(Locations)); EXPECT_THAT(*Locations, ElementsAre(Location{URIForFile{FooCpp}, FooSource.range("two")})); } TEST_F(ClangdVFSTest, MemoryUsage) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); Path FooCpp = testPath("foo.cpp"); const auto SourceContents = R"cpp( struct Something { int method(); }; )cpp"; Path BarCpp = testPath("bar.cpp"); FS.Files[FooCpp] = ""; FS.Files[BarCpp] = ""; EXPECT_THAT(Server.getUsedBytesPerFile(), IsEmpty()); Server.addDocument(FooCpp, SourceContents); Server.addDocument(BarCpp, SourceContents); ASSERT_TRUE(Server.blockUntilIdleForTest()); EXPECT_THAT(Server.getUsedBytesPerFile(), UnorderedElementsAre(Pair(FooCpp, Gt(0u)), Pair(BarCpp, Gt(0u)))); Server.removeDocument(FooCpp); ASSERT_TRUE(Server.blockUntilIdleForTest()); EXPECT_THAT(Server.getUsedBytesPerFile(), ElementsAre(Pair(BarCpp, Gt(0u)))); Server.removeDocument(BarCpp); ASSERT_TRUE(Server.blockUntilIdleForTest()); EXPECT_THAT(Server.getUsedBytesPerFile(), IsEmpty()); } TEST_F(ClangdVFSTest, InvalidCompileCommand) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); auto FooCpp = testPath("foo.cpp"); // clang cannot create CompilerInvocation if we pass two files in the // CompileCommand. We pass the file in ExtraFlags once and CDB adds another // one in getCompileCommand(). CDB.ExtraClangFlags.push_back(FooCpp); // Clang can't parse command args in that case, but we shouldn't crash. runAddDocument(Server, FooCpp, "int main() {}"); EXPECT_EQ(runDumpAST(Server, FooCpp), "<no-ast>"); EXPECT_ERROR(runFindDefinitions(Server, FooCpp, Position())); EXPECT_ERROR(runFindDocumentHighlights(Server, FooCpp, Position())); EXPECT_ERROR(runRename(Server, FooCpp, Position(), "new_name")); // FIXME: codeComplete and signatureHelp should also return errors when they // can't parse the file. EXPECT_THAT(cantFail(runCodeComplete(Server, FooCpp, Position(), clangd::CodeCompleteOptions())) .items, IsEmpty()); auto SigHelp = runSignatureHelp(Server, FooCpp, Position()); ASSERT_TRUE(bool(SigHelp)) << "signatureHelp returned an error"; EXPECT_THAT(SigHelp->signatures, IsEmpty()); } class ClangdThreadingTest : public ClangdVFSTest {}; TEST_F(ClangdThreadingTest, StressTest) { // Without 'static' clang gives an error for a usage inside TestDiagConsumer. static const unsigned FilesCount = 5; const unsigned RequestsCount = 500; // Blocking requests wait for the parsing to complete, they slow down the test // dramatically, so they are issued rarely. Each // BlockingRequestInterval-request will be a blocking one. const unsigned BlockingRequestInterval = 40; const auto SourceContentsWithoutErrors = R"cpp( int a; int b; int c; int d; )cpp"; const auto SourceContentsWithErrors = R"cpp( int a = x; int b; int c; int d; )cpp"; // Giving invalid line and column number should not crash ClangdServer, but // just to make sure we're sometimes hitting the bounds inside the file we // limit the intervals of line and column number that are generated. unsigned MaxLineForFileRequests = 7; unsigned MaxColumnForFileRequests = 10; std::vector<std::string> FilePaths; MockFSProvider FS; for (unsigned I = 0; I < FilesCount; ++I) { std::string Name = std::string("Foo") + std::to_string(I) + ".cpp"; FS.Files[Name] = ""; FilePaths.push_back(testPath(Name)); } struct FileStat { unsigned HitsWithoutErrors = 0; unsigned HitsWithErrors = 0; bool HadErrorsInLastDiags = false; }; class TestDiagConsumer : public DiagnosticsConsumer { public: TestDiagConsumer() : Stats(FilesCount, FileStat()) {} void onDiagnosticsReady(PathRef File, std::vector<Diag> Diagnostics) override { StringRef FileIndexStr = llvm::sys::path::stem(File); ASSERT_TRUE(FileIndexStr.consume_front("Foo")); unsigned long FileIndex = std::stoul(FileIndexStr.str()); bool HadError = diagsContainErrors(Diagnostics); std::lock_guard<std::mutex> Lock(Mutex); if (HadError) Stats[FileIndex].HitsWithErrors++; else Stats[FileIndex].HitsWithoutErrors++; Stats[FileIndex].HadErrorsInLastDiags = HadError; } std::vector<FileStat> takeFileStats() { std::lock_guard<std::mutex> Lock(Mutex); return std::move(Stats); } private: std::mutex Mutex; std::vector<FileStat> Stats; }; struct RequestStats { unsigned RequestsWithoutErrors = 0; unsigned RequestsWithErrors = 0; bool LastContentsHadErrors = false; bool FileIsRemoved = true; }; std::vector<RequestStats> ReqStats; ReqStats.reserve(FilesCount); for (unsigned FileIndex = 0; FileIndex < FilesCount; ++FileIndex) ReqStats.emplace_back(); TestDiagConsumer DiagConsumer; { MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); // Prepare some random distributions for the test. std::random_device RandGen; std::uniform_int_distribution<unsigned> FileIndexDist(0, FilesCount - 1); // Pass a text that contains compiler errors to addDocument in about 20% of // all requests. std::bernoulli_distribution ShouldHaveErrorsDist(0.2); // Line and Column numbers for requests that need them. std::uniform_int_distribution<int> LineDist(0, MaxLineForFileRequests); std::uniform_int_distribution<int> ColumnDist(0, MaxColumnForFileRequests); // Some helpers. auto UpdateStatsOnAddDocument = [&](unsigned FileIndex, bool HadErrors) { auto &Stats = ReqStats[FileIndex]; if (HadErrors) ++Stats.RequestsWithErrors; else ++Stats.RequestsWithoutErrors; Stats.LastContentsHadErrors = HadErrors; Stats.FileIsRemoved = false; }; auto UpdateStatsOnRemoveDocument = [&](unsigned FileIndex) { auto &Stats = ReqStats[FileIndex]; Stats.FileIsRemoved = true; }; auto AddDocument = [&](unsigned FileIndex, bool SkipCache) { bool ShouldHaveErrors = ShouldHaveErrorsDist(RandGen); Server.addDocument(FilePaths[FileIndex], ShouldHaveErrors ? SourceContentsWithErrors : SourceContentsWithoutErrors, WantDiagnostics::Auto, SkipCache); UpdateStatsOnAddDocument(FileIndex, ShouldHaveErrors); }; // Various requests that we would randomly run. auto AddDocumentRequest = [&]() { unsigned FileIndex = FileIndexDist(RandGen); AddDocument(FileIndex, /*SkipCache=*/false); }; auto ForceReparseRequest = [&]() { unsigned FileIndex = FileIndexDist(RandGen); AddDocument(FileIndex, /*SkipCache=*/true); }; auto RemoveDocumentRequest = [&]() { unsigned FileIndex = FileIndexDist(RandGen); // Make sure we don't violate the ClangdServer's contract. if (ReqStats[FileIndex].FileIsRemoved) AddDocument(FileIndex, /*SkipCache=*/false); Server.removeDocument(FilePaths[FileIndex]); UpdateStatsOnRemoveDocument(FileIndex); }; auto CodeCompletionRequest = [&]() { unsigned FileIndex = FileIndexDist(RandGen); // Make sure we don't violate the ClangdServer's contract. if (ReqStats[FileIndex].FileIsRemoved) AddDocument(FileIndex, /*SkipCache=*/false); Position Pos; Pos.line = LineDist(RandGen); Pos.character = ColumnDist(RandGen); // FIXME(ibiryukov): Also test async completion requests. // Simply putting CodeCompletion into async requests now would make // tests slow, since there's no way to cancel previous completion // requests as opposed to AddDocument/RemoveDocument, which are implicitly // cancelled by any subsequent AddDocument/RemoveDocument request to the // same file. cantFail(runCodeComplete(Server, FilePaths[FileIndex], Pos, clangd::CodeCompleteOptions())); }; auto FindDefinitionsRequest = [&]() { unsigned FileIndex = FileIndexDist(RandGen); // Make sure we don't violate the ClangdServer's contract. if (ReqStats[FileIndex].FileIsRemoved) AddDocument(FileIndex, /*SkipCache=*/false); Position Pos; Pos.line = LineDist(RandGen); Pos.character = ColumnDist(RandGen); ASSERT_TRUE(!!runFindDefinitions(Server, FilePaths[FileIndex], Pos)); }; std::vector<std::function<void()>> AsyncRequests = { AddDocumentRequest, ForceReparseRequest, RemoveDocumentRequest}; std::vector<std::function<void()>> BlockingRequests = { CodeCompletionRequest, FindDefinitionsRequest}; // Bash requests to ClangdServer in a loop. std::uniform_int_distribution<int> AsyncRequestIndexDist( 0, AsyncRequests.size() - 1); std::uniform_int_distribution<int> BlockingRequestIndexDist( 0, BlockingRequests.size() - 1); for (unsigned I = 1; I <= RequestsCount; ++I) { if (I % BlockingRequestInterval != 0) { // Issue an async request most of the time. It should be fast. unsigned RequestIndex = AsyncRequestIndexDist(RandGen); AsyncRequests[RequestIndex](); } else { // Issue a blocking request once in a while. auto RequestIndex = BlockingRequestIndexDist(RandGen); BlockingRequests[RequestIndex](); } } } // Wait for ClangdServer to shutdown before proceeding. // Check some invariants about the state of the program. std::vector<FileStat> Stats = DiagConsumer.takeFileStats(); for (unsigned I = 0; I < FilesCount; ++I) { if (!ReqStats[I].FileIsRemoved) { ASSERT_EQ(Stats[I].HadErrorsInLastDiags, ReqStats[I].LastContentsHadErrors); } ASSERT_LE(Stats[I].HitsWithErrors, ReqStats[I].RequestsWithErrors); ASSERT_LE(Stats[I].HitsWithoutErrors, ReqStats[I].RequestsWithoutErrors); } } TEST_F(ClangdVFSTest, CheckSourceHeaderSwitch) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); auto SourceContents = R"cpp( #include "foo.h" int b = a; )cpp"; auto FooCpp = testPath("foo.cpp"); auto FooH = testPath("foo.h"); auto Invalid = testPath("main.cpp"); FS.Files[FooCpp] = SourceContents; FS.Files[FooH] = "int a;"; FS.Files[Invalid] = "int main() { \n return 0; \n }"; llvm::Optional<Path> PathResult = Server.switchSourceHeader(FooCpp); EXPECT_TRUE(PathResult.hasValue()); ASSERT_EQ(PathResult.getValue(), FooH); PathResult = Server.switchSourceHeader(FooH); EXPECT_TRUE(PathResult.hasValue()); ASSERT_EQ(PathResult.getValue(), FooCpp); SourceContents = R"c( #include "foo.HH" int b = a; )c"; // Test with header file in capital letters and different extension, source // file with different extension auto FooC = testPath("bar.c"); auto FooHH = testPath("bar.HH"); FS.Files[FooC] = SourceContents; FS.Files[FooHH] = "int a;"; PathResult = Server.switchSourceHeader(FooC); EXPECT_TRUE(PathResult.hasValue()); ASSERT_EQ(PathResult.getValue(), FooHH); // Test with both capital letters auto Foo2C = testPath("foo2.C"); auto Foo2HH = testPath("foo2.HH"); FS.Files[Foo2C] = SourceContents; FS.Files[Foo2HH] = "int a;"; PathResult = Server.switchSourceHeader(Foo2C); EXPECT_TRUE(PathResult.hasValue()); ASSERT_EQ(PathResult.getValue(), Foo2HH); // Test with source file as capital letter and .hxx header file auto Foo3C = testPath("foo3.C"); auto Foo3HXX = testPath("foo3.hxx"); SourceContents = R"c( #include "foo3.hxx" int b = a; )c"; FS.Files[Foo3C] = SourceContents; FS.Files[Foo3HXX] = "int a;"; PathResult = Server.switchSourceHeader(Foo3C); EXPECT_TRUE(PathResult.hasValue()); ASSERT_EQ(PathResult.getValue(), Foo3HXX); // Test if asking for a corresponding file that doesn't exist returns an empty // string. PathResult = Server.switchSourceHeader(Invalid); EXPECT_FALSE(PathResult.hasValue()); } TEST_F(ClangdThreadingTest, NoConcurrentDiagnostics) { class NoConcurrentAccessDiagConsumer : public DiagnosticsConsumer { public: std::atomic<int> Count = {0}; NoConcurrentAccessDiagConsumer(std::promise<void> StartSecondReparse) : StartSecondReparse(std::move(StartSecondReparse)) {} void onDiagnosticsReady(PathRef, std::vector<Diag>) override { ++Count; std::unique_lock<std::mutex> Lock(Mutex, std::try_to_lock_t()); ASSERT_TRUE(Lock.owns_lock()) << "Detected concurrent onDiagnosticsReady calls for the same file."; // If we started the second parse immediately, it might cancel the first. // So we don't allow it to start until the first has delivered diags... if (FirstRequest) { FirstRequest = false; StartSecondReparse.set_value(); // ... but then we wait long enough that the callbacks would overlap. std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } private: std::mutex Mutex; bool FirstRequest = true; std::promise<void> StartSecondReparse; }; const auto SourceContentsWithoutErrors = R"cpp( int a; int b; int c; int d; )cpp"; const auto SourceContentsWithErrors = R"cpp( int a = x; int b; int c; int d; )cpp"; auto FooCpp = testPath("foo.cpp"); MockFSProvider FS; FS.Files[FooCpp] = ""; std::promise<void> StartSecondPromise; std::future<void> StartSecond = StartSecondPromise.get_future(); NoConcurrentAccessDiagConsumer DiagConsumer(std::move(StartSecondPromise)); MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); Server.addDocument(FooCpp, SourceContentsWithErrors); StartSecond.wait(); Server.addDocument(FooCpp, SourceContentsWithoutErrors); ASSERT_TRUE(Server.blockUntilIdleForTest()) << "Waiting for diagnostics"; ASSERT_EQ(DiagConsumer.Count, 2); // Sanity check - we actually ran both? } TEST_F(ClangdVFSTest, InsertIncludes) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; std::string SearchDirArg = (llvm::Twine("-I") + testRoot()).str(); CDB.ExtraClangFlags.insert(CDB.ExtraClangFlags.end(), {SearchDirArg.c_str()}); ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); auto FooCpp = testPath("foo.cpp"); const auto Code = R"cpp( #include "x.h" #include "z.h" void f() {} )cpp"; FS.Files[FooCpp] = Code; runAddDocument(Server, FooCpp, Code); auto ChangedCode = [&](llvm::StringRef Original, llvm::StringRef Preferred) { auto Replaces = Server.insertInclude( FooCpp, Code, Original, Preferred.empty() ? Original : Preferred); EXPECT_TRUE(static_cast<bool>(Replaces)); auto Changed = tooling::applyAllReplacements(Code, *Replaces); EXPECT_TRUE(static_cast<bool>(Changed)); return *Changed; }; auto Inserted = [&](llvm::StringRef Original, llvm::StringRef Preferred, llvm::StringRef Expected) { return llvm::StringRef(ChangedCode(Original, Preferred)) .contains((llvm::Twine("#include ") + Expected + "").str()); }; EXPECT_TRUE(Inserted("\"y.h\"", /*Preferred=*/"", "\"y.h\"")); EXPECT_TRUE(Inserted("\"y.h\"", /*Preferred=*/"\"Y.h\"", "\"Y.h\"")); EXPECT_TRUE(Inserted("<string>", /*Preferred=*/"", "<string>")); EXPECT_TRUE(Inserted("<string>", /*Preferred=*/"", "<string>")); std::string OriginalHeader = URI::createFile(testPath("y.h")).toString(); std::string PreferredHeader = URI::createFile(testPath("Y.h")).toString(); EXPECT_TRUE(Inserted(OriginalHeader, /*Preferred=*/"", "\"y.h\"")); EXPECT_TRUE(Inserted(OriginalHeader, /*Preferred=*/"<Y.h>", "<Y.h>")); EXPECT_TRUE(Inserted(OriginalHeader, PreferredHeader, "\"Y.h\"")); EXPECT_TRUE(Inserted("<y.h>", PreferredHeader, "\"Y.h\"")); // Check that includes are sorted. const auto Expected = R"cpp( #include "x.h" #include "y.h" #include "z.h" void f() {} )cpp"; EXPECT_EQ(Expected, ChangedCode("\"y.h\"", /*Preferred=*/"")); } TEST_F(ClangdVFSTest, FormatCode) { MockFSProvider FS; ErrorCheckingDiagConsumer DiagConsumer; MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, DiagConsumer, ClangdServer::optsForTest()); auto Path = testPath("foo.cpp"); std::string Code = R"cpp( #include "x.h" #include "y.h" void f( ) {} )cpp"; std::string Expected = R"cpp( #include "x.h" #include "y.h" void f() {} )cpp"; FS.Files[Path] = Code; runAddDocument(Server, Path, Code); auto Replaces = Server.formatFile(Code, Path); EXPECT_TRUE(static_cast<bool>(Replaces)); auto Changed = tooling::applyAllReplacements(Code, *Replaces); EXPECT_TRUE(static_cast<bool>(Changed)); EXPECT_EQ(Expected, *Changed); } } // namespace } // namespace clangd } // namespace clang
[ "1131252124@qq.com" ]
1131252124@qq.com
ec54c920bf536f3628ae64da8f5477b3ff844d68
5e5b7e7435ac4fe1a58049c72d42b31f2abc9dca
/TappyPlane/Entity/RockManager.h
5429d870252334e25973589f7db530f024371078
[]
no_license
JRasay89/TappyPlane
e16d2ee79e021fad86323a7d0b2562a4b6662ccf
4458fa89c15f2f6dd7750092bff9d7f8a43bc670
refs/heads/master
2016-09-05T16:44:26.376188
2014-09-11T05:32:00
2014-09-11T05:32:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
439
h
#ifndef ROCKMANAGER_H_ #define ROCKMANAGER_H_ //Entity #include "NorthSouthRock.h" #include <vector> class RockManager { private: std::vector<NorthSouthRock> rocks_; int elapsedTime_; int type_; public: RockManager(); void init(int type); void update(int deltaTime); void draw(Graphics* graphics, Image* image); std::vector<NorthSouthRock>& getRocks(); void clearRocks(); }; #endif // ROCKMANAGER_H_
[ "newtype187@yahoo.com" ]
newtype187@yahoo.com
1bac008d01ec3cead4e50c37c3ac8eb3fd8342b3
410e45283cf691f932b07c5fdf18d8d8ac9b57c3
/services/network/network_service_unittest.cc
30bce429d0e092a19902d0bc0230245e0708d090
[ "BSD-3-Clause" ]
permissive
yanhuashengdian/chrome_browser
f52a7f533a6b8417e19b85f765f43ea63307a1fb
972d284a9ffa4b794f659f5acc4116087704394c
refs/heads/master
2022-12-21T03:43:07.108853
2019-04-29T14:20:05
2019-04-29T14:20:05
184,068,841
0
2
BSD-3-Clause
2022-12-17T17:35:55
2019-04-29T12:40:27
null
UTF-8
C++
false
false
66,448
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/network/network_service.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/containers/span.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/json/json_file_value_serializer.h" #include "base/optional.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/test/bind_test_util.h" #include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "net/base/escape.h" #include "net/base/mock_network_change_notifier.h" #include "net/base/url_util.h" #include "net/dns/dns_config_service.h" #include "net/dns/host_resolver.h" #include "net/dns/host_resolver_manager.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_auth_scheme.h" #include "net/net_buildflags.h" #include "net/proxy_resolution/proxy_config.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "net/test/spawned_test_server/spawned_test_server.h" #include "net/test/test_data_directory.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_context.h" #include "services/network/network_context.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/network_switches.h" #include "services/network/public/mojom/net_log.mojom.h" #include "services/network/public/mojom/network_change_manager.mojom.h" #include "services/network/public/mojom/network_service.mojom.h" #include "services/network/test/test_network_service_client.h" #include "services/network/test/test_url_loader_client.h" #include "services/service_manager/public/cpp/test/test_connector_factory.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #if BUILDFLAG(USE_KERBEROS) #include "net/http/http_auth_handler_negotiate.h" #endif namespace network { namespace { const char kNetworkServiceName[] = "network"; const base::FilePath::CharType kServicesTestData[] = FILE_PATH_LITERAL("services/test/data"); // Returns a new URL with key=value pair added to the query. GURL AddQuery(const GURL& url, const std::string& key, const std::string& value) { return GURL(url.spec() + (url.has_query() ? "&" : "?") + key + "=" + net::EscapeQueryParamValue(value, false)); } mojom::NetworkContextParamsPtr CreateContextParams() { mojom::NetworkContextParamsPtr params = mojom::NetworkContextParams::New(); // Use a fixed proxy config, to avoid dependencies on local network // configuration. params->initial_proxy_config = net::ProxyConfigWithAnnotation::CreateDirect(); return params; } class NetworkServiceTest : public testing::Test { public: NetworkServiceTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO), service_(NetworkService::CreateForTesting()) {} ~NetworkServiceTest() override {} NetworkService* service() const { return service_.get(); } void DestroyService() { service_.reset(); } private: base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<NetworkService> service_; }; // Test shutdown in the case a NetworkContext is destroyed before the // NetworkService. TEST_F(NetworkServiceTest, CreateAndDestroyContext) { mojom::NetworkContextPtr network_context; service()->CreateNetworkContext(mojo::MakeRequest(&network_context), CreateContextParams()); network_context.reset(); // Make sure the NetworkContext is destroyed. base::RunLoop().RunUntilIdle(); } // Test shutdown in the case there is still a live NetworkContext when the // NetworkService is destroyed. The service should destroy the NetworkContext // itself. TEST_F(NetworkServiceTest, DestroyingServiceDestroysContext) { mojom::NetworkContextPtr network_context; service()->CreateNetworkContext(mojo::MakeRequest(&network_context), CreateContextParams()); base::RunLoop run_loop; network_context.set_connection_error_handler(run_loop.QuitClosure()); DestroyService(); // Destroying the service should destroy the context, causing a connection // error. run_loop.Run(); } TEST_F(NetworkServiceTest, CreateContextWithoutChannelID) { mojom::NetworkContextParamsPtr params = CreateContextParams(); params->cookie_path = base::FilePath(); params->enable_encrypted_cookies = false; mojom::NetworkContextPtr network_context; service()->CreateNetworkContext(mojo::MakeRequest(&network_context), std::move(params)); network_context.reset(); // Make sure the NetworkContext is destroyed. base::RunLoop().RunUntilIdle(); } // Platforms where Negotiate can be used. #if BUILDFLAG(USE_KERBEROS) && !defined(OS_ANDROID) // Returns the negotiate factory, if one exists, to query its configuration. net::HttpAuthHandlerNegotiate::Factory* GetNegotiateFactory( NetworkContext* network_context) { net::HttpAuthHandlerFactory* auth_factory = network_context->url_request_context()->http_auth_handler_factory(); return reinterpret_cast<net::HttpAuthHandlerNegotiate::Factory*>( reinterpret_cast<net::HttpAuthHandlerRegistryFactory*>(auth_factory) ->GetSchemeFactory(net::kNegotiateAuthScheme)); } #endif // BUILDFLAG(USE_KERBEROS) TEST_F(NetworkServiceTest, AuthDefaultParams) { mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerRegistryFactory* auth_handler_factory = reinterpret_cast<net::HttpAuthHandlerRegistryFactory*>( network_context.url_request_context()->http_auth_handler_factory()); ASSERT_TRUE(auth_handler_factory); // These three factories should always be created by default. Negotiate may // or may not be created, depending on other build flags. EXPECT_TRUE(auth_handler_factory->GetSchemeFactory(net::kBasicAuthScheme)); EXPECT_TRUE(auth_handler_factory->GetSchemeFactory(net::kDigestAuthScheme)); EXPECT_TRUE(auth_handler_factory->GetSchemeFactory(net::kNtlmAuthScheme)); #if BUILDFLAG(USE_KERBEROS) && !defined(OS_ANDROID) ASSERT_TRUE(GetNegotiateFactory(&network_context)); #if defined(OS_CHROMEOS) EXPECT_TRUE(GetNegotiateFactory(&network_context) ->allow_gssapi_library_load_for_testing()); #elif defined(OS_POSIX) EXPECT_EQ("", GetNegotiateFactory(&network_context)->GetLibraryNameForTesting()); #endif #endif // BUILDFLAG(USE_KERBEROS) && !defined(OS_ANDROID) EXPECT_FALSE(auth_handler_factory->http_auth_preferences() ->NegotiateDisableCnameLookup()); EXPECT_FALSE( auth_handler_factory->http_auth_preferences()->NegotiateEnablePort()); #if defined(OS_POSIX) || defined(OS_FUCHSIA) EXPECT_TRUE(auth_handler_factory->http_auth_preferences()->NtlmV2Enabled()); #endif // defined(OS_POSIX) || defined(OS_FUCHSIA) #if defined(OS_ANDROID) EXPECT_EQ("", auth_handler_factory->http_auth_preferences() ->AuthAndroidNegotiateAccountType()); #endif // defined(OS_ANDROID) } TEST_F(NetworkServiceTest, AuthSchemesDigestAndNtlmOnly) { mojom::HttpAuthStaticParamsPtr auth_params = mojom::HttpAuthStaticParams::New(); auth_params->supported_schemes.push_back("digest"); auth_params->supported_schemes.push_back("ntlm"); service()->SetUpHttpAuth(std::move(auth_params)); mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerRegistryFactory* auth_handler_factory = reinterpret_cast<net::HttpAuthHandlerRegistryFactory*>( network_context.url_request_context()->http_auth_handler_factory()); ASSERT_TRUE(auth_handler_factory); EXPECT_FALSE(auth_handler_factory->GetSchemeFactory(net::kBasicAuthScheme)); EXPECT_TRUE(auth_handler_factory->GetSchemeFactory(net::kDigestAuthScheme)); EXPECT_TRUE(auth_handler_factory->GetSchemeFactory(net::kNtlmAuthScheme)); EXPECT_FALSE( auth_handler_factory->GetSchemeFactory(net::kNegotiateAuthScheme)); } TEST_F(NetworkServiceTest, AuthSchemesNone) { // An empty list means to support no schemes. service()->SetUpHttpAuth(mojom::HttpAuthStaticParams::New()); mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerRegistryFactory* auth_handler_factory = reinterpret_cast<net::HttpAuthHandlerRegistryFactory*>( network_context.url_request_context()->http_auth_handler_factory()); ASSERT_TRUE(auth_handler_factory); EXPECT_FALSE(auth_handler_factory->GetSchemeFactory(net::kBasicAuthScheme)); EXPECT_FALSE(auth_handler_factory->GetSchemeFactory(net::kDigestAuthScheme)); EXPECT_FALSE(auth_handler_factory->GetSchemeFactory(net::kNtlmAuthScheme)); } // |allow_gssapi_library_load| is only supported on ChromeOS. #if defined(OS_CHROMEOS) TEST_F(NetworkServiceTest, AuthGssapiLibraryDisabled) { mojom::HttpAuthStaticParamsPtr auth_params = mojom::HttpAuthStaticParams::New(); auth_params->supported_schemes.push_back("negotiate"); auth_params->allow_gssapi_library_load = false; service()->SetUpHttpAuth(std::move(auth_params)); mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); ASSERT_TRUE(GetNegotiateFactory(&network_context)); EXPECT_FALSE(GetNegotiateFactory(&network_context) ->allow_gssapi_library_load_for_testing()); } #endif // defined(OS_CHROMEOS) // |gssapi_library_name| is only supported on certain POSIX platforms. #if BUILDFLAG(USE_KERBEROS) && defined(OS_POSIX) && !defined(OS_ANDROID) && \ !defined(OS_CHROMEOS) TEST_F(NetworkServiceTest, AuthGssapiLibraryName) { const std::string kGssapiLibraryName = "Jim"; mojom::HttpAuthStaticParamsPtr auth_params = mojom::HttpAuthStaticParams::New(); auth_params->supported_schemes.push_back("negotiate"); auth_params->gssapi_library_name = kGssapiLibraryName; service()->SetUpHttpAuth(std::move(auth_params)); mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); ASSERT_TRUE(GetNegotiateFactory(&network_context)); EXPECT_EQ(kGssapiLibraryName, GetNegotiateFactory(&network_context)->GetLibraryNameForTesting()); } #endif TEST_F(NetworkServiceTest, AuthServerWhitelist) { // Add one server to the whitelist before creating any NetworkContexts. mojom::HttpAuthDynamicParamsPtr auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->server_whitelist = "server1"; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); // Create a network context, which should reflect the whitelist. mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerFactory* auth_handler_factory = network_context.url_request_context()->http_auth_handler_factory(); ASSERT_TRUE(auth_handler_factory); ASSERT_TRUE(auth_handler_factory->http_auth_preferences()); EXPECT_TRUE( auth_handler_factory->http_auth_preferences()->CanUseDefaultCredentials( GURL("https://server1/"))); EXPECT_FALSE( auth_handler_factory->http_auth_preferences()->CanUseDefaultCredentials( GURL("https://server2/"))); // Change whitelist to only have a different server on it. The pre-existing // NetworkContext should be using the new list. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->server_whitelist = "server2"; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_FALSE( auth_handler_factory->http_auth_preferences()->CanUseDefaultCredentials( GURL("https://server1/"))); EXPECT_TRUE( auth_handler_factory->http_auth_preferences()->CanUseDefaultCredentials( GURL("https://server2/"))); // Change whitelist to have multiple servers. The pre-existing NetworkContext // should be using the new list. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->server_whitelist = "server1,server2"; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_TRUE( auth_handler_factory->http_auth_preferences()->CanUseDefaultCredentials( GURL("https://server1/"))); EXPECT_TRUE( auth_handler_factory->http_auth_preferences()->CanUseDefaultCredentials( GURL("https://server2/"))); } TEST_F(NetworkServiceTest, AuthDelegateWhitelist) { using DelegationType = net::HttpAuth::DelegationType; // Add one server to the whitelist before creating any NetworkContexts. mojom::HttpAuthDynamicParamsPtr auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->delegate_whitelist = "server1"; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); // Create a network context, which should reflect the whitelist. mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerFactory* auth_handler_factory = network_context.url_request_context()->http_auth_handler_factory(); ASSERT_TRUE(auth_handler_factory); const net::HttpAuthPreferences* auth_prefs = auth_handler_factory->http_auth_preferences(); ASSERT_TRUE(auth_prefs); EXPECT_EQ(DelegationType::kUnconstrained, auth_prefs->GetDelegationType(GURL("https://server1/"))); EXPECT_EQ(DelegationType::kNone, auth_prefs->GetDelegationType(GURL("https://server2/"))); // Change whitelist to only have a different server on it. The pre-existing // NetworkContext should be using the new list. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->delegate_whitelist = "server2"; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_EQ(DelegationType::kNone, auth_prefs->GetDelegationType(GURL("https://server1/"))); EXPECT_EQ(DelegationType::kUnconstrained, auth_prefs->GetDelegationType(GURL("https://server2/"))); // Change whitelist to have multiple servers. The pre-existing NetworkContext // should be using the new list. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->delegate_whitelist = "server1,server2"; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_EQ(DelegationType::kUnconstrained, auth_prefs->GetDelegationType(GURL("https://server1/"))); EXPECT_EQ(DelegationType::kUnconstrained, auth_prefs->GetDelegationType(GURL("https://server2/"))); } TEST_F(NetworkServiceTest, DelegateByKdcPolicy) { // Create a network context, which should use default value. mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerFactory* auth_handler_factory = network_context.url_request_context()->http_auth_handler_factory(); ASSERT_TRUE(auth_handler_factory); ASSERT_TRUE(auth_handler_factory->http_auth_preferences()); EXPECT_FALSE( auth_handler_factory->http_auth_preferences()->delegate_by_kdc_policy()); // Change whitelist to only have a different server on it. The pre-existing // NetworkContext should be using the new list. mojom::HttpAuthDynamicParamsPtr auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->delegate_by_kdc_policy = true; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_TRUE( auth_handler_factory->http_auth_preferences()->delegate_by_kdc_policy()); } TEST_F(NetworkServiceTest, AuthNegotiateCnameLookup) { // Set |negotiate_disable_cname_lookup| to true before creating any // NetworkContexts. mojom::HttpAuthDynamicParamsPtr auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->negotiate_disable_cname_lookup = true; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); // Create a network context, which should reflect the setting. mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerFactory* auth_handler_factory = network_context.url_request_context()->http_auth_handler_factory(); ASSERT_TRUE(auth_handler_factory); ASSERT_TRUE(auth_handler_factory->http_auth_preferences()); EXPECT_TRUE(auth_handler_factory->http_auth_preferences() ->NegotiateDisableCnameLookup()); // Set it to false. The pre-existing NetworkContext should be using the new // setting. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->negotiate_disable_cname_lookup = false; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_FALSE(auth_handler_factory->http_auth_preferences() ->NegotiateDisableCnameLookup()); // Set it back to true. The pre-existing NetworkContext should be using the // new setting. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->negotiate_disable_cname_lookup = true; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_TRUE(auth_handler_factory->http_auth_preferences() ->NegotiateDisableCnameLookup()); } TEST_F(NetworkServiceTest, AuthEnableNegotiatePort) { // Set |enable_negotiate_port| to true before creating any NetworkContexts. mojom::HttpAuthDynamicParamsPtr auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->enable_negotiate_port = true; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); // Create a network context, which should reflect the setting. mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerFactory* auth_handler_factory = network_context.url_request_context()->http_auth_handler_factory(); ASSERT_TRUE(auth_handler_factory); ASSERT_TRUE(auth_handler_factory->http_auth_preferences()); EXPECT_TRUE( auth_handler_factory->http_auth_preferences()->NegotiateEnablePort()); // Set it to false. The pre-existing NetworkContext should be using the new // setting. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->enable_negotiate_port = false; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_FALSE( auth_handler_factory->http_auth_preferences()->NegotiateEnablePort()); // Set it back to true. The pre-existing NetworkContext should be using the // new setting. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->enable_negotiate_port = true; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_TRUE( auth_handler_factory->http_auth_preferences()->NegotiateEnablePort()); } // DnsClient isn't supported on iOS. #if !defined(OS_IOS) TEST_F(NetworkServiceTest, DnsClientEnableDisable) { // HostResolver::GetDnsConfigAsValue() returns nullptr if the stub resolver is // disabled. EXPECT_FALSE(service()->host_resolver_manager()->GetDnsConfigAsValue()); service()->ConfigureStubHostResolver( true /* stub_resolver_enabled */, base::nullopt /* dns_over_https_servers */); EXPECT_TRUE(service()->host_resolver_manager()->GetDnsConfigAsValue()); service()->ConfigureStubHostResolver( false /* stub_resolver_enabled */, base::nullopt /* dns_over_https_servers */); EXPECT_FALSE(service()->host_resolver_manager()->GetDnsConfigAsValue()); } TEST_F(NetworkServiceTest, DnsOverHttpsEnableDisable) { const std::string kServer1 = "https://foo/"; const bool kServer1UsePost = false; const std::string kServer2 = "https://bar/dns-query{?dns}"; const bool kServer2UsePost = true; const std::string kServer3 = "https://grapefruit/resolver/query{?dns}"; const bool kServer3UsePost = false; // HostResolver::GetDnsClientForTesting() returns nullptr if the stub resolver // is disabled. EXPECT_FALSE(service()->host_resolver_manager()->GetDnsConfigAsValue()); // Create the primary NetworkContext before enabling DNS over HTTPS. mojom::NetworkContextPtr network_context; mojom::NetworkContextParamsPtr context_params = CreateContextParams(); context_params->primary_network_context = true; service()->CreateNetworkContext(mojo::MakeRequest(&network_context), std::move(context_params)); // Enable DNS over HTTPS for one server. std::vector<mojom::DnsOverHttpsServerPtr> dns_over_https_servers_ptr; mojom::DnsOverHttpsServerPtr dns_over_https_server = mojom::DnsOverHttpsServer::New(); dns_over_https_server->server_template = kServer1; dns_over_https_server->use_post = kServer1UsePost; dns_over_https_servers_ptr.emplace_back(std::move(dns_over_https_server)); service()->ConfigureStubHostResolver(true /* stub_resolver_enabled */, std::move(dns_over_https_servers_ptr)); EXPECT_TRUE(service()->host_resolver_manager()->GetDnsConfigAsValue()); const auto* dns_over_https_servers = service()->host_resolver_manager()->GetDnsOverHttpsServersForTesting(); ASSERT_TRUE(dns_over_https_servers); ASSERT_EQ(1u, dns_over_https_servers->size()); EXPECT_EQ(kServer1, (*dns_over_https_servers)[0].server_template); EXPECT_EQ(kServer1UsePost, (*dns_over_https_servers)[0].use_post); // Enable DNS over HTTPS for two servers. dns_over_https_servers_ptr.clear(); dns_over_https_server = mojom::DnsOverHttpsServer::New(); dns_over_https_server->server_template = kServer2; dns_over_https_server->use_post = kServer2UsePost; dns_over_https_servers_ptr.emplace_back(std::move(dns_over_https_server)); dns_over_https_server = mojom::DnsOverHttpsServer::New(); dns_over_https_server->server_template = kServer3; dns_over_https_server->use_post = kServer3UsePost; dns_over_https_servers_ptr.emplace_back(std::move(dns_over_https_server)); service()->ConfigureStubHostResolver(true /* stub_resolver_enabled */, std::move(dns_over_https_servers_ptr)); EXPECT_TRUE(service()->host_resolver_manager()->GetDnsConfigAsValue()); dns_over_https_servers = service()->host_resolver_manager()->GetDnsOverHttpsServersForTesting(); ASSERT_TRUE(dns_over_https_servers); ASSERT_EQ(2u, dns_over_https_servers->size()); EXPECT_EQ(kServer2, (*dns_over_https_servers)[0].server_template); EXPECT_EQ(kServer2UsePost, (*dns_over_https_servers)[0].use_post); EXPECT_EQ(kServer3, (*dns_over_https_servers)[1].server_template); EXPECT_EQ(kServer3UsePost, (*dns_over_https_servers)[1].use_post); // Destroying the primary NetworkContext should disable DNS over HTTPS. network_context.reset(); base::RunLoop().RunUntilIdle(); // DnsClient is still enabled. EXPECT_TRUE(service()->host_resolver_manager()->GetDnsConfigAsValue()); // DNS over HTTPS is not. EXPECT_FALSE( service()->host_resolver_manager()->GetDnsOverHttpsServersForTesting()); } #endif // !defined(OS_IOS) // |ntlm_v2_enabled| is only supported on POSIX platforms. #if defined(OS_POSIX) TEST_F(NetworkServiceTest, AuthNtlmV2Enabled) { // Set |ntlm_v2_enabled| to false before creating any NetworkContexts. mojom::HttpAuthDynamicParamsPtr auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->ntlm_v2_enabled = false; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); // Create a network context, which should reflect the setting. mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerFactory* auth_handler_factory = network_context.url_request_context()->http_auth_handler_factory(); ASSERT_TRUE(auth_handler_factory); ASSERT_TRUE(auth_handler_factory->http_auth_preferences()); EXPECT_FALSE(auth_handler_factory->http_auth_preferences()->NtlmV2Enabled()); // Set it to true. The pre-existing NetworkContext should be using the new // setting. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->ntlm_v2_enabled = true; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_TRUE(auth_handler_factory->http_auth_preferences()->NtlmV2Enabled()); // Set it back to false. The pre-existing NetworkContext should be using the // new setting. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->ntlm_v2_enabled = false; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_FALSE(auth_handler_factory->http_auth_preferences()->NtlmV2Enabled()); } #endif // defined(OS_POSIX) // |android_negotiate_account_type| is only supported on Android. #if defined(OS_ANDROID) TEST_F(NetworkServiceTest, AuthAndroidNegotiateAccountType) { const char kInitialAccountType[] = "Scorpio"; const char kFinalAccountType[] = "Pisces"; // Set |android_negotiate_account_type| to before creating any // NetworkContexts. mojom::HttpAuthDynamicParamsPtr auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->android_negotiate_account_type = kInitialAccountType; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); // Create a network context, which should reflect the setting. mojom::NetworkContextPtr network_context_ptr; NetworkContext network_context(service(), mojo::MakeRequest(&network_context_ptr), CreateContextParams()); net::HttpAuthHandlerFactory* auth_handler_factory = network_context.url_request_context()->http_auth_handler_factory(); ASSERT_TRUE(auth_handler_factory); ASSERT_TRUE(auth_handler_factory->http_auth_preferences()); EXPECT_EQ(kInitialAccountType, auth_handler_factory->http_auth_preferences() ->AuthAndroidNegotiateAccountType()); // Change |android_negotiate_account_type|. The pre-existing NetworkContext // should be using the new setting. auth_params = mojom::HttpAuthDynamicParams::New(); auth_params->android_negotiate_account_type = kFinalAccountType; service()->ConfigureHttpAuthPrefs(std::move(auth_params)); EXPECT_EQ(kFinalAccountType, auth_handler_factory->http_auth_preferences() ->AuthAndroidNegotiateAccountType()); } #endif // defined(OS_ANDROID) class NetworkServiceTestWithService : public testing::Test { public: NetworkServiceTestWithService() : task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO) {} ~NetworkServiceTestWithService() override {} void SetUp() override { test_server_.AddDefaultHandlers(base::FilePath(kServicesTestData)); ASSERT_TRUE(test_server_.Start()); service_ = NetworkService::CreateForTesting( test_connector_factory_.RegisterInstance(kNetworkServiceName)); test_connector_factory_.GetDefaultConnector()->BindInterface( kNetworkServiceName, &network_service_); } void CreateNetworkContext() { mojom::NetworkContextParamsPtr context_params = mojom::NetworkContextParams::New(); network_service_->CreateNetworkContext(mojo::MakeRequest(&network_context_), std::move(context_params)); } void LoadURL(const GURL& url, int options = mojom::kURLLoadOptionNone) { ResourceRequest request; request.url = url; request.method = "GET"; request.request_initiator = url::Origin(); StartLoadingURL(request, 0 /* process_id */, options); client_->RunUntilComplete(); } void StartLoadingURL(const ResourceRequest& request, uint32_t process_id, int options = mojom::kURLLoadOptionNone) { client_.reset(new TestURLLoaderClient()); mojom::URLLoaderFactoryPtr loader_factory; mojom::URLLoaderFactoryParamsPtr params = mojom::URLLoaderFactoryParams::New(); params->process_id = process_id; params->is_corb_enabled = false; network_context_->CreateURLLoaderFactory(mojo::MakeRequest(&loader_factory), std::move(params)); loader_factory->CreateLoaderAndStart( mojo::MakeRequest(&loader_), 1, 1, options, request, client_->CreateInterfacePtr(), net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS)); } void Shutdown() { service_.reset(); } net::EmbeddedTestServer* test_server() { return &test_server_; } TestURLLoaderClient* client() { return client_.get(); } mojom::URLLoader* loader() { return loader_.get(); } mojom::NetworkService* service() { return network_service_.get(); } mojom::NetworkContext* context() { return network_context_.get(); } protected: base::test::ScopedTaskEnvironment task_environment_; service_manager::TestConnectorFactory test_connector_factory_; std::unique_ptr<NetworkService> service_; net::EmbeddedTestServer test_server_; std::unique_ptr<TestURLLoaderClient> client_; mojom::NetworkServicePtr network_service_; mojom::NetworkContextPtr network_context_; mojom::URLLoaderPtr loader_; DISALLOW_COPY_AND_ASSIGN(NetworkServiceTestWithService); }; // Verifies that loading a URL through the network service's mojo interface // works. TEST_F(NetworkServiceTestWithService, Basic) { CreateNetworkContext(); LoadURL(test_server()->GetURL("/echo")); EXPECT_EQ(net::OK, client()->completion_status().error_code); } // Verifies that a passed net log file is successfully opened and sane data // written to it. TEST_F(NetworkServiceTestWithService, StartsNetLog) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath log_dir = temp_dir.GetPath(); base::FilePath log_path = log_dir.Append(FILE_PATH_LITERAL("test_log.json")); base::DictionaryValue dict; dict.SetString("amiatest", "iamatest"); base::File log_file(log_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); network_service_->StartNetLog(std::move(log_file), network::mojom::NetLogCaptureMode::DEFAULT, std::move(dict)); CreateNetworkContext(); LoadURL(test_server()->GetURL("/echo")); EXPECT_EQ(net::OK, client()->completion_status().error_code); // |log_file| is closed on destruction of the NetworkService. Shutdown(); // |log_file| is closed on another thread, so have to wait for that to happen. task_environment_.RunUntilIdle(); JSONFileValueDeserializer deserializer(log_path); std::unique_ptr<base::Value> log_dict = deserializer.Deserialize(nullptr, nullptr); ASSERT_TRUE(log_dict); ASSERT_EQ(log_dict->FindKey("constants")->FindKey("amiatest")->GetString(), "iamatest"); } // Verifies that raw headers are only reported if requested. TEST_F(NetworkServiceTestWithService, RawRequestHeadersAbsent) { CreateNetworkContext(); ResourceRequest request; request.url = test_server()->GetURL("/server-redirect?/echo"); request.method = "GET"; request.request_initiator = url::Origin(); StartLoadingURL(request, 0); client()->RunUntilRedirectReceived(); EXPECT_TRUE(client()->has_received_redirect()); EXPECT_TRUE(!client()->response_head().raw_request_response_info); loader()->FollowRedirect({}, {}, base::nullopt); client()->RunUntilComplete(); EXPECT_TRUE(!client()->response_head().raw_request_response_info); } TEST_F(NetworkServiceTestWithService, RawRequestHeadersPresent) { CreateNetworkContext(); ResourceRequest request; request.url = test_server()->GetURL("/server-redirect?/echo"); request.method = "GET"; request.report_raw_headers = true; request.request_initiator = url::Origin(); StartLoadingURL(request, 0); client()->RunUntilRedirectReceived(); EXPECT_TRUE(client()->has_received_redirect()); { scoped_refptr<HttpRawRequestResponseInfo> request_response_info = client()->response_head().raw_request_response_info; ASSERT_TRUE(request_response_info); EXPECT_EQ(301, request_response_info->http_status_code); EXPECT_EQ("Moved Permanently", request_response_info->http_status_text); EXPECT_TRUE(base::StartsWith(request_response_info->request_headers_text, "GET /server-redirect?/echo HTTP/1.1\r\n", base::CompareCase::SENSITIVE)); EXPECT_GE(request_response_info->request_headers.size(), 1lu); EXPECT_GE(request_response_info->response_headers.size(), 1lu); EXPECT_TRUE(base::StartsWith(request_response_info->response_headers_text, "HTTP/1.1 301 Moved Permanently\r", base::CompareCase::SENSITIVE)); } loader()->FollowRedirect({}, {}, base::nullopt); client()->RunUntilComplete(); { scoped_refptr<HttpRawRequestResponseInfo> request_response_info = client()->response_head().raw_request_response_info; EXPECT_EQ(200, request_response_info->http_status_code); EXPECT_EQ("OK", request_response_info->http_status_text); EXPECT_TRUE(base::StartsWith(request_response_info->request_headers_text, "GET /echo HTTP/1.1\r\n", base::CompareCase::SENSITIVE)); EXPECT_GE(request_response_info->request_headers.size(), 1lu); EXPECT_GE(request_response_info->response_headers.size(), 1lu); EXPECT_TRUE(base::StartsWith(request_response_info->response_headers_text, "HTTP/1.1 200 OK\r", base::CompareCase::SENSITIVE)); } } TEST_F(NetworkServiceTestWithService, RawRequestAccessControl) { const uint32_t process_id = 42; CreateNetworkContext(); ResourceRequest request; request.url = test_server()->GetURL("/nocache.html"); request.method = "GET"; request.report_raw_headers = true; request.request_initiator = url::Origin(); StartLoadingURL(request, process_id); client()->RunUntilComplete(); EXPECT_FALSE(client()->response_head().raw_request_response_info); service()->SetRawHeadersAccess( process_id, {url::Origin::CreateFromNormalizedTuple("http", "example.com", 80), url::Origin::Create(request.url)}); StartLoadingURL(request, process_id); client()->RunUntilComplete(); { scoped_refptr<HttpRawRequestResponseInfo> request_response_info = client()->response_head().raw_request_response_info; ASSERT_TRUE(request_response_info); EXPECT_EQ(200, request_response_info->http_status_code); EXPECT_EQ("OK", request_response_info->http_status_text); } service()->SetRawHeadersAccess(process_id, {}); StartLoadingURL(request, process_id); client()->RunUntilComplete(); EXPECT_FALSE(client()->response_head().raw_request_response_info.get()); service()->SetRawHeadersAccess( process_id, {url::Origin::CreateFromNormalizedTuple("http", "example.com", 80)}); StartLoadingURL(request, process_id); client()->RunUntilComplete(); EXPECT_FALSE(client()->response_head().raw_request_response_info.get()); } class NetworkServiceTestWithResolverMap : public NetworkServiceTestWithService { void SetUp() override { base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( network::switches::kHostResolverRules, "MAP *.test 127.0.0.1"); NetworkServiceTestWithService::SetUp(); } }; TEST_F(NetworkServiceTestWithResolverMap, RawRequestAccessControlWithRedirect) { CreateNetworkContext(); const uint32_t process_id = 42; // initial_url in a.test redirects to b_url (in b.test) that then redirects to // url_a in a.test. GURL url_a = test_server()->GetURL("a.test", "/echo"); GURL url_b = test_server()->GetURL("b.test", "/server-redirect?" + url_a.spec()); GURL initial_url = test_server()->GetURL("a.test", "/server-redirect?" + url_b.spec()); ResourceRequest request; request.url = initial_url; request.method = "GET"; request.report_raw_headers = true; request.request_initiator = url::Origin(); service()->SetRawHeadersAccess(process_id, {url::Origin::Create(url_a)}); StartLoadingURL(request, process_id); client()->RunUntilRedirectReceived(); // from a.test to b.test EXPECT_TRUE(client()->response_head().raw_request_response_info); loader()->FollowRedirect({}, {}, base::nullopt); client()->ClearHasReceivedRedirect(); client()->RunUntilRedirectReceived(); // from b.test to a.test EXPECT_FALSE(client()->response_head().raw_request_response_info); loader()->FollowRedirect({}, {}, base::nullopt); client()->RunUntilComplete(); // Done loading a.test EXPECT_TRUE(client()->response_head().raw_request_response_info.get()); service()->SetRawHeadersAccess(process_id, {url::Origin::Create(url_b)}); StartLoadingURL(request, process_id); client()->RunUntilRedirectReceived(); // from a.test to b.test EXPECT_FALSE(client()->response_head().raw_request_response_info); loader()->FollowRedirect({}, {}, base::nullopt); client()->ClearHasReceivedRedirect(); client()->RunUntilRedirectReceived(); // from b.test to a.test EXPECT_TRUE(client()->response_head().raw_request_response_info); loader()->FollowRedirect({}, {}, base::nullopt); client()->RunUntilComplete(); // Done loading a.test EXPECT_FALSE(client()->response_head().raw_request_response_info.get()); } TEST_F(NetworkServiceTestWithService, SetNetworkConditions) { const base::UnguessableToken profile_id = base::UnguessableToken::Create(); CreateNetworkContext(); mojom::NetworkConditionsPtr network_conditions = mojom::NetworkConditions::New(); network_conditions->offline = true; context()->SetNetworkConditions(profile_id, std::move(network_conditions)); ResourceRequest request; request.url = test_server()->GetURL("/nocache.html"); request.method = "GET"; StartLoadingURL(request, 0); client()->RunUntilComplete(); EXPECT_EQ(net::OK, client()->completion_status().error_code); request.throttling_profile_id = profile_id; StartLoadingURL(request, 0); client()->RunUntilComplete(); EXPECT_EQ(net::ERR_INTERNET_DISCONNECTED, client()->completion_status().error_code); network_conditions = mojom::NetworkConditions::New(); network_conditions->offline = false; context()->SetNetworkConditions(profile_id, std::move(network_conditions)); StartLoadingURL(request, 0); client()->RunUntilComplete(); EXPECT_EQ(net::OK, client()->completion_status().error_code); network_conditions = mojom::NetworkConditions::New(); network_conditions->offline = true; context()->SetNetworkConditions(profile_id, std::move(network_conditions)); request.throttling_profile_id = profile_id; StartLoadingURL(request, 0); client()->RunUntilComplete(); EXPECT_EQ(net::ERR_INTERNET_DISCONNECTED, client()->completion_status().error_code); context()->SetNetworkConditions(profile_id, nullptr); StartLoadingURL(request, 0); client()->RunUntilComplete(); EXPECT_EQ(net::OK, client()->completion_status().error_code); } // CRLSets are not supported on iOS and Android system verifiers. #if !defined(OS_IOS) && !defined(OS_ANDROID) // Verifies CRLSets take effect if configured on the service. TEST_F(NetworkServiceTestWithService, CRLSetIsApplied) { net::EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS); test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); test_server.AddDefaultHandlers(base::FilePath(kServicesTestData)); ASSERT_TRUE(test_server.Start()); CreateNetworkContext(); uint32_t options = mojom::kURLLoadOptionSendSSLInfoWithResponse | mojom::kURLLoadOptionSendSSLInfoForCertificateError; // Make sure the test server loads fine with no CRLSet. LoadURL(test_server.GetURL("/echo"), options); ASSERT_EQ(net::OK, client()->completion_status().error_code); // Send a CRLSet that blocks the leaf cert. std::string crl_set_bytes; EXPECT_TRUE(base::ReadFileToString( net::GetTestCertsDirectory().AppendASCII("crlset_by_leaf_spki.raw"), &crl_set_bytes)); service()->UpdateCRLSet(base::as_bytes(base::make_span(crl_set_bytes))); network_service_.FlushForTesting(); // Flush all connections in the context, to force a new connection. A new // verification should be attempted, due to the configuration having // changed, thus forcing the CRLSet to be checked. base::RunLoop run_loop; context()->CloseAllConnections(run_loop.QuitClosure()); run_loop.Run(); // Make sure the connection fails, due to the certificate being revoked. LoadURL(test_server.GetURL("/echo"), options); EXPECT_EQ(net::ERR_INSECURE_RESPONSE, client()->completion_status().error_code); ASSERT_TRUE(client()->completion_status().ssl_info.has_value()); EXPECT_TRUE(client()->completion_status().ssl_info->cert_status & net::CERT_STATUS_REVOKED); } // Verifies CRLSets configured before creating a new network context are // applied to that network context. TEST_F(NetworkServiceTestWithService, CRLSetIsPassedToNewContexts) { net::EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS); test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); test_server.AddDefaultHandlers(base::FilePath(kServicesTestData)); ASSERT_TRUE(test_server.Start()); // Send a CRLSet that blocks the leaf cert, even while no NetworkContexts // exist. std::string crl_set_bytes; EXPECT_TRUE(base::ReadFileToString( net::GetTestCertsDirectory().AppendASCII("crlset_by_leaf_spki.raw"), &crl_set_bytes)); service()->UpdateCRLSet(base::as_bytes(base::make_span(crl_set_bytes))); network_service_.FlushForTesting(); // Configure a new NetworkContext. CreateNetworkContext(); uint32_t options = mojom::kURLLoadOptionSendSSLInfoWithResponse | mojom::kURLLoadOptionSendSSLInfoForCertificateError; // Make sure the connection fails, due to the certificate being revoked. LoadURL(test_server.GetURL("/echo"), options); EXPECT_EQ(net::ERR_INSECURE_RESPONSE, client()->completion_status().error_code); ASSERT_TRUE(client()->completion_status().ssl_info.has_value()); EXPECT_TRUE(client()->completion_status().ssl_info->cert_status & net::CERT_STATUS_REVOKED); } // Verifies newer CRLSets (by sequence number) are applied. TEST_F(NetworkServiceTestWithService, CRLSetIsUpdatedIfNewer) { net::EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS); test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); test_server.AddDefaultHandlers(base::FilePath(kServicesTestData)); ASSERT_TRUE(test_server.Start()); // Send a CRLSet that only allows the root cert if it matches a known SPKI // hash (that matches the test server chain) std::string crl_set_bytes; ASSERT_TRUE(base::ReadFileToString( net::GetTestCertsDirectory().AppendASCII("crlset_by_root_subject.raw"), &crl_set_bytes)); service()->UpdateCRLSet(base::as_bytes(base::make_span(crl_set_bytes))); network_service_.FlushForTesting(); CreateNetworkContext(); uint32_t options = mojom::kURLLoadOptionSendSSLInfoWithResponse | mojom::kURLLoadOptionSendSSLInfoForCertificateError; // Make sure the connection loads, due to the root being whitelisted. LoadURL(test_server.GetURL("/echo"), options); ASSERT_EQ(net::OK, client()->completion_status().error_code); // Send a new CRLSet that removes trust in the root. ASSERT_TRUE(base::ReadFileToString(net::GetTestCertsDirectory().AppendASCII( "crlset_by_root_subject_no_spki.raw"), &crl_set_bytes)); service()->UpdateCRLSet(base::as_bytes(base::make_span(crl_set_bytes))); network_service_.FlushForTesting(); // Flush all connections in the context, to force a new connection. A new // verification should be attempted, due to the configuration having // changed, thus forcing the CRLSet to be checked. base::RunLoop run_loop; context()->CloseAllConnections(run_loop.QuitClosure()); run_loop.Run(); // Make sure the connection fails, due to the certificate being revoked. LoadURL(test_server.GetURL("/echo"), options); EXPECT_EQ(net::ERR_INSECURE_RESPONSE, client()->completion_status().error_code); ASSERT_TRUE(client()->completion_status().ssl_info.has_value()); EXPECT_TRUE(client()->completion_status().ssl_info->cert_status & net::CERT_STATUS_REVOKED); } // Verifies that attempting to send an older CRLSet (by sequence number) // does not apply to existing or new contexts. TEST_F(NetworkServiceTestWithService, CRLSetDoesNotDowngrade) { net::EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS); test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); test_server.AddDefaultHandlers(base::FilePath(kServicesTestData)); ASSERT_TRUE(test_server.Start()); // Send a CRLSet that blocks the root certificate by subject name. std::string crl_set_bytes; ASSERT_TRUE(base::ReadFileToString(net::GetTestCertsDirectory().AppendASCII( "crlset_by_root_subject_no_spki.raw"), &crl_set_bytes)); service()->UpdateCRLSet(base::as_bytes(base::make_span(crl_set_bytes))); network_service_.FlushForTesting(); CreateNetworkContext(); uint32_t options = mojom::kURLLoadOptionSendSSLInfoWithResponse | mojom::kURLLoadOptionSendSSLInfoForCertificateError; // Make sure the connection fails, due to the certificate being revoked. LoadURL(test_server.GetURL("/echo"), options); EXPECT_EQ(net::ERR_INSECURE_RESPONSE, client()->completion_status().error_code); ASSERT_TRUE(client()->completion_status().ssl_info.has_value()); EXPECT_TRUE(client()->completion_status().ssl_info->cert_status & net::CERT_STATUS_REVOKED); // Attempt to configure an older CRLSet that allowed trust in the root. ASSERT_TRUE(base::ReadFileToString( net::GetTestCertsDirectory().AppendASCII("crlset_by_root_subject.raw"), &crl_set_bytes)); service()->UpdateCRLSet(base::as_bytes(base::make_span(crl_set_bytes))); network_service_.FlushForTesting(); // Flush all connections in the context, to force a new connection. A new // verification should be attempted, due to the configuration having // changed, thus forcing the CRLSet to be checked. base::RunLoop run_loop; context()->CloseAllConnections(run_loop.QuitClosure()); run_loop.Run(); // Make sure the connection still fails, due to the newer CRLSet still // applying. LoadURL(test_server.GetURL("/echo"), options); EXPECT_EQ(net::ERR_INSECURE_RESPONSE, client()->completion_status().error_code); ASSERT_TRUE(client()->completion_status().ssl_info.has_value()); EXPECT_TRUE(client()->completion_status().ssl_info->cert_status & net::CERT_STATUS_REVOKED); // Create a new NetworkContext and ensure the latest CRLSet is still // applied. network_context_.reset(); CreateNetworkContext(); // The newer CRLSet that blocks the connection should still apply, even to // new NetworkContexts. LoadURL(test_server.GetURL("/echo"), options); EXPECT_EQ(net::ERR_INSECURE_RESPONSE, client()->completion_status().error_code); ASSERT_TRUE(client()->completion_status().ssl_info.has_value()); EXPECT_TRUE(client()->completion_status().ssl_info->cert_status & net::CERT_STATUS_REVOKED); } #endif // !defined(OS_IOS) && !defined(OS_ANDROID) // The SpawnedTestServer does not work on iOS. #if !defined(OS_IOS) // Test |primary_network_context|, which is required by AIA fetching, among // other things. TEST_F(NetworkServiceTestWithService, AIAFetching) { mojom::NetworkContextParamsPtr context_params = CreateContextParams(); context_params->primary_network_context = true; network_service_->CreateNetworkContext(mojo::MakeRequest(&network_context_), std::move(context_params)); net::SpawnedTestServer::SSLOptions ssl_options( net::SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE); net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath(kServicesTestData)); ASSERT_TRUE(test_server.Start()); LoadURL(test_server.GetURL("/echo"), mojom::kURLLoadOptionSendSSLInfoWithResponse); EXPECT_EQ(net::OK, client()->completion_status().error_code); EXPECT_EQ( 0u, client()->response_head().cert_status & net::CERT_STATUS_ALL_ERRORS); ASSERT_TRUE(client()->ssl_info()); ASSERT_TRUE(client()->ssl_info()->cert); EXPECT_EQ(2u, client()->ssl_info()->cert->intermediate_buffers().size()); ASSERT_TRUE(client()->ssl_info()->unverified_cert); EXPECT_EQ( 0u, client()->ssl_info()->unverified_cert->intermediate_buffers().size()); } #endif // !defined(OS_IOS) // Check that destroying a NetworkContext with |primary_network_context| set // destroys all other NetworkContexts. TEST_F(NetworkServiceTestWithService, DestroyingPrimaryNetworkContextDestroysOtherContexts) { mojom::NetworkContextParamsPtr context_params = CreateContextParams(); context_params->primary_network_context = true; mojom::NetworkContextPtr cert_validating_network_context; network_service_->CreateNetworkContext( mojo::MakeRequest(&cert_validating_network_context), std::move(context_params)); base::RunLoop run_loop; mojom::NetworkContextPtr network_context; network_service_->CreateNetworkContext(mojo::MakeRequest(&network_context), CreateContextParams()); network_context.set_connection_error_handler(run_loop.QuitClosure()); // Wait until the new NetworkContext has been created, so it's not created // after the primary NetworkContext is destroyed. network_service_.FlushForTesting(); // Destroying |cert_validating_network_context| should result in destroying // |network_context| as well. cert_validating_network_context.reset(); run_loop.Run(); EXPECT_TRUE(network_context.encountered_error()); } TEST_F(NetworkServiceTestWithService, GetDnsConfigChangeManager) { mojom::DnsConfigChangeManagerPtr ptr; ASSERT_FALSE(ptr.is_bound()); network_service_->GetDnsConfigChangeManager(mojo::MakeRequest(&ptr)); EXPECT_TRUE(ptr.is_bound()); } TEST_F(NetworkServiceTestWithService, GetNetworkList) { base::RunLoop run_loop; network_service_->GetNetworkList( net::INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES, base::BindLambdaForTesting( [&](const base::Optional<std::vector<net::NetworkInterface>>& list) { EXPECT_NE(base::nullopt, list); for (auto it = list->begin(); it != list->end(); ++it) { // Verify that names are not empty. EXPECT_FALSE(it->name.empty()); EXPECT_FALSE(it->friendly_name.empty()); // Verify that the address is correct. EXPECT_TRUE(it->address.IsValid()); EXPECT_FALSE(it->address.IsZero()); EXPECT_GT(it->prefix_length, 1u); EXPECT_LE(it->prefix_length, it->address.size() * 8); } run_loop.Quit(); })); run_loop.Run(); } class TestNetworkChangeManagerClient : public mojom::NetworkChangeManagerClient { public: explicit TestNetworkChangeManagerClient( mojom::NetworkService* network_service) : connection_type_(mojom::ConnectionType::CONNECTION_UNKNOWN), binding_(this) { mojom::NetworkChangeManagerPtr manager_ptr; mojom::NetworkChangeManagerRequest request(mojo::MakeRequest(&manager_ptr)); network_service->GetNetworkChangeManager(std::move(request)); mojom::NetworkChangeManagerClientPtr client_ptr; mojom::NetworkChangeManagerClientRequest client_request( mojo::MakeRequest(&client_ptr)); binding_.Bind(std::move(client_request)); manager_ptr->RequestNotifications(std::move(client_ptr)); } ~TestNetworkChangeManagerClient() override {} // NetworkChangeManagerClient implementation: void OnInitialConnectionType(mojom::ConnectionType type) override { if (type == connection_type_) run_loop_.Quit(); } void OnNetworkChanged(mojom::ConnectionType type) override { if (type == connection_type_) run_loop_.Quit(); } // Waits for the desired |connection_type| notification. void WaitForNotification(mojom::ConnectionType type) { connection_type_ = type; run_loop_.Run(); } void Flush() { binding_.FlushForTesting(); } private: base::RunLoop run_loop_; mojom::ConnectionType connection_type_; mojo::Binding<mojom::NetworkChangeManagerClient> binding_; DISALLOW_COPY_AND_ASSIGN(TestNetworkChangeManagerClient); }; class NetworkChangeTest : public testing::Test { public: NetworkChangeTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO), network_change_notifier_(net::NetworkChangeNotifier::CreateMock()), service_(NetworkService::CreateForTesting()) {} ~NetworkChangeTest() override {} NetworkService* service() const { return service_.get(); } private: base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier_; std::unique_ptr<NetworkService> service_; }; // mojom:NetworkChangeManager isn't supported on iOS. // See the same ifdef in CreateNetworkChangeNotifierIfNeeded. #if defined(OS_IOS) #define MAYBE_NetworkChangeManagerRequest DISABLED_NetworkChangeManagerRequest #else #define MAYBE_NetworkChangeManagerRequest NetworkChangeManagerRequest #endif TEST_F(NetworkChangeTest, MAYBE_NetworkChangeManagerRequest) { TestNetworkChangeManagerClient manager_client(service()); net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests( net::NetworkChangeNotifier::CONNECTION_3G); manager_client.WaitForNotification(mojom::ConnectionType::CONNECTION_3G); } class NetworkServiceNetworkChangeTest : public testing::Test { public: NetworkServiceNetworkChangeTest() : task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::IO), network_change_notifier_(net::NetworkChangeNotifier::CreateMock()), service_(NetworkService::CreateForTesting( test_connector_factory_.RegisterInstance(kNetworkServiceName))) { test_connector_factory_.GetDefaultConnector()->BindInterface( kNetworkServiceName, &network_service_); } ~NetworkServiceNetworkChangeTest() override {} mojom::NetworkService* service() { return network_service_.get(); } private: base::test::ScopedTaskEnvironment task_environment_; service_manager::TestConnectorFactory test_connector_factory_; std::unique_ptr<net::NetworkChangeNotifier> network_change_notifier_; std::unique_ptr<NetworkService> service_; mojom::NetworkServicePtr network_service_; DISALLOW_COPY_AND_ASSIGN(NetworkServiceNetworkChangeTest); }; TEST_F(NetworkServiceNetworkChangeTest, MAYBE_NetworkChangeManagerRequest) { TestNetworkChangeManagerClient manager_client(service()); // Wait for the NetworkChangeManagerClient registration to be processed within // the NetworkService impl before simulating a change. Flushing guarantees // end-to-end connection of the client interface. manager_client.Flush(); net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests( net::NetworkChangeNotifier::CONNECTION_3G); manager_client.WaitForNotification(mojom::ConnectionType::CONNECTION_3G); } class NetworkServiceNetworkDelegateTest : public NetworkServiceTest { public: NetworkServiceNetworkDelegateTest() { // |NetworkServiceNetworkDelegate::HandleClearSiteDataHeader| requires // Network Service. scoped_feature_list_.InitAndEnableFeature( network::features::kNetworkService); } ~NetworkServiceNetworkDelegateTest() override = default; void CreateNetworkContext() { mojom::NetworkContextParamsPtr context_params = mojom::NetworkContextParams::New(); service()->CreateNetworkContext(mojo::MakeRequest(&network_context_), std::move(context_params)); } void LoadURL(const GURL& url, int options = mojom::kURLLoadOptionNone) { ResourceRequest request; request.url = url; request.method = "GET"; request.request_initiator = url::Origin(); StartLoadingURL(request, 0 /* process_id */, options); client_->RunUntilComplete(); } void StartLoadingURL(const ResourceRequest& request, uint32_t process_id, int options = mojom::kURLLoadOptionNone) { client_.reset(new TestURLLoaderClient()); mojom::URLLoaderFactoryPtr loader_factory; mojom::URLLoaderFactoryParamsPtr params = mojom::URLLoaderFactoryParams::New(); params->process_id = process_id; params->is_corb_enabled = false; network_context_->CreateURLLoaderFactory(mojo::MakeRequest(&loader_factory), std::move(params)); loader_factory->CreateLoaderAndStart( mojo::MakeRequest(&loader_), 1, 1, options, request, client_->CreateInterfacePtr(), net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS)); } net::EmbeddedTestServer* https_server() { return https_server_.get(); } TestURLLoaderClient* client() { return client_.get(); } protected: void SetUp() override { // Set up HTTPS server. https_server_.reset(new net::EmbeddedTestServer( net::test_server::EmbeddedTestServer::TYPE_HTTPS)); https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK); https_server_->RegisterRequestHandler(base::BindRepeating( &NetworkServiceNetworkDelegateTest::HandleHTTPSRequest, base::Unretained(this))); ASSERT_TRUE(https_server_->Start()); } // Responds with the header "<header>" if we have "header"=<header> query // parameters in the url. std::unique_ptr<net::test_server::HttpResponse> HandleHTTPSRequest( const net::test_server::HttpRequest& request) { std::string header; if (net::GetValueForKeyInQuery(request.GetURL(), "header", &header)) { std::unique_ptr<net::test_server::RawHttpResponse> response( new net::test_server::RawHttpResponse("HTTP/1.1 200 OK\r\n", "")); // Newlines are encoded as '%0A' in URLs. const std::string newline_escape = "%0A"; std::size_t pos = header.find(newline_escape); while (pos != std::string::npos) { header.replace(pos, newline_escape.length(), "\r\n"); pos = header.find(newline_escape); } response->AddHeader(header); return response; } return nullptr; } std::unique_ptr<net::EmbeddedTestServer> https_server_; std::unique_ptr<TestURLLoaderClient> client_; mojom::NetworkContextPtr network_context_; mojom::URLLoaderPtr loader_; base::test::ScopedFeatureList scoped_feature_list_; DISALLOW_COPY_AND_ASSIGN(NetworkServiceNetworkDelegateTest); }; class ClearSiteDataNetworkServiceClient : public TestNetworkServiceClient { public: explicit ClearSiteDataNetworkServiceClient( mojom::NetworkServiceClientRequest request) : TestNetworkServiceClient(std::move(request)) {} ~ClearSiteDataNetworkServiceClient() override = default; // Needed these two cookie overrides to avoid NOTREACHED(). void OnCookiesRead(int process_id, int routing_id, const GURL& url, const GURL& first_party_url, const net::CookieList& cookie_list, bool blocked_by_policy) override {} void OnCookieChange(int process_id, int routing_id, const GURL& url, const GURL& first_party_url, const net::CanonicalCookie& cookie, bool blocked_by_policy) override {} void OnClearSiteData(int process_id, int routing_id, const GURL& url, const std::string& header_value, int load_flags, OnClearSiteDataCallback callback) override { ++on_clear_site_data_counter_; last_on_clear_site_data_header_value_ = header_value; std::move(callback).Run(); } int on_clear_site_data_counter() const { return on_clear_site_data_counter_; } const std::string& last_on_clear_site_data_header_value() const { return last_on_clear_site_data_header_value_; } void ClearOnClearSiteDataCounter() { on_clear_site_data_counter_ = 0; last_on_clear_site_data_header_value_.clear(); } private: int on_clear_site_data_counter_ = 0; std::string last_on_clear_site_data_header_value_; }; // Check that |NetworkServiceNetworkDelegate| handles Clear-Site-Data header // w/ and w/o |NetworkServiceCient|. TEST_F(NetworkServiceNetworkDelegateTest, ClearSiteDataNetworkServiceCient) { const char kClearCookiesHeader[] = "Clear-Site-Data: \"cookies\""; CreateNetworkContext(); // Null |NetworkServiceCient|. The request should complete without being // deferred. EXPECT_EQ(nullptr, service()->client()); GURL url = https_server()->GetURL("/foo"); url = AddQuery(url, "header", kClearCookiesHeader); LoadURL(url); EXPECT_EQ(net::OK, client()->completion_status().error_code); // With |NetworkServiceCient|. The request should go through // |ClearSiteDataNetworkServiceClient| and complete. mojom::NetworkServiceClientPtr client_ptr; auto client_impl = std::make_unique<ClearSiteDataNetworkServiceClient>( mojo::MakeRequest(&client_ptr)); service()->SetClient(std::move(client_ptr), network::mojom::NetworkServiceParams::New()); url = https_server()->GetURL("/bar"); url = AddQuery(url, "header", kClearCookiesHeader); EXPECT_EQ(0, client_impl->on_clear_site_data_counter()); LoadURL(url); EXPECT_EQ(net::OK, client()->completion_status().error_code); EXPECT_EQ(1, client_impl->on_clear_site_data_counter()); } // Check that headers are handled and passed to the client correctly. TEST_F(NetworkServiceNetworkDelegateTest, HandleClearSiteDataHeaders) { const char kClearCookiesHeaderValue[] = "\"cookies\""; const char kClearCookiesHeader[] = "Clear-Site-Data: \"cookies\""; CreateNetworkContext(); mojom::NetworkServiceClientPtr client_ptr; auto client_impl = std::make_unique<ClearSiteDataNetworkServiceClient>( mojo::MakeRequest(&client_ptr)); service()->SetClient(std::move(client_ptr), network::mojom::NetworkServiceParams::New()); // |passed_header_value| are only checked if |should_call_client| is true. const struct TestCase { std::string response_headers; bool should_call_client; std::string passed_header_value; } kTestCases[] = { // The throttle does not defer requests if there are no interesting // response headers. {"", false, ""}, {"Set-Cookie: abc=123;", false, ""}, {"Content-Type: image/png;", false, ""}, // Both malformed and valid Clear-Site-Data headers will defer requests // and be passed to the client. It's client's duty to detect malformed // headers. {"Clear-Site-Data: cookies", true, "cookies"}, {"Clear-Site-Data: \"unknown type\"", true, "\"unknown type\""}, {"Clear-Site-Data: \"cookies\", \"unknown type\"", true, "\"cookies\", \"unknown type\""}, {kClearCookiesHeader, true, kClearCookiesHeaderValue}, {base::StringPrintf("Content-Type: image/png;\n%s", kClearCookiesHeader), true, kClearCookiesHeaderValue}, {base::StringPrintf("%s\nContent-Type: image/png;", kClearCookiesHeader), true, kClearCookiesHeaderValue}, // Multiple instances of the header will be parsed correctly. {base::StringPrintf("%s\n%s", kClearCookiesHeader, kClearCookiesHeader), true, "\"cookies\", \"cookies\""}, }; for (const TestCase& test_case : kTestCases) { SCOPED_TRACE( base::StringPrintf("Headers:\n%s", test_case.response_headers.c_str())); GURL url = https_server()->GetURL("/foo"); url = AddQuery(url, "header", test_case.response_headers); EXPECT_EQ(0, client_impl->on_clear_site_data_counter()); LoadURL(url); EXPECT_EQ(net::OK, client()->completion_status().error_code); if (test_case.should_call_client) { EXPECT_EQ(1, client_impl->on_clear_site_data_counter()); EXPECT_EQ(test_case.passed_header_value, client_impl->last_on_clear_site_data_header_value()); } else { EXPECT_EQ(0, client_impl->on_clear_site_data_counter()); } client_impl->ClearOnClearSiteDataCounter(); } } } // namespace } // namespace network
[ "279687673@qq.com" ]
279687673@qq.com
1337c1284ba40d3b357c2b56ac409f342df67bc3
afeeb3ebc3b915a5df9d95823248e63cc3c608cc
/Object-Oriented/access_specifiers.cpp
baab46265644587216b0553c3205ace52febef07
[]
no_license
diegoinacio/cpp-data-structures-and-algorithms
a045fa0631bf5e5385cee1c0250d7a5d8180c0d9
e53703ce45bc7d69864070cc9564e09ee576068b
refs/heads/master
2020-12-05T15:41:44.765346
2020-01-08T23:47:51
2020-01-08T23:47:51
232,158,067
0
0
null
null
null
null
UTF-8
C++
false
false
1,126
cpp
#include <iostream> using namespace std; class ClassA { private: float privateAttrib; // Could be accessed from here only protected: float protectedAttrib; // Could be accessed from here and derived classes public: float publicAttrib; // Could be accessed from anywhere void setPrivateAttrib(float value) { privateAttrib = value; } float getPrivateAttrib() { return privateAttrib; } }; class ClassB : public ClassA { public: void setProtectedAttrib(float value) { protectedAttrib = value; } float getProtectedAttrib() { return protectedAttrib; } }; int main() { // Init object ClassB cb; // Sets cb.setPrivateAttrib(10); cb.setProtectedAttrib(20); cb.publicAttrib = 30; // Output cout << "Object private attribute : " << cb.getPrivateAttrib() << endl; cout << "Object protected attribute : " << cb.getProtectedAttrib() << endl; cout << "Object public attribute : " << cb.publicAttrib << endl; return 0; }
[ "diegodci@gmail.com" ]
diegodci@gmail.com
fe8bc678f82a9ece539317487781f17b962a625c
e1ccb4eb3e61c51d7750966deac7e09e50925018
/src/PrintDebug.h
b65f50e9ffd2cfd5e63f57c805081fdbafd2cb1c
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
Perf-Org-5KRepos/AccessorFramework
6eb1bc3e2d831f4fae6816726c4264baf99b7b8b
62db90576433aee2f243446ec1fedb74d29a2b6d
refs/heads/master
2022-04-08T14:41:38.059303
2020-02-25T22:21:51
2020-02-25T22:21:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
647
h
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #ifndef PRINT_DEBUG_H #define PRINT_DEBUG_H #ifdef NDEBUG #define PRINT_DEBUG(format, ...) #define PRINT_VERBOSE(format, ...) #else #include <stdio.h> #include <string> #include <mutex> static std::mutex g_stderr_mutex; #define PRINT_DEBUG(format, ...) { std::lock_guard<std::mutex> guard(g_stderr_mutex); fprintf(stderr, format, ##__VA_ARGS__); fprintf(stderr, "\n"); } #ifdef VERBOSE #define PRINT_VERBOSE PRINT_DEBUG #else #ifdef PRINT_VERBOSE #undef PRINT_VERBOSE #endif #define PRINT_VERBOSE(format, ...) #endif // VERBOSE #endif // NDEBUG #endif // PRINT_DEBUG_H
[ "brhick@microsoft.com" ]
brhick@microsoft.com
982c147bd29e5f6601d07dabedbd77f41b342a03
151a46e4bb5c589987eaa265063d062c6d3a2c16
/pbrt/me/shape_me.cpp
3a916618195c3af42935822454393513579d189d
[]
no_license
sq7636785/MINI_PBRT
ce488a1c53696cc85239a676559305eb190f9bd8
26217606254bb7bb045bc05f6c17eae8c1dd3ea3
refs/heads/master
2021-10-23T18:44:46.299951
2019-03-19T08:09:07
2019-03-19T08:09:07
159,270,441
3
0
null
null
null
null
UTF-8
C++
false
false
1,172
cpp
#include "shape.h" #include "stats.h" namespace pbrt { Interaction Shape::Sample(const Interaction &ref, const Point2f &u, Float *pdf) const { Interaction intr = Sample(u, pdf); Vector3f wi = intr.p - ref.p; if (wi.LengthSquared() == 0) *pdf = 0; else { wi = Normalize(wi); // Convert from area measure, as returned by the Sample() call // above, to solid angle measure. *pdf *= DistanceSquared(ref.p, intr.p) / AbsDot(intr.n, -wi); if (std::isinf(*pdf)) *pdf = 0.f; } return intr; } Float Shape::Pdf(const Interaction &ref, const Vector3f &wi) const { // Intersect sample ray with area light geometry Ray ray = ref.SpawnRay(wi); Float tHit; SurfaceInteraction isectLight; // Ignore any alpha textures used for trimming the shape when performing // this intersection. Hack for the "San Miguel" scene, where this is used // to make an invisible area light. if (!Intersect(ray, &tHit, &isectLight, false)) return 0; // Convert light sample weight to solid angle measure Float pdf = DistanceSquared(ref.p, isectLight.p) / (AbsDot(isectLight.n, -wi) * Area()); if (std::isinf(pdf)) pdf = 0.f; return pdf; } }
[ "799671203@qq.com" ]
799671203@qq.com
c44599a91a630dc673c58f0b6423b73ab3227f61
a68198c45c14f337d8d775d9038a419f4a597765
/enc_temp_folder/26fac6128d93472dd28594603cd60e4/node.h
afb4c437244b6d52b3057cd57d9f37a4851909a6
[]
no_license
DevPrestigious/W04-Linked-List
c9f640be2646e68733db13178ea3f6eb9aafe0dc
51664870f1fd5e72da018121568dbc4b8c9f7029
refs/heads/main
2023-08-20T22:48:35.693641
2021-10-11T23:54:19
2021-10-11T23:54:19
413,619,609
0
0
null
null
null
null
UTF-8
C++
false
false
10,863
h
/*********************************************************************** * Header: * NODE * Summary: * One node in a linked list (and the functions to support them). * __ __ _______ __ * / | / | | _____| _ / / * `| | `| | | |____ (_)/ / * | | | | '_.____''. / / _ * _| |_ _| |_ | \____) | / / (_) * |_____| |_____| \______.' /_/ * * This will contain the class definition of: * Node : A class representing a Node * Additionally, it will contain a few functions working on Node * Author * Stephen Costigan, Alexander Dohms, Jonathan Colwell ************************************************************************/ #pragma once #include <cassert> // for ASSERT #include <iostream> // for NULL /************************************************* * NODE * the node class. Since we do not validate any * of the setters, there is no point in making them * private. This is the case because only the * List class can make validation decisions *************************************************/ template <class T> class Node { public: // // Construct // Node() // DEFAULT -- Alex { /*Node.default - constructor() data <- T() pNext <- NULL pPrev <- NULL*/ data = T(); pNext = pPrev = NULL; // added by steve } Node(const T& data) // COPY -- Jon { // COPY VALUE CONSTRUCTOR /*Node.copy-constructor(t) data <- t pNext <- NULL pPrev <- NULL*/ this->data = std::move(data); pNext = pPrev = NULL; } Node(T&& data) // MOVE -- Steve { this->data = std::move(data); } // // Member variables // T data; // user data Node <T> * pNext; // pointer to next node Node <T> * pPrev; // pointer to previous node }; /*********************************************** * COPY * Copy the list from the pSource and return * the new list * INPUT : the list to be copied * OUTPUT : return the new list * COST : O(n) **********************************************/ template <class T> inline Node <T> * copy(const Node <T> * pSource) // --Alex { // COPY /*copy(pSource) 1. pDestination <- new Node(pSource.data) 2. pSrc <- pSource 3. pDes <- pDestination 4. FOR pSrc <- pSrc.pNext … end of the list 5. pDes <- insert(pSrc.data, pDes, true) 6. RETURN pDestination*/ /*if (pSource == NULL) return nullptr; Node<T>* pDestination = new Node<T>(pSource->data); Node<T>* pDes = pDestination; for (auto p = pSource->pNext; p;p->pNext) { pDes = insert(pDes, p->data, true); return pDestination; }*/ Node<T>* pDestination = new Node<T>(pSource->data); return pDestination; //if (pSource == NULL) // return NULL; //Node<T>* pDestination = new Node<T>(pSource->data); //// This loop accomplishes nothing... //for (auto pSrc = pSource->pNext; pSrc != nullptr; pSrc = pSrc->pNext) //{ // pDestination = insert(pDestination, pSource->data, true); //} //return pDestination; } /*********************************************** * Assign * Copy the values from pSource into pDestination * reusing the nodes already created in pDestination if possible. * INPUT : the list to be copied * OUTPUT : return the new list * COST : O(n) **********************************************/ template <class T> inline void assign(Node <T>*& pDestination, const Node <T>* pSource) // -- Jon { // ASSIGN NEEDS TO BE DONE IN A THREE STEP PROCESS!!!!!!!!!!!!!!// /*pSrc <- pSource pDes <- pDestination WHILE pSrc ≠ NULL AND pDest ≠ NULL pDes.data <- pSrc.data pDes <- pDes.pNext pSrc <- pSrc.pNext*/ //Node <T>* pSrc = pSource; //Node <T>* pDes = pDestination; //for (Node <T>* pSrc = pSource->pNext; pSrc != nullptr; pSrc = pSrc->pNext) //{ // pDes->data = pSrc->data; // pDes = pDes->pNext; // //pSrc = pSrc->pNext; // /*IF pSrc ≠ NULL // pDes <- pDesPrevious // WHILE pSrc ≠ NULL // pDes <- insert(pDes, pSrc.data, TRUE) // IF pDestination = NULL // pDestination <- pDes*/ // if (pSrc != NULL) { // } // // /*IF pSrc ≠ NULL // setToNull <- FALSE // IF pDes.pRev != NULL // pDEs.pPrev.pNext <- NULL // ELSE // setToNull <- TRUE // freeData(pDes) // IF setToNull // pDestination <- NULL*/ // if (pSrc != NULL) // { // /*setToNull = false;*/ // if (pDes->pPrev != NULL) // { // pDes->pPrev->pNext = NULL; // } // else // { // /*setToNull = true;*/ // clear(pDes); // } // /*if (setToNull) // pDestination = NULL;*/ // } //} } /*********************************************** * SWAP * Swap the list from LHS to RHS * COST : O(1) **********************************************/ template <class T> inline void swap(Node <T>* &pLHS, Node <T>* &pRHS) // -- Steve { // Not sure if this is even called upon, but it produces no errors or testnodes Node <T>* test = std::move(pLHS); pLHS = std::move(pRHS); pRHS = std::move(test); } /*********************************************** * REMOVE * Remove the node pSource in the linked list * INPUT : the node to be removed * OUTPUT : the pointer to the parent node * COST : O(1) **********************************************/ template <class T> inline Node <T> * remove(const Node <T> * pRemove) // -- Alex (Stolen by Steve) { /*remove(pRemove) IF NULL = pRemove RETURN IF pRemove.pPrev pRemove.pPrev.pNext <- pRemove.pNext IF pRemove.pNext pRemove.pNext.pPrev <- pRemove.pPrev IF pRemove.pPrev pReturn <- pRemove.pPrev; ELSE pReturn <- pRemove.pNext DELETE pRemove RETURN pReturn*/ Node <T>* pReturn = NULL; if (pRemove == NULL) return pReturn; if (pRemove->pPrev) pRemove->pPrev->pNext = pRemove->pNext; if (pRemove->pNext) pRemove->pNext->pPrev = pRemove->pPrev; pReturn = pRemove->pPrev ? pRemove->pPrev : pRemove->pNext; delete pRemove; return pReturn; } /********************************************** * INSERT * Insert a new node the the value in "t" into a linked * list immediately before the current position. * INPUT : t - the value to be used for the new node * pCurrent - a pointer to the node before which * we will be inserting the new node * after - whether we will be inserting after * OUTPUT : return the newly inserted item * COST : O(1) **********************************************/ template <class T> // -- Jon -- (Added to by Steve) inline Node <T> * insert(Node <T> * pCurrent, const T & t, bool after = false) { /*insert(t, pCurrent, after) 1. pNew <- NEW Node(t) 2. IF pCurrent != NULL and after = false 3. pNew.pNext <- pCurrent 4. pNew.pPrev <- pCurrent.pPrev 5. pCurrent.pPrev <- pNew 6. IF pNew.pPrev 7. pNew.pPrev.pNext <- pNew 8. IF pCurrent != NULL and after = true … something similar … 9. RETURN pNew*/ // THIS LOOKS RIGHT, BUT DOESN'T CHANGE %. FEEL FREE TO EDIT // 1. pNew < -NEW Node(t) Node <T>* pNew = new Node <T>(t); // 2. IF pCurrent != NULL and after = false if (pCurrent != NULL && !after) { // 4. pNew.pPrev <- pCurrent.pPrev pNew->pPrev = pCurrent->pPrev; // 3. pNew.pNext <- pCurrent pNew->pNext = pCurrent; // 5. pCurrent.pPrev <- pNew pCurrent->pPrev = pNew; // 6. IF pNew.pPrev if (pNew->pPrev) // 7. pNew.pPrev.pNext <- pNew pNew->pPrev->pNext = pNew; } // 8. IF pCurrent != NULL and after = true else if (pCurrent != NULL && after) { // … something similar … pNew->pNext = pCurrent->pNext; pNew->pPrev = pCurrent; pCurrent->pNext = pNew; if (pNew->pNext) pNew->pNext->pPrev = pNew; } // 9. RETURN pNew*/ return pNew; } /****************************************************** * FIND * Find a given node in an unsorted linked list. Return * a pointer to the node if it is found, NULL otherwise. * INPUT : a pointer to the head of the linked list * the value to be found * OUTPUT : a pointer to the node if it is found * COST : O(n) ********************************************************/ template <class T> inline size_t size(const Node <T> * pHead) // -- Steve { //size(pHead) // IF pHead = NULL //RETURN 0 // ELSE //RETURN 1 + size(pHead.pNext) if (pHead == nullptr) { return 0; } return size(pHead->pNext) + 1; } /*********************************************** * DISPLAY * Display all the items in the linked list from here on back * INPUT : the output stream * pointer to the linked list * OUTPUT : the data from the linked list on the screen * COST : O(n) **********************************************/ template <class T> inline std::ostream & operator << (std::ostream & out, const Node <T> * pHead) // -- Alex (Stolen by steve) { // I don't think this contributes to our % for (const Node <T>* p = pHead; p; p = p->pNext) { if (p->pNext != nullptr) { out << p->data << ", "; // comma separation in case there are multiple } else { out << p->data; // if one value, just return 1 } } return out; } /***************************************************** * FREE DATA * Free all the data currently in the linked list * INPUT : pointer to the head of the linked list * OUTPUT : pHead set to NULL * COST : O(n) ****************************************************/ template <class T> inline void clear(Node <T> * & pHead) // -- Steve { /*clear(pHead) WHILE pHead != NULL pDelete <- pHead pHead <- pHead.pNext DELETE pDelete*/ Node <T>* pDelete = pHead; // redundant for first loop, but oh well while (pHead != nullptr) { pDelete = pHead; pHead = pHead->pNext; delete pDelete; } delete pHead; }
[ "stephenjcostigan@hotmail.com" ]
stephenjcostigan@hotmail.com
cb54edca98b0af5849212a02e5139e228fce332e
b1c70bddccf38ebfb719b13d5c7b76e018d28044
/long_incr_subseq/main.cpp
01076721fbc0f5f58a791fa2065a34bb49edd326
[]
no_license
rdelgador/ADA
6d386093ca3014909e658d501d3343cfec6eabd8
31ce7f85a80b6c8472604304146720ef48990493
refs/heads/master
2021-01-21T04:50:44.867005
2016-06-17T04:56:26
2016-06-17T04:56:26
54,079,502
0
0
null
null
null
null
UTF-8
C++
false
false
1,124
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; void subsec(int X[], int tam) { int P[tam]; int M[tam]; int L = 1; int j; M[0] = 0; for(int i=1;i<tam;++i) { int lo = 0; int hi = L; if(X[M[hi-1]]<X[i]) j = hi; else { while(hi-lo > 1) { int mid = (lo+hi)/2; if(X[M[mid-1]]<X[i]) lo = mid; else hi = mid; } j = lo; } P[i] = M[j-1]; if(j==L || X[i]<X[M[j]]) { M[j] = i; L = max(L,j+1); } } vector<int> result; int pos = M[L-1]; for(int i=L;i>0;--i) { result.push_back(X[pos]); pos = P[pos]; } reverse(result.begin(),result.end()); for(int i=0;i<result.size();++i) { cout<<result[i]<<" "; } } int main() { int X[] = {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}; subsec(X,16); }
[ "ricardo.delgado@ucsp.edu.pe" ]
ricardo.delgado@ucsp.edu.pe
eed3d274fc2f2045b77bcc77edfe4670d907c93c
05f57ca2664b6f69024c6df9c861b24904aa1b90
/src/astra_ros_node/main.cpp
5c4c292093dfc6cf8e3201e74af4c334f3135643
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
semio-ai/astra_ros
2b3abdd171d102815db1185e50aa38c30ea9f4cd
2dfe80cf68cf4dcaa191d2387b0e97b76144acfa
refs/heads/master
2023-08-30T08:31:01.216173
2021-11-19T09:30:16
2021-11-19T09:30:16
325,932,064
1
0
null
null
null
null
UTF-8
C++
false
false
1,990
cpp
#include "astra_ros/RosDevice.hpp" #include "astra_ros/Exception.hpp" #include <ros/ros.h> #include <string> #include <unistd.h> using namespace std::string_literals; using namespace astra_ros; int main(int argc, char *argv[]) { ros::init(argc, argv, "astra_ros_node"); ros::NodeHandle nh; ros::NodeHandle pnh("~"); // Get all parameter keys from the parameter server (I didn't see a way to only get a namespace) std::vector<std::string> param_names; if (!pnh.getParamNames(param_names)) { ROS_ERROR("NodeHandle::getParamNames() failed. Aborting."); return EXIT_FAILURE; } // Extract the device names from the parameter key list std::set<std::string> devices; const std::string prefix = pnh.getNamespace() + "/" + DEVICE_NAMESPACE; for (const auto &param : param_names) { if (param.find(prefix) != 0) continue; std::string::size_type next_slash = param.find("/", prefix.size() + 1); if (next_slash == std::string::npos) next_slash = param.size(); const std::string device = param.substr(prefix.size() + 1, next_slash - prefix.size() - 1); devices.insert(device); } // Construct the ROS representations of the devices std::vector<RosDevice> ros_devices; for (const auto &device : devices) { ros_devices.emplace_back(device, nh, pnh); } // Finally, start streaming ros::Rate rate(35.0); while (ros::ok()) { for (auto &ros_device : ros_devices) { try { ros_device.update(); } catch (const Exception &exception) { ROS_ERROR_STREAM("Failed to update device \"" << ros_device.getName() << "\": " << exception.what()); continue; } catch(const std::exception &exception) { ROS_FATAL_STREAM("Unknown exception occurred while updating device \"" << ros_device.getName() << "\". Aborting: " << exception.what()); return EXIT_FAILURE; } } ros::spinOnce(); rate.sleep(); } return EXIT_SUCCESS; }
[ "bmcdorman@gmail.com" ]
bmcdorman@gmail.com
3d908c81e160fe8c44149f991989f65ffe3be3c9
fe58cc4cadf6b2f5381b09d345f16872adb28bba
/mrbgems/mruby-sprintf/src/sprintf.cpp
68198a86400e5917fce6c3dee8eadca725c3a355
[ "MIT" ]
permissive
nemerle/red_tint
659d8b51ef73df62a204ee06965a6e29ac4308a9
685af64ddc8915bf64e508a8d2e27cc097fb6d9c
refs/heads/master
2020-06-03T19:11:43.146124
2014-03-28T08:45:41
2014-03-28T08:45:41
9,427,016
1
1
null
null
null
null
UTF-8
C++
false
false
38,203
cpp
/* ** sprintf.c - Kernel.#sprintf ** ** See Copyright Notice in mruby.h */ #include "mruby.h" #include <limits.h> #include <stdio.h> #include <string.h> #include "mruby/string.h" #include "mruby/hash.h" #include "mruby/numeric.h" #include <math.h> #include <ctype.h> #ifdef _MSC_VER #include <float.h> #endif #define BIT_DIGITS(N) (((N)*146)/485 + 1) /* log2(10) =~ 146/485 */ #define BITSPERDIG (sizeof(mrb_int)*CHAR_BIT) #define EXTENDSIGN(n, l) (((~0 << (n)) >> (((n)*(l)) % BITSPERDIG)) & ~(~0 << (n))) mrb_value mrb_str_format(mrb_state *mrb, int argc, const mrb_value *argv, mrb_value fmt); static void fmt_setup(char*,size_t,int,int,mrb_int,mrb_int); static char* remove_sign_bits(char *str, int base) { char *t; t = str; if (base == 16) { while (*t == 'f') { t++; } } else if (base == 8) { *t |= EXTENDSIGN(3, strlen(t)); while (*t == '7') { t++; } } else if (base == 2) { while (*t == '1') { t++; } } return t; } static char sign_bits(int base, const char *p) { char c; switch (base) { case 16: if (*p == 'X') c = 'F'; else c = 'f'; break; case 8: c = '7'; break; case 2: c = '1'; break; default: c = '.'; break; } return c; } static RString * mrb_fix2binstr(mrb_state *mrb, mrb_value x, int base) { char buf[64], *b = buf + sizeof buf; mrb_int num = mrb_fixnum(x); unsigned long val = (unsigned long)num; char d; if (base != 2) { mrb->mrb_raisef(E_ARGUMENT_ERROR, "invalid radix %S", mrb_fixnum_value(base)); } if (val >= (1 << 10)) val &= 0x3ff; if (val == 0) { return RString::create(mrb, "0", 1); } *--b = '\0'; do { *--b = mrb_digitmap[(int)(val % base)]; } while (val /= base); if (num < 0) { b = remove_sign_bits(b, base); switch (base) { case 16: d = 'f'; break; case 8: d = '7'; break; case 2: d = '1'; break; default: d = 0; break; } if (d && *b != d) { *--b = d; } } return mrb_str_new_cstr(mrb, b); } #define FNONE 0 #define FSHARP 1 #define FMINUS 2 #define FPLUS 4 #define FZERO 8 #define FSPACE 16 #define FWIDTH 32 #define FPREC 64 #define FPREC0 128 #define CHECK(l) do {\ /* int cr = ENC_CODERANGE(result);*/\ while (blen + (l) >= bsiz) {\ bsiz*=2;\ }\ res_ptr->resize(bsiz);\ /* ENC_CODERANGE_SET(result, cr);*/\ buf = res_ptr->m_ptr;\ } while (0) #define PUSH(s, l) do { \ CHECK(l);\ memcpy(&buf[blen], s, l);\ blen += (l);\ } while (0) #define FILL(c, l) do { \ CHECK(l);\ memset(&buf[blen], c, l);\ blen += (l);\ } while (0) #define GETARG() (!nextvalue.is_undef() ? nextvalue : \ posarg == -1 ? \ (mrb->mrb_raisef(E_ARGUMENT_ERROR, "unnumbered(%S) mixed with numbered", mrb_fixnum_value(nextarg)), mrb_value::undef()) : \ posarg == -2 ? \ (mrb->mrb_raisef(E_ARGUMENT_ERROR, "unnumbered(%S) mixed with named", mrb_fixnum_value(nextarg)), mrb_value::undef()) : \ (posarg = nextarg++, GETNTHARG(posarg))) #define GETPOSARG(n) (posarg > 0 ? \ (mrb->mrb_raisef(E_ARGUMENT_ERROR, "numbered(%S) after unnumbered(%S)", mrb_fixnum_value(n), mrb_fixnum_value(posarg)), mrb_value::undef()) : \ posarg == -2 ? \ (mrb->mrb_raisef(E_ARGUMENT_ERROR, "numbered(%S) after named", mrb_fixnum_value(n)), mrb_value::undef()) : \ ((n < 1) ? \ (mrb->mrb_raisef(E_ARGUMENT_ERROR, "invalid index - %S$", mrb_fixnum_value(n)), mrb_value::undef()) : \ (posarg = -1, GETNTHARG(n)))) #define GETNTHARG(nth) \ ((nth >= argc) ? (mrb->mrb_raise(E_ARGUMENT_ERROR, "too few arguments"), mrb_value::undef()) : argv[nth]) #define GETNAMEARG(id, name, len) ( \ posarg > 0 ? \ (mrb->mrb_raisef(E_ARGUMENT_ERROR, "named%S after unnumbered(%S)", mrb_str_new(mrb, (name), (len)), mrb_fixnum_value(posarg)), mrb_value::undef()) : \ posarg == -1 ? \ (mrb->mrb_raisef(E_ARGUMENT_ERROR, "named%S after numbered", mrb_str_new(mrb, (name), (len))), mrb_value::undef()) : \ (posarg = -2, get_hash(mrb, &hash, argc, argv).ptr<RHash>()->fetch(id, mrb_value::undef()))) #define GETNUM(n, val) \ for (; p < end && ISDIGIT(*p); p++) {\ int next_n = 10 * n + (*p - '0'); \ if (next_n / 10 != n) {\ mrb->mrb_raise(E_ARGUMENT_ERROR, #val " too big"); \ } \ n = next_n; \ } \ if (p >= end) { \ mrb->mrb_raise(E_ARGUMENT_ERROR, "malformed format string - %*[0-9]"); \ } #define GETASTER(num) do { \ t = p++; \ n = 0; \ GETNUM(n, val); \ if (*p == '$') { \ tmp = GETPOSARG(n); \ } \ else { \ tmp = GETARG(); \ p = t; \ } \ num = mrb_fixnum(tmp); \ } while (0) static mrb_value get_hash(mrb_state *mrb, mrb_value *hash, int argc, const mrb_value *argv) { mrb_value tmp; if (!hash->is_undef()) return *hash; if (argc != 2) { mrb->mrb_raise(E_ARGUMENT_ERROR, "one hash required"); } tmp = mrb_check_convert_type(mrb, argv[1], MRB_TT_HASH, "Hash", "to_hash"); if (tmp.is_nil()) { mrb->mrb_raise(E_ARGUMENT_ERROR, "one hash required"); } return (*hash = tmp); } /* * call-seq: * format(format_string [, arguments...] ) -> string * sprintf(format_string [, arguments...] ) -> string * * Returns the string resulting from applying <i>format_string</i> to * any additional arguments. Within the format string, any characters * other than format sequences are copied to the result. * * The syntax of a format sequence is follows. * * %[flags][width][.precision]type * * A format * sequence consists of a percent sign, followed by optional flags, * width, and precision indicators, then terminated with a field type * character. The field type controls how the corresponding * <code>sprintf</code> argument is to be interpreted, while the flags * modify that interpretation. * * The field type characters are: * * Field | Integer Format * ------+-------------------------------------------------------------- * b | Convert argument as a binary number. * | Negative numbers will be displayed as a two's complement * | prefixed with `..1'. * B | Equivalent to `b', but uses an uppercase 0B for prefix * | in the alternative format by #. * d | Convert argument as a decimal number. * i | Identical to `d'. * o | Convert argument as an octal number. * | Negative numbers will be displayed as a two's complement * | prefixed with `..7'. * u | Identical to `d'. * x | Convert argument as a hexadecimal number. * | Negative numbers will be displayed as a two's complement * | prefixed with `..f' (representing an infinite string of * | leading 'ff's). * X | Equivalent to `x', but uses uppercase letters. * * Field | Float Format * ------+-------------------------------------------------------------- * e | Convert floating point argument into exponential notation * | with one digit before the decimal point as [-]d.dddddde[+-]dd. * | The precision specifies the number of digits after the decimal * | point (defaulting to six). * E | Equivalent to `e', but uses an uppercase E to indicate * | the exponent. * f | Convert floating point argument as [-]ddd.dddddd, * | where the precision specifies the number of digits after * | the decimal point. * g | Convert a floating point number using exponential form * | if the exponent is less than -4 or greater than or * | equal to the precision, or in dd.dddd form otherwise. * | The precision specifies the number of significant digits. * G | Equivalent to `g', but use an uppercase `E' in exponent form. * a | Convert floating point argument as [-]0xh.hhhhp[+-]dd, * | which is consisted from optional sign, "0x", fraction part * | as hexadecimal, "p", and exponential part as decimal. * A | Equivalent to `a', but use uppercase `X' and `P'. * * Field | Other Format * ------+-------------------------------------------------------------- * c | Argument is the numeric code for a single character or * | a single character string itself. * p | The valuing of argument.inspect. * s | Argument is a string to be substituted. If the format * | sequence contains a precision, at most that many characters * | will be copied. * % | A percent sign itself will be displayed. No argument taken. * * The flags modifies the behavior of the formats. * The flag characters are: * * Flag | Applies to | Meaning * ---------+---------------+----------------------------------------- * space | bBdiouxX | Leave a space at the start of * | aAeEfgG | non-negative numbers. * | (numeric fmt) | For `o', `x', `X', `b' and `B', use * | | a minus sign with absolute value for * | | negative values. * ---------+---------------+----------------------------------------- * (digit)$ | all | Specifies the absolute argument number * | | for this field. Absolute and relative * | | argument numbers cannot be mixed in a * | | sprintf string. * ---------+---------------+----------------------------------------- * # | bBoxX | Use an alternative format. * | aAeEfgG | For the conversions `o', increase the precision * | | until the first digit will be `0' if * | | it is not formatted as complements. * | | For the conversions `x', `X', `b' and `B' * | | on non-zero, prefix the result with ``0x'', * | | ``0X'', ``0b'' and ``0B'', respectively. * | | For `a', `A', `e', `E', `f', `g', and 'G', * | | force a decimal point to be added, * | | even if no digits follow. * | | For `g' and 'G', do not remove trailing zeros. * ---------+---------------+----------------------------------------- * + | bBdiouxX | Add a leading plus sign to non-negative * | aAeEfgG | numbers. * | (numeric fmt) | For `o', `x', `X', `b' and `B', use * | | a minus sign with absolute value for * | | negative values. * ---------+---------------+----------------------------------------- * - | all | Left-justify the result of this conversion. * ---------+---------------+----------------------------------------- * 0 (zero) | bBdiouxX | Pad with zeros, not spaces. * | aAeEfgG | For `o', `x', `X', `b' and `B', radix-1 * | (numeric fmt) | is used for negative numbers formatted as * | | complements. * ---------+---------------+----------------------------------------- * * | all | Use the next argument as the field width. * | | If negative, left-justify the result. If the * | | asterisk is followed by a number and a dollar * | | sign, use the indicated argument as the width. * * Examples of flags: * * # `+' and space flag specifies the sign of non-negative numbers. * sprintf("%d", 123) #=> "123" * sprintf("%+d", 123) #=> "+123" * sprintf("% d", 123) #=> " 123" * * # `#' flag for `o' increases number of digits to show `0'. * # `+' and space flag changes format of negative numbers. * sprintf("%o", 123) #=> "173" * sprintf("%#o", 123) #=> "0173" * sprintf("%+o", -123) #=> "-173" * sprintf("%o", -123) #=> "..7605" * sprintf("%#o", -123) #=> "..7605" * * # `#' flag for `x' add a prefix `0x' for non-zero numbers. * # `+' and space flag disables complements for negative numbers. * sprintf("%x", 123) #=> "7b" * sprintf("%#x", 123) #=> "0x7b" * sprintf("%+x", -123) #=> "-7b" * sprintf("%x", -123) #=> "..f85" * sprintf("%#x", -123) #=> "0x..f85" * sprintf("%#x", 0) #=> "0" * * # `#' for `X' uses the prefix `0X'. * sprintf("%X", 123) #=> "7B" * sprintf("%#X", 123) #=> "0X7B" * * # `#' flag for `b' add a prefix `0b' for non-zero numbers. * # `+' and space flag disables complements for negative numbers. * sprintf("%b", 123) #=> "1111011" * sprintf("%#b", 123) #=> "0b1111011" * sprintf("%+b", -123) #=> "-1111011" * sprintf("%b", -123) #=> "..10000101" * sprintf("%#b", -123) #=> "0b..10000101" * sprintf("%#b", 0) #=> "0" * * # `#' for `B' uses the prefix `0B'. * sprintf("%B", 123) #=> "1111011" * sprintf("%#B", 123) #=> "0B1111011" * * # `#' for `e' forces to show the decimal point. * sprintf("%.0e", 1) #=> "1e+00" * sprintf("%#.0e", 1) #=> "1.e+00" * * # `#' for `f' forces to show the decimal point. * sprintf("%.0f", 1234) #=> "1234" * sprintf("%#.0f", 1234) #=> "1234." * * # `#' for `g' forces to show the decimal point. * # It also disables stripping lowest zeros. * sprintf("%g", 123.4) #=> "123.4" * sprintf("%#g", 123.4) #=> "123.400" * sprintf("%g", 123456) #=> "123456" * sprintf("%#g", 123456) #=> "123456." * * The field width is an optional integer, followed optionally by a * period and a precision. The width specifies the minimum number of * characters that will be written to the result for this field. * * Examples of width: * * # padding is done by spaces, width=20 * # 0 or radix-1. <------------------> * sprintf("%20d", 123) #=> " 123" * sprintf("%+20d", 123) #=> " +123" * sprintf("%020d", 123) #=> "00000000000000000123" * sprintf("%+020d", 123) #=> "+0000000000000000123" * sprintf("% 020d", 123) #=> " 0000000000000000123" * sprintf("%-20d", 123) #=> "123 " * sprintf("%-+20d", 123) #=> "+123 " * sprintf("%- 20d", 123) #=> " 123 " * sprintf("%020x", -123) #=> "..ffffffffffffffff85" * * For * numeric fields, the precision controls the number of decimal places * displayed. For string fields, the precision determines the maximum * number of characters to be copied from the string. (Thus, the format * sequence <code>%10.10s</code> will always contribute exactly ten * characters to the result.) * * Examples of precisions: * * # precision for `d', 'o', 'x' and 'b' is * # minimum number of digits <------> * sprintf("%20.8d", 123) #=> " 00000123" * sprintf("%20.8o", 123) #=> " 00000173" * sprintf("%20.8x", 123) #=> " 0000007b" * sprintf("%20.8b", 123) #=> " 01111011" * sprintf("%20.8d", -123) #=> " -00000123" * sprintf("%20.8o", -123) #=> " ..777605" * sprintf("%20.8x", -123) #=> " ..ffff85" * sprintf("%20.8b", -11) #=> " ..110101" * * # "0x" and "0b" for `#x' and `#b' is not counted for * # precision but "0" for `#o' is counted. <------> * sprintf("%#20.8d", 123) #=> " 00000123" * sprintf("%#20.8o", 123) #=> " 00000173" * sprintf("%#20.8x", 123) #=> " 0x0000007b" * sprintf("%#20.8b", 123) #=> " 0b01111011" * sprintf("%#20.8d", -123) #=> " -00000123" * sprintf("%#20.8o", -123) #=> " ..777605" * sprintf("%#20.8x", -123) #=> " 0x..ffff85" * sprintf("%#20.8b", -11) #=> " 0b..110101" * * # precision for `e' is number of * # digits after the decimal point <------> * sprintf("%20.8e", 1234.56789) #=> " 1.23456789e+03" * * # precision for `f' is number of * # digits after the decimal point <------> * sprintf("%20.8f", 1234.56789) #=> " 1234.56789000" * * # precision for `g' is number of * # significant digits <-------> * sprintf("%20.8g", 1234.56789) #=> " 1234.5679" * * # <-------> * sprintf("%20.8g", 123456789) #=> " 1.2345679e+08" * * # precision for `s' is * # maximum number of characters <------> * sprintf("%20.8s", "string test") #=> " string t" * * Examples: * * sprintf("%d %04x", 123, 123) #=> "123 007b" * sprintf("%08b '%4s'", 123, 123) #=> "01111011 ' 123'" * sprintf("%1$*2$s %2$d %1$s", "hello", 8) #=> " hello 8 hello" * sprintf("%1$*2$s %2$d", "hello", -8) #=> "hello -8" * sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23) #=> "+1.23: 1.23:1.23" * sprintf("%u", -123) #=> "-123" * * For more complex formatting, Ruby supports a reference by name. * %<name>s style uses format style, but %{name} style doesn't. * * Exapmles: * sprintf("%<foo>d : %<bar>f", { :foo => 1, :bar => 2 }) * #=> 1 : 2.000000 * sprintf("%{foo}f", { :foo => 1 }) * # => "1f" */ mrb_value mrb_f_sprintf(mrb_state *mrb, mrb_value obj) { int argc; mrb_value *argv; mrb_get_args(mrb, "*", &argv, &argc); if (argc <= 0) { mrb->mrb_raise(E_ARGUMENT_ERROR, "too few arguments"); return mrb_value::nil(); } else { return mrb_str_format(mrb, argc - 1, argv + 1, argv[0]); } } mrb_value mrb_str_format(mrb_state *mrb, int argc, const mrb_value *argv, mrb_value fmt) { const char *p, *end; char *buf; mrb_int blen; mrb_int bsiz; mrb_int n; mrb_int width; mrb_int prec; int flags = FNONE; int nextarg = 1; int posarg = 0; mrb_value nextvalue; mrb_value tmp; mrb_value str; mrb_value hash = mrb_value::undef(); #define CHECK_FOR_WIDTH(f) \ if ((f) & FWIDTH) { \ mrb->mrb_raise(E_ARGUMENT_ERROR, "width given twice"); \ } \ if ((f) & FPREC0) { \ mrb->mrb_raise(E_ARGUMENT_ERROR, "width after precision"); \ } #define CHECK_FOR_FLAGS(f) \ if ((f) & FWIDTH) { \ mrb->mrb_raise(E_ARGUMENT_ERROR, "flag after width"); \ } \ if ((f) & FPREC0) { \ mrb->mrb_raise(E_ARGUMENT_ERROR, "flag after precision"); \ } ++argc; --argv; fmt = mrb_str_to_str(mrb, fmt); p = RSTRING_PTR(fmt); end = p + RSTRING_LEN(fmt); blen = 0; bsiz = 120; RString *res_ptr= RString::create(mrb,bsiz); buf = res_ptr->m_ptr; memset(buf, 0, bsiz); for (; p < end; p++) { const char *t; mrb_sym id = 0; for (t = p; t < end && *t != '%'; t++) ; PUSH(p, t - p); if (t >= end) goto sprint_exit; /* end of fmt string */ p = t + 1; /* skip `%' */ width = prec = -1; nextvalue = mrb_value::undef(); retry: switch (*p) { default: mrb->mrb_raisef(E_ARGUMENT_ERROR, "malformed format string - \\%%S", mrb_str_new(mrb, p, 1)); break; case ' ': CHECK_FOR_FLAGS(flags); flags |= FSPACE; p++; goto retry; case '#': CHECK_FOR_FLAGS(flags); flags |= FSHARP; p++; goto retry; case '+': CHECK_FOR_FLAGS(flags); flags |= FPLUS; p++; goto retry; case '-': CHECK_FOR_FLAGS(flags); flags |= FMINUS; p++; goto retry; case '0': CHECK_FOR_FLAGS(flags); flags |= FZERO; p++; goto retry; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': n = 0; GETNUM(n, width); if (*p == '$') { if (!nextvalue.is_undef()) { mrb->mrb_raisef(E_ARGUMENT_ERROR, "value given twice - %S$", mrb_fixnum_value(n)); } nextvalue = GETPOSARG(n); p++; goto retry; } CHECK_FOR_WIDTH(flags); width = n; flags |= FWIDTH; goto retry; case '<': case '{': { const char *start = p; char term = (*p == '<') ? '>' : '}'; mrb_value symname; for (; p < end && *p != term; ) p++; if (id) { mrb->mrb_raisef(E_ARGUMENT_ERROR, "name%S after <%S>", mrb_str_new(mrb, start, p - start + 1), mrb_sym2str(mrb, id)); } symname = mrb_str_new(mrb, start + 1, p - start - 1); id = mrb_intern_str(mrb, symname); nextvalue = GETNAMEARG(mrb_symbol_value(id), start, (int)(p - start + 1)); if (nextvalue.is_undef()) { mrb->mrb_raisef(E_KEY_ERROR, "key%S not found", mrb_str_new(mrb, start, p - start + 1)); } if (term == '}') goto format_s; p++; goto retry; } case '*': CHECK_FOR_WIDTH(flags); flags |= FWIDTH; GETASTER(width); if (width < 0) { flags |= FMINUS; width = -width; } p++; goto retry; case '.': if (flags & FPREC0) { mrb->mrb_raise(E_ARGUMENT_ERROR, "precision given twice"); } flags |= FPREC|FPREC0; prec = 0; p++; if (*p == '*') { GETASTER(prec); if (prec < 0) { /* ignore negative precision */ flags &= ~FPREC; } p++; goto retry; } GETNUM(prec, precision); goto retry; case '\n': case '\0': p--; case '%': if (flags != FNONE) { mrb->mrb_raise(E_ARGUMENT_ERROR, "invalid format character - %"); } PUSH("%", 1); break; case 'c': { mrb_value val = GETARG(); mrb_value tmp; unsigned int c; tmp = mrb_check_string_type(mrb, val); if (!tmp.is_nil()) { if (RSTRING_LEN(tmp) != 1 ) { mrb->mrb_raise(E_ARGUMENT_ERROR, "%c requires a character"); } c = RSTRING_PTR(tmp)[0]; n = 1; } else { c = mrb_fixnum(val); n = 1; } if (n <= 0) { mrb->mrb_raise(E_ARGUMENT_ERROR, "invalid character"); } if (!(flags & FWIDTH)) { CHECK(n); buf[blen] = c; blen += n; } else if ((flags & FMINUS)) { CHECK(n); buf[blen] = c; blen += n; FILL(' ', width-1); } else { FILL(' ', width-1); CHECK(n); buf[blen] = c; blen += n; } } break; case 's': case 'p': format_s: { mrb_value arg = GETARG(); mrb_int len; mrb_int slen; if (*p == 'p') arg = mrb_inspect(mrb, arg)->wrap(); str = mrb_obj_as_string(mrb, arg)->wrap(); len = RSTRING_LEN(str); res_ptr->len = blen; if (flags&(FPREC|FWIDTH)) { slen = RSTRING_LEN(str); if (slen < 0) { mrb->mrb_raise(E_ARGUMENT_ERROR, "invalid mbstring sequence"); } if ((flags&FPREC) && (prec < slen)) { char *p = RSTRING_PTR(str) + prec; slen = prec; len = p - RSTRING_PTR(str); } /* need to adjust multi-byte string pos */ if ((flags&FWIDTH) && (width > slen)) { width -= (int)slen; if (!(flags&FMINUS)) { CHECK(width); while (width--) { buf[blen++] = ' '; } } CHECK(len); memcpy(&buf[blen], RSTRING_PTR(str), len); blen += len; if (flags&FMINUS) { CHECK(width); while (width--) { buf[blen++] = ' '; } } break; } } PUSH(RSTRING_PTR(str), len); } break; case 'd': case 'i': case 'o': case 'x': case 'X': case 'b': case 'B': case 'u': { mrb_value val = GETARG(); char fbuf[32], nbuf[64], *s; const char *prefix = NULL; int sign = 0, dots = 0; char sc = 0; mrb_int v = 0, org_v = 0; int base; mrb_int len; switch (*p) { case 'd': case 'i': case 'u': sign = 1; break; case 'o': case 'x': case 'X': case 'b': case 'B': if (flags&(FPLUS|FSPACE)) sign = 1; break; default: break; } if (flags & FSHARP) { switch (*p) { case 'o': prefix = "0"; break; case 'x': prefix = "0x"; break; case 'X': prefix = "0X"; break; case 'b': prefix = "0b"; break; case 'B': prefix = "0B"; break; default: break; } } bin_retry: switch (mrb_type(val)) { case MRB_TT_FLOAT: if (FIXABLE(mrb_float(val))) { val = mrb_fixnum_value((mrb_int)mrb_float(val)); goto bin_retry; } v = mrb_flo_to_fixnum(mrb, val); break; case MRB_TT_STRING: v = val.ptr<RString>()->mrb_str_to_inum(0, true); break; case MRB_TT_FIXNUM: v = mrb_fixnum(val); break; default: val = mrb_Integer(mrb, val); goto bin_retry; } switch (*p) { case 'o': base = 8; break; case 'x': case 'X': base = 16; break; case 'b': case 'B': base = 2; break; case 'u': case 'd': case 'i': default: base = 10; break; } if (base == 2) { org_v = v; RString *val_ptr; if ( v < 0 && !sign ) { val_ptr = mrb_fix2binstr(mrb, mrb_fixnum_value(v), base); dots = 1; } else { val_ptr = mrb_fixnum_to_str(mrb, mrb_fixnum_value(v), base); } v = val_ptr->mrb_str_to_inum(10, false); } if (sign) { char c = *p; if (c == 'i') c = 'd'; /* %d and %i are identical */ if (base == 2) c = 'd'; if (v < 0) { v = -v; sc = '-'; width--; } else if (flags & FPLUS) { sc = '+'; width--; } else if (flags & FSPACE) { sc = ' '; width--; } snprintf(fbuf, sizeof(fbuf), "%%l%c", c); snprintf(nbuf, sizeof(nbuf), fbuf, v); s = nbuf; } else { char c = *p; if (c == 'X') c = 'x'; if (base == 2) c = 'd'; s = nbuf; if (v < 0) { dots = 1; } snprintf(fbuf, sizeof(fbuf), "%%l%c", c); snprintf(++s, sizeof(nbuf) - 1, fbuf, v); if (v < 0) { char d; s = remove_sign_bits(s, base); switch (base) { case 16: d = 'f'; break; case 8: d = '7'; break; case 2: d = '1'; break; default: d = 0; break; } if (d && *s != d) { *--s = d; } } } { size_t size; size = strlen(s); /* PARANOID: assert(size <= MRB_INT_MAX) */ len = (mrb_int)size; } if (dots) { prec -= 2; width -= 2; } if (*p == 'X') { char *pp = s; int c; while ((c = (int)(unsigned char)*pp) != 0) { *pp = toupper(c); pp++; } } if (prefix && !prefix[1]) { /* octal */ if (dots) { prefix = NULL; } else if (len == 1 && *s == '0') { len = 0; if (flags & FPREC) prec--; } else if ((flags & FPREC) && (prec > len)) { prefix = NULL; } } else if (len == 1 && *s == '0') { prefix = NULL; } if (prefix) { size_t size; size = strlen(prefix); /* PARANOID: assert(size <= MRB_INT_MAX). * this check is absolutely paranoid. */ width -= (mrb_int)size; } if ((flags & (FZERO|FMINUS|FPREC)) == FZERO) { prec = width; width = 0; } else { if (prec < len) { if (!prefix && prec == 0 && len == 1 && *s == '0') len = 0; prec = len; } width -= prec; } if (!(flags&FMINUS)) { CHECK(width); while (width-- > 0) { buf[blen++] = ' '; } } if (sc) PUSH(&sc, 1); if (prefix) { int plen = (int)strlen(prefix); PUSH(prefix, plen); } CHECK(prec - len); if (dots) PUSH("..", 2); if (v < 0 || (base == 2 && org_v < 0)) { char c = sign_bits(base, p); while (len < prec--) { buf[blen++] = c; } } else if ((flags & (FMINUS|FPREC)) != FMINUS) { char c = '0'; while (len < prec--) { buf[blen++] = c; } } PUSH(s, len); CHECK(width); while (width-- > 0) { buf[blen++] = ' '; } } break; case 'f': case 'g': case 'G': case 'e': case 'E': case 'a': case 'A': { mrb_value val = GETARG(); double fval; int i, need = 6; char fbuf[32]; fval = mrb_float(mrb_Float(mrb, val)); if (isnan(fval) || isinf(fval)) { const char *expr; const int elen = 3; if (isnan(fval)) { expr = "NaN"; } else { expr = "Inf"; } need = elen; if ((!isnan(fval) && fval < 0.0) || (flags & FPLUS)) need++; if ((flags & FWIDTH) && need < width) need = width; CHECK(need + 1); snprintf(&buf[blen], need + 1, "%*s", need, ""); if (flags & FMINUS) { if (!isnan(fval) && fval < 0.0) buf[blen++] = '-'; else if (flags & FPLUS) buf[blen++] = '+'; else if (flags & FSPACE) blen++; memcpy(&buf[blen], expr, elen); } else { if (!isnan(fval) && fval < 0.0) buf[blen + need - elen - 1] = '-'; else if (flags & FPLUS) buf[blen + need - elen - 1] = '+'; else if ((flags & FSPACE) && need > width) blen++; memcpy(&buf[blen + need - elen], expr, elen); } blen += strlen(&buf[blen]); break; } fmt_setup(fbuf, sizeof(fbuf), *p, flags, width, prec); need = 0; if (*p != 'e' && *p != 'E') { i = INT_MIN; frexp(fval, &i); if (i > 0) need = BIT_DIGITS(i); } need += (flags&FPREC) ? prec : 6; if ((flags&FWIDTH) && need < width) need = width; need += 20; CHECK(need); n = snprintf(&buf[blen], need, fbuf, fval); blen += n; } break; } flags = FNONE; } sprint_exit: #if 0 /* XXX - We cannot validate the number of arguments if (digit)$ style used. */ if (posarg >= 0 && nextarg < argc) { const char *mesg = "too many arguments for format string"; if (mrb_test(ruby_debug)) mrb->mrb_raise(E_ARGUMENT_ERROR, mesg); if (mrb_test(ruby_verbose)) mrb_warn(mrb,"%s", mesg); } #endif res_ptr->resize(blen); return res_ptr->wrap(); } static void fmt_setup(char *buf, size_t size, int c, int flags, mrb_int width, mrb_int prec) { char *end = buf + size; int n; *buf++ = '%'; if (flags & FSHARP) *buf++ = '#'; if (flags & FPLUS) *buf++ = '+'; if (flags & FMINUS) *buf++ = '-'; if (flags & FZERO) *buf++ = '0'; if (flags & FSPACE) *buf++ = ' '; if (flags & FWIDTH) { n = snprintf(buf, end - buf, "%d", (int)width); buf += n; } if (flags & FPREC) { n = snprintf(buf, end - buf, ".%d", (int)prec); buf += n; } *buf++ = c; *buf = '\0'; }
[ "nemerle5@gmail.com" ]
nemerle5@gmail.com
e9638d00aef30b1fe96a36d70c742c27df767499
e9a6d51f037496b1ef1f0e3ec2fe0da90f9e2ad7
/Project_PDV/Project_PDV/Ordenes.h
88ddf9866298c7f369dd623cf97355bba564d96b
[]
no_license
CarlosIzarra09/PuntoDeVenta
1fcd268a5e360e17c7ed5ad0c72ceb2f557cae82
845cd3f748dc27ed35e0062a7fd7b21754e5ab66
refs/heads/master
2022-11-23T09:44:11.870354
2020-07-23T00:51:54
2020-07-23T00:51:54
279,483,925
0
0
null
null
null
null
ISO-8859-1
C++
false
false
55,113
h
#pragma once #include "ThemeColor.h" #include "EditarOrden.h" namespace ProjectPDV { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::Data::SqlClient; /// <summary> /// Resumen de Ordenes /// </summary> public ref class Ordenes : public System::Windows::Forms::Form { double T_Order; bool puntero; SqlConnection^cn; SqlConnectionStringBuilder^str; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column4; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column1; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column2; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column3; private: System::Windows::Forms::Button^ button4; public: Ordenes(void) { puntero = false; InitializeComponent(); // //TODO: agregar código de constructor aquí // } protected: /// <summary> /// Limpiar los recursos que se estén usando. /// </summary> ~Ordenes() { if (components) { delete components; } } private: System::Windows::Forms::Button^ btnRegist; protected: private: System::Windows::Forms::Button^ btnEdit; private: System::Windows::Forms::DataGridView^ dataGridView2; private: System::Windows::Forms::Label^ lbl1; private: System::Windows::Forms::TextBox^ TBcliente; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::TextBox^ TBcel; private: System::Windows::Forms::TextBox^ TBdireccion; private: System::Windows::Forms::CheckBox^ checkBox1; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::CheckBox^ checkBox2; private: System::Windows::Forms::ComboBox^ CBB1; private: System::Windows::Forms::RichTextBox^ richTBcomment; private: System::Windows::Forms::Button^ button1; private: System::Windows::Forms::Label^ label4; private: System::Windows::Forms::Label^ label7; private: System::Windows::Forms::TextBox^ textBox5; private: System::Windows::Forms::Label^ label8; private: System::Windows::Forms::Label^ lblPrecio; private: System::Windows::Forms::Label^ lbl2; private: System::Windows::Forms::ComboBox^ CBB2; private: System::Windows::Forms::Label^ label10; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::ComboBox^ CBB3; private: System::Windows::Forms::Button^ button3; private: System::Windows::Forms::DataGridView^ dataGridView1; private: System::Windows::Forms::Label^ lblprecioU; private: System::Windows::Forms::Label^ label9; private: System::Windows::Forms::CheckBox^ checkBox3; private: System::Windows::Forms::Label^ label5; private: System::Windows::Forms::TextBox^ textBox1; private: System::Windows::Forms::Button^ BtnSearch; private: System::ComponentModel::IContainer^ components; private: /// <summary> /// Variable del diseñador necesaria. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido de este método con el editor de código. /// </summary> void InitializeComponent(void) { System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Ordenes::typeid)); System::Windows::Forms::DataGridViewCellStyle^ dataGridViewCellStyle1 = (gcnew System::Windows::Forms::DataGridViewCellStyle()); System::Windows::Forms::DataGridViewCellStyle^ dataGridViewCellStyle2 = (gcnew System::Windows::Forms::DataGridViewCellStyle()); this->btnRegist = (gcnew System::Windows::Forms::Button()); this->btnEdit = (gcnew System::Windows::Forms::Button()); this->dataGridView2 = (gcnew System::Windows::Forms::DataGridView()); this->lbl1 = (gcnew System::Windows::Forms::Label()); this->TBcliente = (gcnew System::Windows::Forms::TextBox()); this->label1 = (gcnew System::Windows::Forms::Label()); this->label2 = (gcnew System::Windows::Forms::Label()); this->TBcel = (gcnew System::Windows::Forms::TextBox()); this->TBdireccion = (gcnew System::Windows::Forms::TextBox()); this->checkBox1 = (gcnew System::Windows::Forms::CheckBox()); this->label3 = (gcnew System::Windows::Forms::Label()); this->checkBox2 = (gcnew System::Windows::Forms::CheckBox()); this->CBB1 = (gcnew System::Windows::Forms::ComboBox()); this->richTBcomment = (gcnew System::Windows::Forms::RichTextBox()); this->button1 = (gcnew System::Windows::Forms::Button()); this->label4 = (gcnew System::Windows::Forms::Label()); this->label7 = (gcnew System::Windows::Forms::Label()); this->textBox5 = (gcnew System::Windows::Forms::TextBox()); this->label8 = (gcnew System::Windows::Forms::Label()); this->lblPrecio = (gcnew System::Windows::Forms::Label()); this->lbl2 = (gcnew System::Windows::Forms::Label()); this->CBB2 = (gcnew System::Windows::Forms::ComboBox()); this->label10 = (gcnew System::Windows::Forms::Label()); this->button2 = (gcnew System::Windows::Forms::Button()); this->CBB3 = (gcnew System::Windows::Forms::ComboBox()); this->button3 = (gcnew System::Windows::Forms::Button()); this->dataGridView1 = (gcnew System::Windows::Forms::DataGridView()); this->Column4 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Column1 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Column2 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Column3 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->lblprecioU = (gcnew System::Windows::Forms::Label()); this->label9 = (gcnew System::Windows::Forms::Label()); this->checkBox3 = (gcnew System::Windows::Forms::CheckBox()); this->label5 = (gcnew System::Windows::Forms::Label()); this->textBox1 = (gcnew System::Windows::Forms::TextBox()); this->BtnSearch = (gcnew System::Windows::Forms::Button()); this->button4 = (gcnew System::Windows::Forms::Button()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView2))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView1))->BeginInit(); this->SuspendLayout(); // // btnRegist // this->btnRegist->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->btnRegist->BackColor = System::Drawing::SystemColors::ActiveCaptionText; this->btnRegist->Cursor = System::Windows::Forms::Cursors::Hand; this->btnRegist->FlatAppearance->BorderSize = 0; this->btnRegist->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->btnRegist->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->btnRegist->ForeColor = System::Drawing::Color::White; this->btnRegist->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnRegist.Image"))); this->btnRegist->Location = System::Drawing::Point(577, 50); this->btnRegist->Name = L"btnRegist"; this->btnRegist->Size = System::Drawing::Size(159, 42); this->btnRegist->TabIndex = 2; this->btnRegist->Text = L" Registrar"; this->btnRegist->TextImageRelation = System::Windows::Forms::TextImageRelation::ImageBeforeText; this->btnRegist->UseVisualStyleBackColor = false; this->btnRegist->Click += gcnew System::EventHandler(this, &Ordenes::btnRegist_Click); // // btnEdit // this->btnEdit->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->btnEdit->BackColor = System::Drawing::SystemColors::ActiveCaptionText; this->btnEdit->Cursor = System::Windows::Forms::Cursors::Hand; this->btnEdit->FlatAppearance->BorderSize = 0; this->btnEdit->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->btnEdit->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->btnEdit->ForeColor = System::Drawing::Color::White; this->btnEdit->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"btnEdit.Image"))); this->btnEdit->ImageAlign = System::Drawing::ContentAlignment::MiddleLeft; this->btnEdit->Location = System::Drawing::Point(577, 98); this->btnEdit->Name = L"btnEdit"; this->btnEdit->Size = System::Drawing::Size(159, 42); this->btnEdit->TabIndex = 3; this->btnEdit->Text = L" Corregir"; this->btnEdit->TextImageRelation = System::Windows::Forms::TextImageRelation::ImageBeforeText; this->btnEdit->UseVisualStyleBackColor = false; this->btnEdit->Click += gcnew System::EventHandler(this, &Ordenes::btnEdit_Click); // // dataGridView2 // this->dataGridView2->AllowUserToAddRows = false; this->dataGridView2->AllowUserToDeleteRows = false; this->dataGridView2->AllowUserToResizeColumns = false; this->dataGridView2->AllowUserToResizeRows = false; this->dataGridView2->Anchor = static_cast<System::Windows::Forms::AnchorStyles>(((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right)); this->dataGridView2->BackgroundColor = System::Drawing::SystemColors::Control; this->dataGridView2->BorderStyle = System::Windows::Forms::BorderStyle::None; this->dataGridView2->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; this->dataGridView2->Location = System::Drawing::Point(12, 366); this->dataGridView2->Name = L"dataGridView2"; this->dataGridView2->ReadOnly = true; dataGridViewCellStyle1->Alignment = System::Windows::Forms::DataGridViewContentAlignment::MiddleLeft; dataGridViewCellStyle1->BackColor = System::Drawing::SystemColors::ActiveCaptionText; dataGridViewCellStyle1->Font = (gcnew System::Drawing::Font(L"Montserrat", 8.249999F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); dataGridViewCellStyle1->ForeColor = System::Drawing::SystemColors::Window; dataGridViewCellStyle1->SelectionBackColor = System::Drawing::SystemColors::Highlight; dataGridViewCellStyle1->SelectionForeColor = System::Drawing::SystemColors::HighlightText; dataGridViewCellStyle1->WrapMode = System::Windows::Forms::DataGridViewTriState::True; this->dataGridView2->RowHeadersDefaultCellStyle = dataGridViewCellStyle1; this->dataGridView2->Size = System::Drawing::Size(724, 169); this->dataGridView2->TabIndex = 5; // // lbl1 // this->lbl1->AutoSize = true; this->lbl1->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lbl1->Location = System::Drawing::Point(26, 50); this->lbl1->Name = L"lbl1"; this->lbl1->Size = System::Drawing::Size(80, 24); this->lbl1->TabIndex = 6; this->lbl1->Text = L"Cliente"; // // TBcliente // this->TBcliente->BorderStyle = System::Windows::Forms::BorderStyle::None; this->TBcliente->Font = (gcnew System::Drawing::Font(L"Montserrat", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->TBcliente->Location = System::Drawing::Point(112, 54); this->TBcliente->Name = L"TBcliente"; this->TBcliente->Size = System::Drawing::Size(181, 20); this->TBcliente->TabIndex = 8; // // label1 // this->label1->AutoSize = true; this->label1->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label1->Location = System::Drawing::Point(26, 86); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(80, 24); this->label1->TabIndex = 9; this->label1->Text = L"Celular"; this->label1->Click += gcnew System::EventHandler(this, &Ordenes::label1_Click); // // label2 // this->label2->AutoSize = true; this->label2->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label2->Location = System::Drawing::Point(26, 148); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(106, 24); this->label2->TabIndex = 10; this->label2->Text = L"Dirección"; // // TBcel // this->TBcel->BorderStyle = System::Windows::Forms::BorderStyle::None; this->TBcel->Font = (gcnew System::Drawing::Font(L"Montserrat", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->TBcel->Location = System::Drawing::Point(112, 86); this->TBcel->Name = L"TBcel"; this->TBcel->Size = System::Drawing::Size(181, 20); this->TBcel->TabIndex = 11; // // TBdireccion // this->TBdireccion->BorderStyle = System::Windows::Forms::BorderStyle::None; this->TBdireccion->Font = (gcnew System::Drawing::Font(L"Montserrat", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->TBdireccion->Location = System::Drawing::Point(138, 152); this->TBdireccion->Name = L"TBdireccion"; this->TBdireccion->Size = System::Drawing::Size(243, 20); this->TBdireccion->TabIndex = 12; // // checkBox1 // this->checkBox1->AutoSize = true; this->checkBox1->Font = (gcnew System::Drawing::Font(L"Montserrat", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->checkBox1->Location = System::Drawing::Point(122, 122); this->checkBox1->Name = L"checkBox1"; this->checkBox1->Size = System::Drawing::Size(43, 23); this->checkBox1->TabIndex = 13; this->checkBox1->Text = L"SI"; this->checkBox1->UseVisualStyleBackColor = true; this->checkBox1->CheckedChanged += gcnew System::EventHandler(this, &Ordenes::checkBox1_CheckedChanged); // // label3 // this->label3->AutoSize = true; this->label3->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label3->Location = System::Drawing::Point(26, 119); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(90, 24); this->label3->TabIndex = 14; this->label3->Text = L"Delivery"; // // checkBox2 // this->checkBox2->AutoSize = true; this->checkBox2->Font = (gcnew System::Drawing::Font(L"Montserrat", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->checkBox2->Location = System::Drawing::Point(171, 122); this->checkBox2->Name = L"checkBox2"; this->checkBox2->Size = System::Drawing::Size(54, 23); this->checkBox2->TabIndex = 15; this->checkBox2->Text = L"NO"; this->checkBox2->UseVisualStyleBackColor = true; this->checkBox2->CheckedChanged += gcnew System::EventHandler(this, &Ordenes::checkBox2_CheckedChanged); // // CBB1 // this->CBB1->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList; this->CBB1->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->CBB1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->CBB1->FormattingEnabled = true; this->CBB1->Items->AddRange(gcnew cli::array< System::Object^ >(2) { L"Bladi", L"Gabriel" }); this->CBB1->Location = System::Drawing::Point(231, 117); this->CBB1->Name = L"CBB1"; this->CBB1->Size = System::Drawing::Size(150, 28); this->CBB1->TabIndex = 16; // // richTBcomment // this->richTBcomment->BorderStyle = System::Windows::Forms::BorderStyle::None; this->richTBcomment->Font = (gcnew System::Drawing::Font(L"Montserrat", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->richTBcomment->Location = System::Drawing::Point(161, 183); this->richTBcomment->Name = L"richTBcomment"; this->richTBcomment->Size = System::Drawing::Size(220, 127); this->richTBcomment->TabIndex = 17; this->richTBcomment->Text = L""; // // button1 // this->button1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->button1->BackColor = System::Drawing::SystemColors::ActiveCaptionText; this->button1->Cursor = System::Windows::Forms::Cursors::Hand; this->button1->FlatAppearance->BorderSize = 0; this->button1->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->button1->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button1->ForeColor = System::Drawing::Color::White; this->button1->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"button1.Image"))); this->button1->ImageAlign = System::Drawing::ContentAlignment::MiddleLeft; this->button1->Location = System::Drawing::Point(577, 146); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(159, 42); this->button1->TabIndex = 18; this->button1->Text = L" Eliminar"; this->button1->TextImageRelation = System::Windows::Forms::TextImageRelation::ImageBeforeText; this->button1->UseVisualStyleBackColor = false; this->button1->Click += gcnew System::EventHandler(this, &Ordenes::button1_Click); // // label4 // this->label4->AutoSize = true; this->label4->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label4->Location = System::Drawing::Point(26, 183); this->label4->Name = L"label4"; this->label4->Size = System::Drawing::Size(129, 24); this->label4->TabIndex = 19; this->label4->Text = L"Comentario"; // // label7 // this->label7->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->label7->AutoSize = true; this->label7->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label7->Location = System::Drawing::Point(387, 125); this->label7->Name = L"label7"; this->label7->Size = System::Drawing::Size(64, 24); this->label7->TabIndex = 25; this->label7->Text = L"Cant."; // // textBox5 // this->textBox5->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->textBox5->BorderStyle = System::Windows::Forms::BorderStyle::None; this->textBox5->Font = (gcnew System::Drawing::Font(L"Montserrat", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->textBox5->Location = System::Drawing::Point(457, 125); this->textBox5->Name = L"textBox5"; this->textBox5->Size = System::Drawing::Size(59, 20); this->textBox5->TabIndex = 26; // // label8 // this->label8->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->label8->AutoSize = true; this->label8->Font = (gcnew System::Drawing::Font(L"Montserrat", 20)); this->label8->Location = System::Drawing::Point(616, 275); this->label8->Name = L"label8"; this->label8->Size = System::Drawing::Size(102, 33); this->label8->TabIndex = 27; this->label8->Text = L"TOTAL"; // // lblPrecio // this->lblPrecio->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->lblPrecio->AutoSize = true; this->lblPrecio->Font = (gcnew System::Drawing::Font(L"Montserrat", 22)); this->lblPrecio->ForeColor = System::Drawing::Color::DarkRed; this->lblPrecio->Location = System::Drawing::Point(639, 308); this->lblPrecio->Name = L"lblPrecio"; this->lblPrecio->Size = System::Drawing::Size(88, 37); this->lblPrecio->TabIndex = 28; this->lblPrecio->Text = L"0.00"; // // lbl2 // this->lbl2->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->lbl2->AutoSize = true; this->lbl2->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lbl2->Location = System::Drawing::Point(387, 90); this->lbl2->Name = L"lbl2"; this->lbl2->Size = System::Drawing::Size(64, 24); this->lbl2->TabIndex = 31; this->lbl2->Text = L"Prod."; this->lbl2->Click += gcnew System::EventHandler(this, &Ordenes::lbl2_Click); // // CBB2 // this->CBB2->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->CBB2->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList; this->CBB2->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->CBB2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->CBB2->FormattingEnabled = true; this->CBB2->Items->AddRange(gcnew cli::array< System::Object^ >(6) { L"Broaster", L"Burgers", L"Gaseosas", L"Bebidas", L"Postres", L"Extras" }); this->CBB2->Location = System::Drawing::Point(457, 50); this->CBB2->Name = L"CBB2"; this->CBB2->Size = System::Drawing::Size(114, 28); this->CBB2->TabIndex = 30; this->CBB2->SelectedIndexChanged += gcnew System::EventHandler(this, &Ordenes::CBB2_SelectedIndexChanged); // // label10 // this->label10->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->label10->AutoSize = true; this->label10->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label10->Location = System::Drawing::Point(375, 54); this->label10->Name = L"label10"; this->label10->Size = System::Drawing::Size(76, 24); this->label10->TabIndex = 29; this->label10->Text = L"Categ."; // // button2 // this->button2->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->button2->BackColor = System::Drawing::SystemColors::ActiveCaptionText; this->button2->Cursor = System::Windows::Forms::Cursors::Hand; this->button2->FlatAppearance->BorderSize = 0; this->button2->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->button2->Font = (gcnew System::Drawing::Font(L"Montserrat", 12)); this->button2->ForeColor = System::Drawing::Color::White; this->button2->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"button2.Image"))); this->button2->ImageAlign = System::Drawing::ContentAlignment::MiddleLeft; this->button2->Location = System::Drawing::Point(391, 159); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(86, 27); this->button2->TabIndex = 33; this->button2->Text = L"Añadir"; this->button2->TextImageRelation = System::Windows::Forms::TextImageRelation::ImageBeforeText; this->button2->UseVisualStyleBackColor = false; this->button2->Click += gcnew System::EventHandler(this, &Ordenes::button2_Click); // // CBB3 // this->CBB3->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->CBB3->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList; this->CBB3->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->CBB3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->CBB3->FormattingEnabled = true; this->CBB3->Location = System::Drawing::Point(457, 86); this->CBB3->Name = L"CBB3"; this->CBB3->Size = System::Drawing::Size(114, 28); this->CBB3->TabIndex = 34; this->CBB3->SelectedIndexChanged += gcnew System::EventHandler(this, &Ordenes::CBB3_SelectedIndexChanged); // // button3 // this->button3->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->button3->BackColor = System::Drawing::SystemColors::ActiveCaptionText; this->button3->Cursor = System::Windows::Forms::Cursors::Hand; this->button3->FlatAppearance->BorderSize = 0; this->button3->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->button3->Font = (gcnew System::Drawing::Font(L"Montserrat", 12)); this->button3->ForeColor = System::Drawing::Color::White; this->button3->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"button3.Image"))); this->button3->ImageAlign = System::Drawing::ContentAlignment::MiddleLeft; this->button3->Location = System::Drawing::Point(485, 159); this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(86, 27); this->button3->TabIndex = 35; this->button3->Text = L"Quitar"; this->button3->TextImageRelation = System::Windows::Forms::TextImageRelation::ImageBeforeText; this->button3->UseVisualStyleBackColor = false; this->button3->Click += gcnew System::EventHandler(this, &Ordenes::button3_Click); // // dataGridView1 // this->dataGridView1->AllowUserToAddRows = false; this->dataGridView1->AllowUserToDeleteRows = false; this->dataGridView1->AllowUserToResizeColumns = false; this->dataGridView1->AllowUserToResizeRows = false; this->dataGridView1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>(((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right)); this->dataGridView1->BackgroundColor = System::Drawing::SystemColors::ActiveBorder; this->dataGridView1->BorderStyle = System::Windows::Forms::BorderStyle::None; this->dataGridView1->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; this->dataGridView1->Columns->AddRange(gcnew cli::array< System::Windows::Forms::DataGridViewColumn^ >(4) { this->Column4, this->Column1, this->Column2, this->Column3 }); this->dataGridView1->Location = System::Drawing::Point(391, 192); this->dataGridView1->Name = L"dataGridView1"; this->dataGridView1->ReadOnly = true; dataGridViewCellStyle2->Alignment = System::Windows::Forms::DataGridViewContentAlignment::MiddleLeft; dataGridViewCellStyle2->BackColor = System::Drawing::SystemColors::ActiveCaptionText; dataGridViewCellStyle2->Font = (gcnew System::Drawing::Font(L"Montserrat", 8.249999F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); dataGridViewCellStyle2->ForeColor = System::Drawing::SystemColors::Window; dataGridViewCellStyle2->SelectionBackColor = System::Drawing::SystemColors::Highlight; dataGridViewCellStyle2->SelectionForeColor = System::Drawing::SystemColors::HighlightText; dataGridViewCellStyle2->WrapMode = System::Windows::Forms::DataGridViewTriState::True; this->dataGridView1->RowHeadersDefaultCellStyle = dataGridViewCellStyle2; this->dataGridView1->RowHeadersVisible = false; this->dataGridView1->Size = System::Drawing::Size(180, 156); this->dataGridView1->TabIndex = 36; // // Column4 // this->Column4->HeaderText = L"ID"; this->Column4->Name = L"Column4"; this->Column4->ReadOnly = true; this->Column4->Width = 25; // // Column1 // this->Column1->HeaderText = L"Cant."; this->Column1->Name = L"Column1"; this->Column1->ReadOnly = true; this->Column1->Width = 40; // // Column2 // this->Column2->HeaderText = L"Nombre"; this->Column2->Name = L"Column2"; this->Column2->ReadOnly = true; this->Column2->Width = 50; // // Column3 // this->Column3->HeaderText = L"Precio"; this->Column3->Name = L"Column3"; this->Column3->ReadOnly = true; this->Column3->Width = 50; // // lblprecioU // this->lblprecioU->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->lblprecioU->AutoSize = true; this->lblprecioU->BackColor = System::Drawing::Color::Transparent; this->lblprecioU->Font = (gcnew System::Drawing::Font(L"Montserrat", 22)); this->lblprecioU->ForeColor = System::Drawing::Color::DarkRed; this->lblprecioU->Location = System::Drawing::Point(595, 308); this->lblprecioU->Name = L"lblprecioU"; this->lblprecioU->Size = System::Drawing::Size(50, 37); this->lblprecioU->TabIndex = 37; this->lblprecioU->Text = L"s/"; // // label9 // this->label9->AutoSize = true; this->label9->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label9->Location = System::Drawing::Point(157, 324); this->label9->Name = L"label9"; this->label9->Size = System::Drawing::Size(104, 24); this->label9->TabIndex = 38; this->label9->Text = L"Paga con"; // // checkBox3 // this->checkBox3->AutoSize = true; this->checkBox3->Font = (gcnew System::Drawing::Font(L"Montserrat", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->checkBox3->Location = System::Drawing::Point(267, 327); this->checkBox3->Name = L"checkBox3"; this->checkBox3->Size = System::Drawing::Size(74, 23); this->checkBox3->TabIndex = 39; this->checkBox3->Text = L"YAPE "; this->checkBox3->UseVisualStyleBackColor = true; this->checkBox3->CheckedChanged += gcnew System::EventHandler(this, &Ordenes::checkBox3_CheckedChanged); // // label5 // this->label5->AutoSize = true; this->label5->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->label5->Location = System::Drawing::Point(26, 323); this->label5->Name = L"label5"; this->label5->Size = System::Drawing::Size(92, 24); this->label5->TabIndex = 40; this->label5->Text = L"Envio s/"; // // textBox1 // this->textBox1->BorderStyle = System::Windows::Forms::BorderStyle::None; this->textBox1->Font = (gcnew System::Drawing::Font(L"Montserrat", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->textBox1->Location = System::Drawing::Point(122, 324); this->textBox1->Name = L"textBox1"; this->textBox1->Size = System::Drawing::Size(29, 20); this->textBox1->TabIndex = 41; // // BtnSearch // this->BtnSearch->BackColor = System::Drawing::SystemColors::ActiveCaptionText; this->BtnSearch->Cursor = System::Windows::Forms::Cursors::Hand; this->BtnSearch->FlatAppearance->BorderSize = 0; this->BtnSearch->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->BtnSearch->Font = (gcnew System::Drawing::Font(L"Montserrat", 12)); this->BtnSearch->ForeColor = System::Drawing::Color::White; this->BtnSearch->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"BtnSearch.Image"))); this->BtnSearch->ImageAlign = System::Drawing::ContentAlignment::MiddleLeft; this->BtnSearch->Location = System::Drawing::Point(299, 51); this->BtnSearch->Name = L"BtnSearch"; this->BtnSearch->Size = System::Drawing::Size(28, 27); this->BtnSearch->TabIndex = 42; this->BtnSearch->TextImageRelation = System::Windows::Forms::TextImageRelation::ImageBeforeText; this->BtnSearch->UseVisualStyleBackColor = false; this->BtnSearch->Click += gcnew System::EventHandler(this, &Ordenes::BtnSearch_Click); // // button4 // this->button4->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right)); this->button4->BackColor = System::Drawing::SystemColors::ActiveCaptionText; this->button4->Cursor = System::Windows::Forms::Cursors::Hand; this->button4->FlatAppearance->BorderSize = 0; this->button4->FlatStyle = System::Windows::Forms::FlatStyle::Flat; this->button4->Font = (gcnew System::Drawing::Font(L"Montserrat", 15, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->button4->ForeColor = System::Drawing::Color::White; this->button4->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"button4.Image"))); this->button4->Location = System::Drawing::Point(688, 192); this->button4->Name = L"button4"; this->button4->Size = System::Drawing::Size(48, 42); this->button4->TabIndex = 43; this->button4->TextImageRelation = System::Windows::Forms::TextImageRelation::ImageBeforeText; this->button4->UseVisualStyleBackColor = false; this->button4->Click += gcnew System::EventHandler(this, &Ordenes::button4_Click); // // Ordenes // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(748, 470); this->Controls->Add(this->button4); this->Controls->Add(this->BtnSearch); this->Controls->Add(this->textBox1); this->Controls->Add(this->label5); this->Controls->Add(this->checkBox3); this->Controls->Add(this->label9); this->Controls->Add(this->lblprecioU); this->Controls->Add(this->dataGridView1); this->Controls->Add(this->button3); this->Controls->Add(this->CBB3); this->Controls->Add(this->button2); this->Controls->Add(this->lbl2); this->Controls->Add(this->CBB2); this->Controls->Add(this->label10); this->Controls->Add(this->lblPrecio); this->Controls->Add(this->label8); this->Controls->Add(this->textBox5); this->Controls->Add(this->label7); this->Controls->Add(this->label4); this->Controls->Add(this->button1); this->Controls->Add(this->richTBcomment); this->Controls->Add(this->CBB1); this->Controls->Add(this->checkBox2); this->Controls->Add(this->label3); this->Controls->Add(this->checkBox1); this->Controls->Add(this->TBdireccion); this->Controls->Add(this->TBcel); this->Controls->Add(this->label2); this->Controls->Add(this->label1); this->Controls->Add(this->TBcliente); this->Controls->Add(this->lbl1); this->Controls->Add(this->dataGridView2); this->Controls->Add(this->btnEdit); this->Controls->Add(this->btnRegist); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None; this->Name = L"Ordenes"; this->Text = L"ORDENES"; this->Load += gcnew System::EventHandler(this, &Ordenes::Ordenes_Load); this->MdiChildActivate += gcnew System::EventHandler(this, &Ordenes::Ordenes_MdiChildActivate); this->SizeChanged += gcnew System::EventHandler(this, &Ordenes::Ordenes_SizeChanged); this->MouseClick += gcnew System::Windows::Forms::MouseEventHandler(this, &Ordenes::Ordenes_MouseClick); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView2))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView1))->EndInit(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void label1_Click(System::Object^ sender, System::EventArgs^ e) { } public: void LoadTheme(Color primary, Color secondary) { lblPrecio->ForeColor = primary; lblprecioU->ForeColor = secondary; } private: System::Void Ordenes_Load(System::Object^ sender, System::EventArgs^ e) { //dateTimePicker1->Value = DateTime::Now; checkBox1->Checked = true; CBB1->SelectedIndex = 0; CBB2->SelectedIndex = 0; CBB3->SelectedIndex = 0; //Inicializamos conexion con la base de datos str = gcnew SqlConnectionStringBuilder(); str->DataSource = "EDUARDO-PC\\SQLEXPRESS"; str->InitialCatalog = "DSONIA_BD"; str->IntegratedSecurity = true; cn = gcnew SqlConnection(Convert::ToString(str)); Actualizar_DGV(); //CargarRegistros("Select*from dbo.Product"); } private: void CargarRegistros(String^Comando) { SqlCommand^cmdDatabase = gcnew SqlCommand(Comando, cn); SqlDataAdapter^ sda = gcnew SqlDataAdapter(); if (Comando->Substring(0, 6) == "Select") { sda->SelectCommand = cmdDatabase; DataTable^ dbaDataSet = gcnew DataTable(); sda->Fill(dbaDataSet); BindingSource^ bSource = gcnew BindingSource(); bSource->DataSource = dbaDataSet; dataGridView2->DataSource = bSource; sda->Update(dbaDataSet); bSource->Position = dataGridView2->Rows->Count - 1; } if (Comando->Substring(0, 6) == "Update" || Comando->Substring(0, 6) == "Insert" || Comando->Substring(0, 6) == "Delete") { cn->Open(); cmdDatabase->ExecuteNonQuery(); cn->Close(); } } private: String^ fecha_actual() { int ano = DateTime::Now.Year; int mes = DateTime::Now.Month; int dia = DateTime::Now.Day; String^fecha = ano.ToString() + "-" + mes.ToString() + "-" + dia.ToString(); return fecha; } private: String^ hora_actual() { int hh = DateTime::Now.Hour; int mm = DateTime::Now.Minute; int ss = DateTime::Now.Second; String^hora = hh.ToString() + ":" + mm.ToString() + ":" + ss.ToString()+".000"; return hora; } private: void Actualizar_DGV() { CargarRegistros("Select * from dbo.FN_Productos_hoy_dia('"+fecha_actual()+"')"); dataGridView2->Columns[0]->HeaderText = "ID"; dataGridView2->Columns[1]->HeaderText = "Cliente"; dataGridView2->Columns[2]->HeaderText = "Teléfono"; dataGridView2->Columns[3]->HeaderText = "Hora ordenada"; dataGridView2->Columns[4]->HeaderText = "Hora entregada"; dataGridView2->Columns[5]->HeaderText = "Direccion"; dataGridView2->Columns[6]->HeaderText = "Comentario"; dataGridView2->Columns[7]->HeaderText = "Monto"; } private: System::Void Ordenes_SizeChanged(System::Object^ sender, System::EventArgs^ e) { this->dataGridView2->Height = this->Height - 240; this->dataGridView1->Columns[1]->Width = (dataGridView1->Width - 80) / 2; this->dataGridView1->Columns[2]->Width = (dataGridView1->Width - 80) / 2; } private: System::Void lbl2_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { double precio; int ID; if (CBB3->Text == "Alita") { precio = 4.50; ID = 1; } else if (CBB3->Text == "Piernita") { precio = 5.00; ID = 2; } else if (CBB3->Text == "Muslito") { precio = 6.00; ID = 3; } else if (CBB3->Text == "Pecho") { precio = 7.00; ID = 4; } else if (CBB3->Text == "Filete de pollo") {precio = 6.50; ID = 5;} else if (CBB3->Text == "Salchipapa") { precio = 4.00; ID = 6; } else if (CBB3->Text == "H. de pollo") {precio = 3.00; ID = 7;} else if (CBB3->Text == "H. de carne") {precio = 3.00; ID = 8;} else if (CBB3->Text == "Broaster Burger") {precio = 5.50; ID = 9;} else if (CBB3->Text == "1 1/2 L INKA") {precio = 6.50; ID = 10;} else if (CBB3->Text == "1 1/2 L COCA") {precio = 6.50; ID =11;} else if (CBB3->Text == "1 L INKA") {precio = 5.50; ID = 12;} else if (CBB3->Text == "1 L COCA") {precio = 5.50; ID = 13;} else if (CBB3->Text == "1/2 L INKA") { precio = 2.50; ID = 14; } else if (CBB3->Text == "1/2 L COCA") {precio = 2.50; ID = 15;} else if (CBB3->Text == "1/2 L Fanta R.") {precio = 2.00; ID = 16;} else if (CBB3->Text == "1/2 L Fanta N.") {precio = 2.00; ID = 17;} else if (CBB3->Text == "1/2 L Pepsi") {precio = 2.00; ID = 18;} else if (CBB3->Text == "1/2 L Guarana") {precio = 2.00; ID = 19;} else if (CBB3->Text == "Pepsi J.") {precio = 3.00; ID = 20;} else if (CBB3->Text == "Esporade") {precio = 2.50; ID = 21;} else if (CBB3->Text == "Agua Cielo") {precio = 1.50; ID = 22;} else if (CBB3->Text == "Emoliente Vaso") {precio = 1.00; ID = 23;} else if (CBB3->Text == "Emoliente 1/2 Litro") {precio = 2.50; ID = 24;} else if (CBB3->Text == "Emoliente 1 Litro") {precio = 4.00; ID = 25;} else if (CBB3->Text == "Gelatina") {precio = 1.00; ID = 26;} else if (CBB3->Text == "Gelatina con flan") {precio = 1.50; ID = 27;} else if (CBB3->Text == "Porcion Papa") {precio = 3.00; ID = 28;} else if (CBB3->Text == "Arroz adicional") {precio = 0.50; ID = 29;} else if (CBB3->Text == "Porcion Arroz") { precio = 2.00; ID = 30;} double total = Convert::ToDouble(textBox5->Text)*precio; int rowEscribir = dataGridView1->Rows->Count; dataGridView1->Rows->Add(1); dataGridView1->Rows[rowEscribir]->Cells[0]->Value =ID.ToString(); dataGridView1->Rows[rowEscribir]->Cells[1]->Value = textBox5->Text; dataGridView1->Rows[rowEscribir]->Cells[2]->Value = CBB3->Text; dataGridView1->Rows[rowEscribir]->Cells[3]->Value = total.ToString(); T_Order = Convert::ToDouble(lblPrecio->Text); T_Order += total; lblPrecio->Text = T_Order.ToString(); } private: System::Void CBB2_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { CBB3->Items->Clear(); switch (CBB2->SelectedIndex) { case 0: CBB3->Items->Add(L"Alita"); CBB3->Items->Add(L"Piernita"); CBB3->Items->Add(L"Muslito"); CBB3->Items->Add(L"Pecho"); CBB3->Items->Add(L"Filete de pollo"); CBB3->Items->Add(L"Salchipapa"); break; case 1: CBB3->Items->Add(L"H. de pollo"); CBB3->Items->Add(L"H. de carne"); CBB3->Items->Add(L"Broaster Burger"); break; case 2: CBB3->Items->Add("1 1/2 L INKA"); CBB3->Items->Add("1 1/2 L COCA"); CBB3->Items->Add("1 L INKA"); CBB3->Items->Add("1 L COCA"); CBB3->Items->Add("1/2 L INKA"); CBB3->Items->Add("1/2 L COCA"); CBB3->Items->Add("1/2 L Fanta R."); CBB3->Items->Add("1/2 L Fanta N."); CBB3->Items->Add("1/2 L Pepsi"); CBB3->Items->Add("1/2 L Guaraná"); CBB3->Items->Add("Pepsi J."); CBB3->Items->Add("Esporade"); CBB3->Items->Add("Agua Cielo"); break; case 3: CBB3->Items->Add(L"Emoliente Vaso"); CBB3->Items->Add(L"Emoliente 1/2 Litro"); CBB3->Items->Add(L"Emoliente 1 Litro"); break; case 4: CBB3->Items->Add(L"Gelatina"); CBB3->Items->Add(L"Gelatina con flan"); break; case 5: CBB3->Items->Add(L"Arroz adicional"); CBB3->Items->Add(L"Porcion Papa"); CBB3->Items->Add(L"Porcion Arroz"); break; } CBB3->SelectedIndex = 0; textBox5->Focus(); } private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { if (dataGridView1->Rows->Count > 0) { double precio = 0.0; precio = Convert::ToDouble(dataGridView1->CurrentRow->Cells[3]->Value); T_Order -= precio; lblPrecio->Text = T_Order.ToString(); dataGridView1->Rows->RemoveAt(dataGridView1->CurrentRow->Index); } } private: System::Void checkBox1_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { if (checkBox1->Checked == true) { checkBox2->Checked = false; TBdireccion->Enabled = true; CBB1->Enabled = true; CBB1->SelectedIndex = 0; label2->Visible = true; label5->Visible = true; textBox1->Enabled = true; } else { checkBox2->Checked = true; } } private: System::Void checkBox2_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { if (checkBox2->Checked == true) { checkBox1->Checked = false; TBdireccion->Text = ""; TBdireccion->Enabled = false; CBB1->SelectedIndex = -1; CBB1->Enabled = false; label2->Visible = false; label5->Visible = false; textBox1->Enabled = false; } else { checkBox1->Checked = true; } } private: System::Void checkBox4_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void checkBox3_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void CBB3_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { textBox5->Focus(); } private: void Devolver_Stock(int ID) { CargarRegistros("Update Product Set UnitInStock = UnitInStock+ t.Quantity from Product p, t1 t where p.ProductID = t.ProductID and t.OrderID =" + ID.ToString()); } private: System::Void btnRegist_Click(System::Object^ sender, System::EventArgs^ e) { if (checkBox1->Checked == true) { if ( (TBcliente->Text == "") || (TBcel->Text == "") || (TBdireccion->Text == "") || (richTBcomment->Text == "") || (textBox1->Text == "") || (dataGridView1->Rows->Count == 0) ) { MessageBox::Show("Por favor verifique si ingresó todos los datos","Mensaje",MessageBoxButtons::OK, MessageBoxIcon::Information); } else { String^nombre; int idO; int i = 0; try { //el mejor caso CargarRegistros("Insert into Client values('" + TBcliente->Text + "'," + TBcel->Text + ",'" + TBdireccion->Text + "')"); //Buscar ID cliente antes de insertar su orden; SqlCommand^cmdDatabase = gcnew SqlCommand("Select IDENT_CURRENT('Client')", cn); cn->Open(); int idC = Convert::ToInt32(cmdDatabase->ExecuteScalar()); cn->Close(); CargarRegistros("Insert into Orders values('" + fecha_actual() + "','" + hora_actual() + "',null,'" + TBdireccion->Text + "',0,'" + richTBcomment->Text + "',0," + textBox1->Text + "," + (CBB1->SelectedIndex + 1).ToString() + "," + idC.ToString() + ")"); //Buscar ID Orden antes de insertar sus productos; SqlCommand^cmdDatabase2 = gcnew SqlCommand("Select IDENT_CURRENT('Orders')", cn); cn->Open(); idO = Convert::ToInt32(cmdDatabase2->ExecuteScalar()); cn->Close(); int idP; double precio =0; int cantidad; for (; i < dataGridView1->Rows->Count; i++) { nombre = Convert::ToString(dataGridView1->Rows[i]->Cells[2]->Value); cantidad = Convert::ToInt32(dataGridView1->Rows[i]->Cells[1]->Value); idP = Convert::ToInt32(dataGridView1->Rows[i]->Cells[0]->Value); precio = Convert::ToDouble (dataGridView1->Rows[i]->Cells[3]->Value) / Convert::ToDouble(dataGridView1->Rows[i]->Cells[1]->Value); //actualizamos stock CargarRegistros("Update Product Set UnitInStock = UnitInStock - " + cantidad.ToString() + " Where ProductID = " + idP.ToString() + " and CategoryID != 4 and CategoryID != 6"/* and UnitInStock >="+cantidad.ToString()*/); CargarRegistros("Insert into Order_Details values (" + (Convert::ToInt16(checkBox1->Checked)).ToString() + "," + (Convert::ToInt16(checkBox3->Checked)).ToString() + "," + (cantidad).ToString() + "," + precio.ToString()->Replace(",",".") + "," + idO.ToString() + "," + idP.ToString() + ")"); Actualizar_DGV(); } } catch (Exception^e) { Actualizar_DGV(); MessageBox::Show("No hay stock disponible para "+nombre,"Mensaje",MessageBoxButtons::OK,MessageBoxIcon::Information); cn->Close(); Devolver_Stock(idO); CargarRegistros("Delete from Order_Details where Order_Details.OrderID = " + idO.ToString()); SqlCommand^cmdDatabase4 = gcnew SqlCommand("Select o.ClientID from Orders o where o.OrderID = " + idO.ToString(), cn); cn->Open(); int idC = Convert::ToInt32(cmdDatabase4->ExecuteScalar()); cn->Close(); //eliminamos orders CargarRegistros("Delete from Orders where Orders.OrderID = " + idO.ToString()); //eliminamos cliente CargarRegistros("Delete from Client where Client.ClientID = " + idC.ToString()); if(dataGridView2->Rows->Count>0 && i!= 0) dataGridView2->Rows->RemoveAt(dataGridView2->CurrentRow->Index); } } } else { String^nombre; int idO; int j = 0; if ( (TBcliente->Text == "") || (richTBcomment->Text == "") || (dataGridView1->Rows->Count == 0) ) { MessageBox::Show("Por favor verifique si ingresó todos los datos", "Mensaje", MessageBoxButtons::OK, MessageBoxIcon::Information); } else { try { //el mejor caso CargarRegistros("Insert into Client values('" + TBcliente->Text + "'," + ((TBcel->Text == "")? "null": TBcel->Text) + ",'" + TBdireccion->Text + "')"); //Buscar ID cliente antes de insertar su orden; SqlCommand^cmdDatabase3 = gcnew SqlCommand("Select IDENT_CURRENT('Client')", cn); cn->Open(); int idC = Convert::ToInt32(cmdDatabase3->ExecuteScalar()); cn->Close(); CargarRegistros("Insert into Orders values('" + fecha_actual() + "','" + hora_actual() + "',null,null,0.00,'" + richTBcomment->Text + "',0,0.00, null," + idC.ToString() + ")"); //Buscar ID Orden antes de insertar sus productos; SqlCommand^cmdDatabase4 = gcnew SqlCommand("Select IDENT_CURRENT('Orders')", cn); cn->Open(); idO = Convert::ToInt32(cmdDatabase4->ExecuteScalar()); cn->Close(); int idP; double precio =0.0; int cantidad; for (; j < dataGridView1->Rows->Count; j++) { nombre = Convert::ToString(dataGridView1->Rows[j]->Cells[2]->Value); cantidad = Convert::ToInt16(dataGridView1->Rows[j]->Cells[1]->Value); idP = Convert::ToInt32(dataGridView1->Rows[j]->Cells[0]->Value); precio = Convert::ToDouble(dataGridView1->Rows[j]->Cells[3]->Value) / Convert::ToDouble(dataGridView1->Rows[j]->Cells[1]->Value); //actualizamos stock CargarRegistros("Update Product Set UnitInStock = UnitInStock - " + cantidad.ToString() + " Where ProductID = " + idP.ToString()+" and CategoryID != 4 and CategoryID != 6"/* and UnitInStock >=" + cantidad.ToString()*/); CargarRegistros("Insert into Order_Details values (" + (Convert::ToInt16(checkBox1->Checked)).ToString() + "," + (Convert::ToInt16(checkBox3->Checked)).ToString() + "," + (cantidad).ToString() + "," + precio.ToString()->Replace(",",".")+ "," + idO.ToString() + "," + idP.ToString() + ")"); Actualizar_DGV(); } } catch (Exception^e) { Actualizar_DGV(); MessageBox::Show("No hay stock disponible para "+nombre , "Mensaje", MessageBoxButtons::OK, MessageBoxIcon::Information); cn->Close(); Devolver_Stock(idO); CargarRegistros("Delete from Order_Details where Order_Details.OrderID = " + idO.ToString()); SqlCommand^cmdDatabase4 = gcnew SqlCommand("Select o.ClientID from Orders o where o.OrderID = " + idO.ToString(), cn); cn->Open(); int idC = Convert::ToInt32(cmdDatabase4->ExecuteScalar()); cn->Close(); //eliminamos orders CargarRegistros("Delete from Orders where Orders.OrderID = " + idO.ToString()); //eliminamos cliente CargarRegistros("Delete from Client where Client.ClientID = " + idC.ToString()); if (dataGridView2->Rows->Count > 0 && j != 0) dataGridView2->Rows->RemoveAt(dataGridView2->CurrentRow->Index); } } } } private: System::Void BtnSearch_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { if (dataGridView2->Rows->Count > 0) { if (MessageBox::Show("Estás seguro que deseas eliminar la orden? Esta acción no se podrá deshacer", "Mensaje", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation) == System::Windows::Forms::DialogResult::Yes) { Devolver_Stock(Convert::ToInt32(dataGridView2->CurrentRow->Cells[0]->Value)); //eliminamos orders details CargarRegistros("Delete from Order_Details where Order_Details.OrderID = " + Convert::ToString(dataGridView2->CurrentRow->Cells[0]->Value)); SqlCommand^cmdDatabase4 = gcnew SqlCommand("Select o.ClientID from Orders o where o.OrderID = " + Convert::ToString(dataGridView2->CurrentRow->Cells[0]->Value), cn); cn->Open(); int idC = Convert::ToInt32(cmdDatabase4->ExecuteScalar()); cn->Close(); //eliminamos orders CargarRegistros("Delete from Orders where Orders.OrderID = " + Convert::ToString(dataGridView2->CurrentRow->Cells[0]->Value)); if (MessageBox::Show("Desea conservar los datos del cliente?", "Mensaje", MessageBoxButtons::YesNo, MessageBoxIcon::Information) == System::Windows::Forms::DialogResult::No) { //eliminamos cliente CargarRegistros("Delete from Client where Client.ClientID = " + idC.ToString()); } dataGridView2->Rows->RemoveAt(dataGridView2->CurrentRow->Index); } } } private: System::Void btnEdit_Click(System::Object^ sender, System::EventArgs^ e) { if (dataGridView2->Rows->Count > 0) { EditarOrden^form = gcnew EditarOrden(Convert::ToInt32(dataGridView2->CurrentRow->Cells[0]->Value)); form->Show(); } } private: System::Void Ordenes_MdiChildActivate(System::Object^ sender, System::EventArgs^ e) { } private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) { } private: System::Void timer1_Tick_1(System::Object^ sender, System::EventArgs^ e) { } private: System::Void Ordenes_MouseClick(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { } private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) { Actualizar_DGV(); TBcliente->Text = ""; TBcel->Text = ""; checkBox1->Checked = true; TBdireccion->Text = ""; richTBcomment->Text = ""; textBox1->Text = ""; checkBox3->Checked = false; CBB2->SelectedIndex = 0; textBox5->Text = ""; dataGridView1->Rows->Clear(); } }; }
[ "eduizarra2@hotmail.com" ]
eduizarra2@hotmail.com
77beafd3d01821d6661f4699f1200c1dd2dd39a4
3977c950bbb456a0f00e3c49b71af6bb03554119
/SFML/GameWindow.cpp
1b28383066c7a5182a015743cdedeb4b38b8f9f0
[]
no_license
justfuckit/SFML
897fc103a4db186488e29dabd6c1edeb03ab4820
720d0ed12d18d49855d8c826118f1c5cc79bd731
refs/heads/master
2020-04-06T07:05:05.466867
2016-09-01T15:25:00
2016-09-01T15:25:00
60,274,272
0
0
null
null
null
null
UTF-8
C++
false
false
1,000
cpp
#include "GameWindow.h" GameWindow::GameWindow() { cfg = ((BinaryFile<bfs::ConfigHead, bfs::EmptyBody>*)AssetsManager::getFile("config")); cfgHead = cfg->getHead(); openWindow(); } GameWindow::~GameWindow() { } void GameWindow::openWindow() { resoultionMultiplier = (cfgHead.fhd ? (float)1.5 : 1); if (cfgHead.fullscreen) window.create(VideoMode((int)(1280 * resoultionMultiplier), (int)(720 * resoultionMultiplier)), "Game Window", sf::Style::Fullscreen ); else window.create(VideoMode((int)(1280 * resoultionMultiplier), (int)(720 * resoultionMultiplier)), "Game Window"); window.setMouseCursorVisible(false); window.setFramerateLimit(60); } void GameWindow::changeFullscreen() { cfgHead.fullscreen = !cfgHead.fullscreen; cfg->setHead(cfgHead); cfg->save(); window.close(); openWindow(); } void GameWindow::changeResoultion() { cfgHead.fhd = !cfgHead.fhd; cfg->setHead(cfgHead); cfg->save(); window.close(); openWindow(); }
[ "marciniaczekbob@o2.pl" ]
marciniaczekbob@o2.pl
021452c3c7e3642b0deff7bef82a84dc4dc1a7b4
91301e4540e775ccbdaf2a6d7682cd7f60f6e8dc
/include/RollTest.h
7a8a4247a89551e0aa4958bd308746c5892ddf74
[]
no_license
Quantum-Entropy/HippocampusController
edf423d64b87325a4ceb5de3ebbb5a7d791c00f8
6c31c329486c77aff4d73949f67bf1efd4845c7f
refs/heads/master
2022-02-11T23:08:58.550543
2019-08-09T08:04:15
2019-08-09T08:04:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,956
h
#ifndef ROLL_TEST_H #define ROLL_TEST_H #include <ros/ros.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/TwistStamped.h> #include <geometry_msgs/Quaternion.h> #include <math.h> #include <Eigen/Eigen> #include <AbstractHippocampusController.h> using namespace std; using namespace Eigen; class RollTest: public AbstractHippocampusController{ private: // Setpoint variables Euler _sp_attitude; float _sp_thrust; float roll, pitch, yaw, thrust; void loadParameters(); bool resetTime; float startTime; float interval; public: float time; RollTest(const ros::NodeHandle& nh, const ros::NodeHandle& nh_private, double frequency); AttitudeSetpoint generateSetpoint(); }; //Constructor RollTest::RollTest(const ros::NodeHandle& nh, const ros::NodeHandle& nh_private, double frequency): //Call super class constructor AbstractHippocampusController(nh, nh_private, frequency) { RollTest::loadParameters(); roll = 0; pitch = 0; yaw = 0; thrust = 0; time = 0; resetTime = false; } //Generate the setpoint to publish AttitudeSetpoint RollTest::generateSetpoint(){ AttitudeSetpoint sp; RollTest::loadParameters(); if(resetTime){ time = 0.0; } if(time < startTime) { roll = 0; } else if(time < startTime + interval) { roll = 20 * M_PI/180; } else if(time < startTime + 2*interval) { roll = 0; } else if(time < startTime + 3*interval) { roll = 20 * M_PI/180; } else { roll = 0; } _sp_attitude.roll = roll; _sp_attitude.pitch = pitch; _sp_attitude.yaw = yaw; _sp_thrust = thrust; sp.set(_sp_attitude, _sp_thrust); return sp; } void RollTest::loadParameters(){ _nh_private.param<bool>("resetTime", resetTime, false); _nh_private.param<float>("startTime", startTime, 0.0); _nh_private.param<float>("interval", interval, 0.0); } #endif
[ "philipp.hastedt@gmail.com" ]
philipp.hastedt@gmail.com
427018d596fed6c5024b5a655ed9abcace092bb4
e8b6b1d47d1701ca214f61a2972cbdaa54efb6c5
/gameplay/character_idle.cpp
e455b41fa234f4215b692dac1d327f8cc4b28688
[]
no_license
josh255/base-pro-edition
8b3c90419c0b1b235d6560c29f6bd683a756d764
e2e72322e8f4b33dcd91af0bcd079e47420b0c3b
refs/heads/master
2023-05-29T11:02:21.242689
2015-01-09T03:19:20
2015-01-09T03:23:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,089
cpp
#include "headers.h" #include "character.h" Character::Idle::Idle(engine::IClump* clump, engine::AnimSequence* sequence, float blendTime, float animSpeed) : Character::Action( clump ) { _blendTime = blendTime; engine::IAnimationController* controller = _clump->getAnimationController(); // capture blend source controller->captureBlendSrc(); // reset animation mixer for( unsigned int i=0; i<engine::maxAnimationTracks; i++ ) { if( controller->getTrackAnimation( i ) ) controller->setTrackActivity( i, false ); } // setup animation sequence controller->setTrackAnimation( 0, sequence ); controller->setTrackSpeed( 0, animSpeed ); controller->setTrackWeight( 0, 1.0f ); controller->setTrackActivity( 0, true ); controller->resetTrackTime( 0 ); // update animation controller->advance( 0.0f ); // capture blend destination controller->captureBlendDst(); controller->blend( 0.0f ); } void Character::Idle::update(float dt) { updateAnimation( dt ); }
[ "martynas.janu@gmail.com" ]
martynas.janu@gmail.com
4730a8236540225bd8287368096fc1b2998c5fed
154ad9b7b26b5c52536bbd83cdaf0a359e6125c3
/content/child/resource_dispatcher.h
11485286edaa714b04f92a3442c19b8627ff9773
[ "BSD-3-Clause" ]
permissive
bopopescu/jstrace
6cc239d57e3a954295b67fa6b8875aabeb64f3e2
2069a7b0a2e507a07cd9aacec4d9290a3178b815
refs/heads/master
2021-06-14T09:08:34.738245
2017-05-03T23:17:06
2017-05-03T23:17:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,003
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading #ifndef CONTENT_CHILD_RESOURCE_DISPATCHER_H_ #define CONTENT_CHILD_RESOURCE_DISPATCHER_H_ #include <stdint.h> #include <deque> #include <map> #include <memory> #include <string> #include "base/containers/hash_tables.h" #include "base/macros.h" #include "base/memory/linked_ptr.h" #include "base/memory/shared_memory.h" #include "base/memory/weak_ptr.h" #include "base/single_thread_task_runner.h" #include "base/time/time.h" #include "content/common/content_export.h" #include "content/public/common/resource_type.h" #include "ipc/ipc_listener.h" #include "ipc/ipc_sender.h" #include "net/base/request_priority.h" #include "url/gurl.h" namespace net { struct RedirectInfo; } namespace content { class RequestPeer; class ResourceDispatcherDelegate; class ResourceRequestBodyImpl; class ResourceSchedulingFilter; struct ResourceResponseInfo; struct RequestInfo; struct ResourceRequest; struct ResourceRequestCompletionStatus; struct ResourceResponseHead; class SharedMemoryReceivedDataFactory; struct SiteIsolationResponseMetaData; struct SyncLoadResponse; // This class serves as a communication interface to the ResourceDispatcherHost // in the browser process. It can be used from any child process. // Virtual methods are for tests. class CONTENT_EXPORT ResourceDispatcher : public IPC::Listener { public: ResourceDispatcher( IPC::Sender* sender, scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner); ~ResourceDispatcher() override; // IPC::Listener implementation. bool OnMessageReceived(const IPC::Message& message) override; // Call this method to load the resource synchronously (i.e., in one shot). // This is an alternative to the StartAsync method. Be warned that this method // will block the calling thread until the resource is fully downloaded or an // error occurs. It could block the calling thread for a long time, so only // use this if you really need it! There is also no way for the caller to // interrupt this method. Errors are reported via the status field of the // response parameter. virtual void StartSync(const RequestInfo& request_info, ResourceRequestBodyImpl* request_body, SyncLoadResponse* response); // Call this method to initiate the request. If this method succeeds, then // the peer's methods will be called asynchronously to report various events. // Returns the request id. virtual int StartAsync(const RequestInfo& request_info, ResourceRequestBodyImpl* request_body, std::unique_ptr<RequestPeer> peer); // Removes a request from the |pending_requests_| list, returning true if the // request was found and removed. bool RemovePendingRequest(int request_id); // Cancels a request in the |pending_requests_| list. The request will be // removed from the dispatcher as well. virtual void Cancel(int request_id); // Toggles the is_deferred attribute for the specified request. virtual void SetDefersLoading(int request_id, bool value); // Indicates the priority of the specified request changed. void DidChangePriority(int request_id, net::RequestPriority new_priority, int intra_priority_value); void set_message_sender(IPC::Sender* sender) { DCHECK(sender); DCHECK(pending_requests_.empty()); message_sender_ = sender; } // This does not take ownership of the delegate. It is expected that the // delegate have a longer lifetime than the ResourceDispatcher. void set_delegate(ResourceDispatcherDelegate* delegate) { delegate_ = delegate; } // Remembers IO thread timestamp for next resource message. void set_io_timestamp(base::TimeTicks io_timestamp) { io_timestamp_ = io_timestamp; } void SetMainThreadTaskRunner( scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner) { main_thread_task_runner_ = main_thread_task_runner; } void SetResourceSchedulingFilter( scoped_refptr<ResourceSchedulingFilter> resource_scheduling_filter); private: friend class ResourceDispatcherTest; typedef std::deque<IPC::Message*> MessageQueue; struct PendingRequestInfo { PendingRequestInfo(std::unique_ptr<RequestPeer> peer, ResourceType resource_type, int origin_pid, const GURL& frame_origin, const GURL& request_url, bool download_to_file); ~PendingRequestInfo(); std::unique_ptr<RequestPeer> peer; ResourceType resource_type; // The PID of the original process which issued this request. This gets // non-zero only for a request proxied by another renderer, particularly // requests from plugins. int origin_pid; MessageQueue deferred_message_queue; bool is_deferred = false; // Original requested url. GURL url; // The security origin of the frame that initiates this request. GURL frame_origin; // The url of the latest response even in case of redirection. GURL response_url; bool download_to_file; std::unique_ptr<IPC::Message> pending_redirect_message; base::TimeTicks request_start; base::TimeTicks response_start; base::TimeTicks completion_time; linked_ptr<base::SharedMemory> buffer; scoped_refptr<SharedMemoryReceivedDataFactory> received_data_factory; std::unique_ptr<SiteIsolationResponseMetaData> site_isolation_metadata; int buffer_size; }; using PendingRequestMap = std::map<int, std::unique_ptr<PendingRequestInfo>>; // Helper to lookup the info based on the request_id. // May return NULL if the request as been canceled from the client side. PendingRequestInfo* GetPendingRequestInfo(int request_id); // Follows redirect, if any, for the given request. void FollowPendingRedirect(int request_id, PendingRequestInfo* request_info); // Message response handlers, called by the message handler for this process. void OnUploadProgress(int request_id, int64_t position, int64_t size); void OnReceivedResponse(int request_id, const ResourceResponseHead&); void OnReceivedCachedMetadata(int request_id, const std::vector<char>& data); void OnReceivedRedirect(int request_id, const net::RedirectInfo& redirect_info, const ResourceResponseHead& response_head); void OnSetDataBuffer(int request_id, base::SharedMemoryHandle shm_handle, int shm_size, base::ProcessId renderer_pid); void OnReceivedInlinedDataChunk(int request_id, const std::vector<char>& data, int encoded_data_length, int encoded_body_length); void OnReceivedData(int request_id, int data_offset, int data_length, int encoded_data_length, int encoded_body_length); void OnDownloadedData(int request_id, int data_len, int encoded_data_length); void OnRequestComplete( int request_id, const ResourceRequestCompletionStatus& request_complete_data); // Dispatch the message to one of the message response handlers. void DispatchMessage(const IPC::Message& message); // Dispatch any deferred messages for the given request, provided it is not // again in the deferred state. This method may mutate |pending_requests_|. void FlushDeferredMessages(int request_id); void ToResourceResponseInfo(const PendingRequestInfo& request_info, const ResourceResponseHead& browser_info, ResourceResponseInfo* renderer_info) const; base::TimeTicks ToRendererCompletionTime( const PendingRequestInfo& request_info, const base::TimeTicks& browser_completion_time) const; // Returns timestamp provided by IO thread. If no timestamp is supplied, // then current time is returned. Saved timestamp is reset, so following // invocations will return current time until set_io_timestamp is called. base::TimeTicks ConsumeIOTimestamp(); // Returns true if the message passed in is a resource related message. static bool IsResourceDispatcherMessage(const IPC::Message& message); // ViewHostMsg_Resource_DataReceived is not POD, it has a shared memory // handle in it that we should cleanup it up nicely. This method accepts any // message and determine whether the message is // ViewHostMsg_Resource_DataReceived and clean up the shared memory handle. static void ReleaseResourcesInDataMessage(const IPC::Message& message); // Iterate through a message queue and clean up the messages by calling // ReleaseResourcesInDataMessage and removing them from the queue. Intended // for use on deferred message queues that are no longer needed. static void ReleaseResourcesInMessageQueue(MessageQueue* queue); std::unique_ptr<ResourceRequest> CreateRequest( const RequestInfo& request_info, ResourceRequestBodyImpl* request_body, GURL* frame_origin); IPC::Sender* message_sender_; // All pending requests issued to the host PendingRequestMap pending_requests_; ResourceDispatcherDelegate* delegate_; // IO thread timestamp for ongoing IPC message. base::TimeTicks io_timestamp_; scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; scoped_refptr<ResourceSchedulingFilter> resource_scheduling_filter_; base::WeakPtrFactory<ResourceDispatcher> weak_factory_; DISALLOW_COPY_AND_ASSIGN(ResourceDispatcher); }; } // namespace content #endif // CONTENT_CHILD_RESOURCE_DISPATCHER_H_
[ "zzbthechaos@gmail.com" ]
zzbthechaos@gmail.com